Skip to content

Commit b083e66

Browse files
author
eva
committed
added toMap
1 parent d640181 commit b083e66

File tree

4 files changed

+54
-0
lines changed

4 files changed

+54
-0
lines changed

src/keyed-array/keyed-array.spec.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,23 @@ describe('KeyedArray', () => {
7272
expect(keyedHelper.deleteByKey(someArray, 'Russia')).toEqual(someArray);
7373
});
7474
});
75+
76+
describe('toMap', () => {
77+
it('works', () => {
78+
expect(keyedHelper.toMap(someArray)).toEqual({
79+
Italy: {
80+
accountId: 'Italy',
81+
score: 3,
82+
},
83+
UK: {
84+
accountId: 'UK',
85+
score: 1,
86+
},
87+
USA: {
88+
accountId: 'USA',
89+
score: 2,
90+
},
91+
});
92+
});
93+
});
7594
});

src/keyed-array/keyed-array.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,18 @@ export class KeyedArray<T> {
3636
return SimpleArray.find(array, x => getKey(x) === key);
3737
}
3838

39+
public toMap(array: T[]): Record<string, T> {
40+
const { getKey } = this;
41+
const myMap: { [k: string]: T } = {};
42+
for (const a of array) {
43+
const key = getKey(a);
44+
if (myMap[key]) continue;
45+
myMap[key] = a;
46+
}
47+
48+
return myMap;
49+
}
50+
3951
public checkValid(array: T[], what?: string, where?: string): void {
4052
const { getKey } = this;
4153

src/named-array/named-array.spec.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,25 @@ describe('NamedArray', () => {
176176
});
177177
});
178178

179+
describe('#toMap', () => {
180+
it('works', () => {
181+
expect(NamedArray.toMap(someArray)).toEqual({
182+
Italy: {
183+
name: 'Italy',
184+
score: 3,
185+
},
186+
UK: {
187+
name: 'UK',
188+
score: 1,
189+
},
190+
USA: {
191+
name: 'USA',
192+
score: 2,
193+
},
194+
});
195+
});
196+
});
197+
179198
describe('synchronize', () => {
180199
function valueEqual(a: any, b: any) {
181200
return a.value === b.value;

src/named-array/named-array.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,10 @@ export class NamedArray {
117117
return KEYED_ARRAY.get(array, name);
118118
}
119119

120+
static toMap<T extends NamedArray>(array: T[]): Record<string, T> {
121+
return KEYED_ARRAY.toMap(array);
122+
}
123+
120124
static containsByName<T extends Nameable>(array: T[], name: string): boolean {
121125
return SimpleArray.contains(array, x => x.name === name);
122126
}

0 commit comments

Comments
 (0)