Last active
April 28, 2023 05:58
-
-
Save yao3060/b36a559a310f67a427739f2cb6e83c3e to your computer and use it in GitHub Desktop.
Typed Array Pluck, Object Pluck, Array Chunk
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
/** | |
* @example ArrayPluck([{name: 'A}, {name: 'B'}], 'name') | |
*/ | |
function ArrayPluck<T, K extends keyof T>(arr: T[], key: K): T[K][] { | |
return arr.map(i => i[key]); | |
} | |
/** | |
* @example ObjectPluck({brand: "BMW", manufacturer:"BF", model: "750"}, ["manufacturer", "model"]); | |
*/ | |
function ObjectPluck<T, K extends keyof T>(o: T, propertyNames: K[]): T[K][] { | |
return propertyNames.map((n) => o[n]); | |
} | |
function ArrayChunk<T>(arr: T[], size: number): T[][] { | |
return Array.from({ length: Math.ceil(arr.length / size) }, (_: any, i: number) => | |
arr.slice(i * size, i * size + size) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment