-
-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(associative): add objectFromKeys()
- Loading branch information
1 parent
1d6d661
commit 0a6ba5f
Showing
2 changed files
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>>{} | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters