|
| 1 | +/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 2 | +interface DeepMapContext { |
| 3 | + mapper: (v: any) => unknown; |
| 4 | + processed: Map<unknown, unknown>; |
| 5 | + cachedForTypes: Set<CacheForType>; |
| 6 | +} |
| 7 | + |
| 8 | +function deepMapImpl(value: unknown, ctx: DeepMapContext) { |
| 9 | + if (ctx.processed.has(value)) return ctx.processed.get(value); |
| 10 | + |
| 11 | + if (Array.isArray(value)) { |
| 12 | + const res: unknown[] = []; |
| 13 | + ctx.processed.set(value, res); |
| 14 | + res.push(...value.map((v) => deepMapImpl(v, ctx))); |
| 15 | + return res; |
| 16 | + } |
| 17 | + |
| 18 | + if (typeof value === "object" && value !== null) { |
| 19 | + const res = {}; |
| 20 | + ctx.processed.set(value, res); |
| 21 | + |
| 22 | + for (const k of Reflect.ownKeys(value)) { |
| 23 | + const v: unknown = Reflect.get(value, k); |
| 24 | + const r = deepMapImpl(v, ctx); |
| 25 | + Reflect.set(res, k, r); |
| 26 | + } |
| 27 | + |
| 28 | + return res; |
| 29 | + } |
| 30 | + |
| 31 | + const res = ctx.mapper(value); |
| 32 | + |
| 33 | + if ( |
| 34 | + (value === null && ctx.cachedForTypes.has("null")) || |
| 35 | + ctx.cachedForTypes.has(typeof value as never) |
| 36 | + ) { |
| 37 | + ctx.processed.set(value, res); |
| 38 | + } |
| 39 | + |
| 40 | + return res; |
| 41 | +} |
| 42 | + |
| 43 | +export type CacheForType = |
| 44 | + | "string" |
| 45 | + | "number" |
| 46 | + | "symbol" |
| 47 | + | "function" |
| 48 | + | "undefined" |
| 49 | + | "null" |
| 50 | + | "bigint" |
| 51 | + | "boolean"; |
| 52 | + |
| 53 | +export interface DeepMapOptions { |
| 54 | + cacheForTypes?: Iterable<CacheForType>; |
| 55 | +} |
| 56 | + |
| 57 | +export type AnyObjectOrArray = Record<string, unknown> | any[]; |
| 58 | + |
| 59 | +export type DeepMappedByMapper< |
| 60 | + T, |
| 61 | + M extends (v: Exclude<T, AnyObjectOrArray>) => unknown, |
| 62 | +> = T extends AnyObjectOrArray |
| 63 | + ? { [K in keyof T]: DeepMappedByMapper<T[K], M> } |
| 64 | + : M extends (v: T) => infer R |
| 65 | + ? R |
| 66 | + : unknown; |
| 67 | + |
| 68 | +export type DeepMapped<TV, TVR> = TV extends AnyObjectOrArray |
| 69 | + ? { [K in keyof TV]: DeepMapped<TV[K], TVR> } |
| 70 | + : TVR; |
| 71 | + |
| 72 | +export function deepMap<TV, TVR>( |
| 73 | + value: TV, |
| 74 | + mapper: ( |
| 75 | + v: Exclude< |
| 76 | + | TV |
| 77 | + | (TV extends (infer TI)[] |
| 78 | + ? TI |
| 79 | + : TV extends Record<PropertyKey, infer TP> |
| 80 | + ? TP |
| 81 | + : never), |
| 82 | + AnyObjectOrArray |
| 83 | + >, |
| 84 | + ) => TVR, |
| 85 | + options?: DeepMapOptions, |
| 86 | +): DeepMapped<TV, TVR> { |
| 87 | + return deepMapImpl(value, { |
| 88 | + mapper, |
| 89 | + cachedForTypes: new Set(options?.cacheForTypes), |
| 90 | + processed: new Map(), |
| 91 | + }) as never; |
| 92 | +} |
0 commit comments