Created
March 21, 2017 17:18
-
-
Save blemoine/1a452319900cb8eda9a9f665a21e547e to your computer and use it in GitHub Desktop.
Lodash schortcuts in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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