Skip to content

Commit

Permalink
Add fromArray()
Browse files Browse the repository at this point in the history
  • Loading branch information
Vovan-VE committed Aug 4, 2022
1 parent 3ac8c98 commit a57f339
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## 1.0.1 (DEV)

- Add: `fromArray()`;

## 1.0.0 (2022-06-27)

- Initial release.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,29 @@ findKey(input, (_, k) => k === k.toUpperCase());

See also `find()`.

### `fromArray()`

```ts
fromArray(
array: readonly T[],
calcKey: (item: T) => K,
): ReadonlyMap<K, T>
```

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
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
26 changes: 26 additions & 0 deletions src/fromArray.ts
Original file line number Diff line number Diff line change
@@ -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<T, K>(
array: readonly T[],
calcKey: (item: T) => K,
): ReadonlyMap<K, T> {
return new Map(array.map(item => [calcKey(item), item]));
}

export default fromArray;
22 changes: 22 additions & 0 deletions test/fromArray.test.ts
Original file line number Diff line number Diff line change
@@ -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' }],
]),
);
});

0 comments on commit a57f339

Please sign in to comment.