Skip to content

Commit a57f339

Browse files
committed
Add fromArray()
1 parent 3ac8c98 commit a57f339

File tree

5 files changed

+76
-1
lines changed

5 files changed

+76
-1
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Changelog
22

3+
## 1.0.1 (DEV)
4+
5+
- Add: `fromArray()`;
6+
37
## 1.0.0 (2022-06-27)
48

59
- Initial release.

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,29 @@ findKey(input, (_, k) => k === k.toUpperCase());
191191

192192
See also `find()`.
193193

194+
### `fromArray()`
195+
196+
```ts
197+
fromArray(
198+
array: readonly T[],
199+
calcKey: (item: T) => K,
200+
): ReadonlyMap<K, T>
201+
```
202+
203+
Creates a map from simple array of items, calculating corresponding key for
204+
every item with the given callback `calcKey()`.
205+
206+
```ts
207+
fromArray([1, 2, 3], (v) => v * 10)
208+
// => Map(3) { 10 => 1, 20 => 2, 30 => 3 }
209+
```
210+
211+
This is a shortcut for commonly used operation:
212+
213+
```js
214+
new Map(array.map(v => [calcKey(v), v]))
215+
```
216+
194217
### `getOr()`
195218

196219
```ts

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@cubux/readonly-map",
3-
"version": "1.0.0",
3+
"version": "1.0.1-dev",
44
"description": "Functions to work with read-only maps",
55
"keywords": [
66
"map",

src/fromArray.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Creates a map from simple array of items, calculating corresponding key for
3+
* every item with the given callback `calcKey()`.
4+
*
5+
* ```ts
6+
* fromArray([1, 2, 3], (v) => v * 10)
7+
* // => Map(3) { 10 => 1, 20 => 2, 30 => 3 }
8+
* ```
9+
*
10+
* This is a shortcut for commonly used operation:
11+
*
12+
* ```js
13+
* new Map(array.map(v => [calcKey(v), v]))
14+
* ```
15+
*
16+
* @param array
17+
* @param calcKey
18+
*/
19+
function fromArray<T, K>(
20+
array: readonly T[],
21+
calcKey: (item: T) => K,
22+
): ReadonlyMap<K, T> {
23+
return new Map(array.map(item => [calcKey(item), item]));
24+
}
25+
26+
export default fromArray;

test/fromArray.test.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import fromArray from '../src/fromArray';
2+
3+
it('creates map', () => {
4+
interface T {
5+
id: number;
6+
name: string;
7+
}
8+
9+
const array: T[] = [
10+
{ id: 10, name: 'John Random' },
11+
{ id: 20, name: 'Pupkin Vasily' },
12+
{ id: 30, name: 'Lu Lu' },
13+
];
14+
15+
expect(fromArray(array, v => v.id)).toEqual(
16+
new Map([
17+
[10, { id: 10, name: 'John Random' }],
18+
[20, { id: 20, name: 'Pupkin Vasily' }],
19+
[30, { id: 30, name: 'Lu Lu' }],
20+
]),
21+
);
22+
});

0 commit comments

Comments
 (0)