Skip to content

Commit 89a94e8

Browse files
authored
Merge pull request #25 from silvermine/jrthomer/pluck
feat: pluck
2 parents e597994 + 78679f7 commit 89a94e8

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,5 @@ export * from './utils/is-undefined';
2222

2323
export * from './utils/chunk';
2424
export * from './utils/flatten';
25+
export * from './utils/pluck';
2526
export * from './utils/delay';

src/utils/pluck.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export function pluck<T, K extends keyof T>(sources: T[], key: K): T[K][] {
2+
return sources.map((o) => {
3+
return o[key];
4+
});
5+
}

tests/utils/pluck.test.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { expect } from 'chai';
2+
import { pluck } from '../../src';
3+
4+
interface Location {
5+
city: string;
6+
state: string;
7+
}
8+
9+
interface Person {
10+
firstName: string;
11+
middleInitial?: string;
12+
lastName: string;
13+
age: number;
14+
location?: Location;
15+
}
16+
17+
const PEOPLE: Person[] = [
18+
{ firstName: 'John', lastName: 'Doe', age: 21 },
19+
{ firstName: 'Jane', lastName: 'Doe', age: 22, location: { city: 'New York', state: 'NY' } },
20+
{ firstName: 'Wile', middleInitial: 'E', lastName: 'Coyote', age: 12, location: { city: 'Tucson', state: 'AZ' } },
21+
{ firstName: 'Road', lastName: 'Runner', age: 12, location: { city: 'Tucson', state: 'AZ' } },
22+
];
23+
24+
describe('pluck', () => {
25+
26+
it('works correctly', () => {
27+
// Explicitly type the results so we can make sure that our types on pluck are
28+
// implemented correctly.
29+
const firstNames: string[] = pluck(PEOPLE, 'firstName'),
30+
ages: number[] = pluck(PEOPLE, 'age'),
31+
middleInitials: (string | undefined)[] = pluck(PEOPLE, 'middleInitial'),
32+
locations: (Location | undefined)[] = pluck(PEOPLE, 'location');
33+
34+
expect(firstNames).to.eql([ 'John', 'Jane', 'Wile', 'Road' ]);
35+
expect(ages).to.eql([ 21, 22, 12, 12 ]);
36+
expect(middleInitials).to.eql([ undefined, undefined, 'E', undefined ]);
37+
expect(locations).to.eql([
38+
undefined,
39+
{ city: 'New York', state: 'NY' },
40+
{ city: 'Tucson', state: 'AZ' },
41+
{ city: 'Tucson', state: 'AZ' },
42+
]);
43+
});
44+
45+
});

0 commit comments

Comments
 (0)