Skip to content

Commit

Permalink
feat(associative): add objectFromKeys()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Aug 21, 2023
1 parent 1d6d661 commit 0a6ba5f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
34 changes: 34 additions & 0 deletions packages/associative/src/from-keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { Fn } from "@thi.ng/api";
import { isFunction } from "@thi.ng/checks/is-function";

/**
* Similar to (but much faster than) `Object.fromEntries()`. Takes an array of
* property keys and an `init` value or function. If the latter, the `init`
* function is called for each key and its results are used as values. Otherwise
* the `init` value is used homogeneously for all keys.
*
* @example
* ```ts
* objectFromKeys(["a", "b", "c"], 1)
* // { a: 1, b: 1, c: 1 }
*
* objectFromKeys(["a", "b", "c"], () => [])
* // { a: [], b: [], c: [] }
*
* objectFromKeys(["a", "b", "c"], (k) => `${k}-${(Math.random()*100)|0}`)
* // { a: 'a-54', b: 'b-8', c: 'c-61' }
* ```
*
* @param keys
* @param init
*/
export const objectFromKeys = <K extends PropertyKey, V>(
keys: K[],
init: V | Fn<K, V>
) =>
keys.reduce(
isFunction(init)
? (acc, k) => ((acc[k] = init(k)), acc)
: (acc, k) => ((acc[k] = init), acc),
<Record<K, V>>{}
);
1 change: 1 addition & 0 deletions packages/associative/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from "./dissoc.js";
export * from "./empty.js";
export * from "./equiv-map.js";
export * from "./first.js";
export * from "./from-keys.js";
export * from "./hash-map.js";
export * from "./indexed.js";
export * from "./intersection.js";
Expand Down

0 comments on commit 0a6ba5f

Please sign in to comment.