diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c56be5..a656d0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 1.0.1 (DEV) + +- Add: `fromArray()`; + ## 1.0.0 (2022-06-27) - Initial release. diff --git a/README.md b/README.md index 555dbeb..f66fdda 100644 --- a/README.md +++ b/README.md @@ -191,6 +191,29 @@ findKey(input, (_, k) => k === k.toUpperCase()); See also `find()`. +### `fromArray()` + +```ts +fromArray( + array: readonly T[], + calcKey: (item: T) => K, +): ReadonlyMap +``` + +Creates a map from simple array of items, calculating corresponding key for +every item with the given callback `calcKey()`. + +```ts +fromArray([1, 2, 3], (v) => v * 10) +// => Map(3) { 10 => 1, 20 => 2, 30 => 3 } +``` + +This is a shortcut for commonly used operation: + +```js +new Map(array.map(v => [calcKey(v), v])) +``` + ### `getOr()` ```ts diff --git a/package.json b/package.json index c3db394..1b32bfe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@cubux/readonly-map", - "version": "1.0.0", + "version": "1.0.1-dev", "description": "Functions to work with read-only maps", "keywords": [ "map", diff --git a/src/fromArray.ts b/src/fromArray.ts new file mode 100644 index 0000000..0d524e7 --- /dev/null +++ b/src/fromArray.ts @@ -0,0 +1,26 @@ +/** + * Creates a map from simple array of items, calculating corresponding key for + * every item with the given callback `calcKey()`. + * + * ```ts + * fromArray([1, 2, 3], (v) => v * 10) + * // => Map(3) { 10 => 1, 20 => 2, 30 => 3 } + * ``` + * + * This is a shortcut for commonly used operation: + * + * ```js + * new Map(array.map(v => [calcKey(v), v])) + * ``` + * + * @param array + * @param calcKey + */ +function fromArray( + array: readonly T[], + calcKey: (item: T) => K, +): ReadonlyMap { + return new Map(array.map(item => [calcKey(item), item])); +} + +export default fromArray; diff --git a/test/fromArray.test.ts b/test/fromArray.test.ts new file mode 100644 index 0000000..5e4111a --- /dev/null +++ b/test/fromArray.test.ts @@ -0,0 +1,22 @@ +import fromArray from '../src/fromArray'; + +it('creates map', () => { + interface T { + id: number; + name: string; + } + + const array: T[] = [ + { id: 10, name: 'John Random' }, + { id: 20, name: 'Pupkin Vasily' }, + { id: 30, name: 'Lu Lu' }, + ]; + + expect(fromArray(array, v => v.id)).toEqual( + new Map([ + [10, { id: 10, name: 'John Random' }], + [20, { id: 20, name: 'Pupkin Vasily' }], + [30, { id: 30, name: 'Lu Lu' }], + ]), + ); +});