Skip to content

Commit

Permalink
added toMap
Browse files Browse the repository at this point in the history
  • Loading branch information
eva committed Aug 15, 2019
1 parent d640181 commit b083e66
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/keyed-array/keyed-array.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,23 @@ describe('KeyedArray', () => {
expect(keyedHelper.deleteByKey(someArray, 'Russia')).toEqual(someArray);
});
});

describe('toMap', () => {
it('works', () => {
expect(keyedHelper.toMap(someArray)).toEqual({
Italy: {
accountId: 'Italy',
score: 3,
},
UK: {
accountId: 'UK',
score: 1,
},
USA: {
accountId: 'USA',
score: 2,
},
});
});
});
});
12 changes: 12 additions & 0 deletions src/keyed-array/keyed-array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,18 @@ export class KeyedArray<T> {
return SimpleArray.find(array, x => getKey(x) === key);
}

public toMap(array: T[]): Record<string, T> {
const { getKey } = this;
const myMap: { [k: string]: T } = {};
for (const a of array) {
const key = getKey(a);
if (myMap[key]) continue;
myMap[key] = a;
}

return myMap;
}

public checkValid(array: T[], what?: string, where?: string): void {
const { getKey } = this;

Expand Down
19 changes: 19 additions & 0 deletions src/named-array/named-array.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,25 @@ describe('NamedArray', () => {
});
});

describe('#toMap', () => {
it('works', () => {
expect(NamedArray.toMap(someArray)).toEqual({
Italy: {
name: 'Italy',
score: 3,
},
UK: {
name: 'UK',
score: 1,
},
USA: {
name: 'USA',
score: 2,
},
});
});
});

describe('synchronize', () => {
function valueEqual(a: any, b: any) {
return a.value === b.value;
Expand Down
4 changes: 4 additions & 0 deletions src/named-array/named-array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ export class NamedArray {
return KEYED_ARRAY.get(array, name);
}

static toMap<T extends NamedArray>(array: T[]): Record<string, T> {
return KEYED_ARRAY.toMap(array);
}

static containsByName<T extends Nameable>(array: T[], name: string): boolean {
return SimpleArray.contains(array, x => x.name === name);
}
Expand Down

0 comments on commit b083e66

Please sign in to comment.