Skip to content

Instantly share code, notes, and snippets.

@blemoine
Created March 21, 2017 17:18
Show Gist options
  • Save blemoine/1a452319900cb8eda9a9f665a21e547e to your computer and use it in GitHub Desktop.
Save blemoine/1a452319900cb8eda9a9f665a21e547e to your computer and use it in GitHub Desktop.
Lodash schortcuts in typescript
interface User {
firstName:string;
lastName:string;
age:number;
}
const user1= {firstName:"Georges",lastName:"Abitbol", age:43}
const user2 = { firstName: "Joel", lastName: "Hammond", age: 25 }
const arr: Array<User> = [user1, user2]
function pluck<A, P extends (keyof A)>(array: Array<A>, p: P): Array<A[P]> {
return array.map(a => a[p]);
}
//equivalent to _.map(arr, 'firstName')
const names:Array<string> = pluck(arr, 'firstName');
function filter<A, P extends (keyof A)>(array: Array<A>, predicate:{[K in P]:A[P]}): Array<A> {
return array.filter(a => {
for (let p in predicate) {
if (a[p] !== predicate[p]) {
return false;
}
}
return true;
});
}
filter(arr, { firstName: 'Georges' });
function find<A, P extends (keyof A)>(array: Array<A>, predicate: {[K in P]: A[P]}): A {
return array.find(a => {
for (let p in predicate) {
if (a[p] !== predicate[p]) {
return false;
}
}
return true;
});
}
find(arr, { firstName: 'Georges' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment