From 1afd9588046c6c46ca608a13f73ff23d42788aed Mon Sep 17 00:00:00 2001 From: Harlan Wilton Date: Wed, 7 Sep 2022 18:31:30 +1000 Subject: [PATCH] fix: allow unpack to unpack deeply --- src/types.ts | 35 ++++++++--------------------------- src/unpack/array.ts | 19 +++++++++++++------ 2 files changed, 21 insertions(+), 33 deletions(-) diff --git a/src/types.ts b/src/types.ts index 4934e97..4d2362d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,31 +1,12 @@ -export interface PackArrayOptions[]> { - key: keyof T[number] | (keyof T[number])[] - value: keyof T[number] | (keyof T[number])[] +type Arrayable = T | T[] + +export interface PackArrayOptions[]> extends PackOptions { + key?: Arrayable + value?: Arrayable } export interface PackOptions> { - key: keyof T | (keyof T)[] - value: keyof T | (keyof T)[] + key?: Arrayable + value?: Arrayable + resolveKey?: (key: keyof T) => string } - -// export type ReverseMap> = { -// [P in T[keyof T]]: { -// [K in keyof T]: T[K] extends P ? K : never -// }[keyof T] -// } -// type Prepend = [T, ...U] -// type Keys> = Keys_ -// type Keys_, U extends PropertyKey[]> = -// { -// [P in keyof T]: {} extends Omit ? [P] : Prepend, U>> -// }[keyof T] -// export interface ObjectKeys> { -// key: Keys>[0] -// value: Keys>[1] -// } -// export type GetObjectKeys> = Keys>>[0] -// export type FirstObjectKeyFiltered, Filter extends keyof Data> = Keys>>[0] -// export type ObjectKeyValue, K extends keyof Data, V extends keyof Data> = Record< -// FirstObjectKeyFiltered, -// FirstObjectKeyFiltered -// > diff --git a/src/unpack/array.ts b/src/unpack/array.ts index 1e92df7..b66dd5d 100644 --- a/src/unpack/array.ts +++ b/src/unpack/array.ts @@ -1,23 +1,30 @@ export interface UnpackArrayOptions { - key: string - value: string + key: string | ((key: string) => string) + value: string | ((key: string) => string) resolveKeyData?: (key: string) => string resolveValueData?: (value: unknown) => unknown } export function unpackToArray(input: Record, options: UnpackArrayOptions): Record[] { const unpacked: any[] = [] - options = options || { key: 'name', value: 'content' } const kFn = options.resolveKeyData || ((k: string) => k) const vFn = options.resolveValueData || ((k: string) => k) for (const [k, v] of Object.entries(input)) { unpacked.push(...(Array.isArray(v) ? v : [v]).map((i) => { + // handle nested objects + if (typeof i === 'object') + i = unpackToArray(i!, options) + const val = vFn(i) + + if (Array.isArray(val)) + return val + return { - [options.key]: kFn(k), - [options.value]: vFn(i), + [typeof options.key === 'function' ? options.key(k) : options.key]: kFn(k), + [typeof options.value === 'function' ? options.value(k) : options.value]: val, } - })) + }).flat()) } return unpacked }