728x90
function filter<T>(array: T[], f: (item: T) => boolean): T[] {
let result = [];
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < array.length; i++) {
let item = array[i];
if (f(item)) {
result.push(item);
}
}
return result;
}
type Filter<T> = { (array: T[], f: (iter: T) => boolean): T[] };
let names = [{ ์ด๋ฆ: "smith" }, { ์ด๋ฆ: "kate" }, { ์ด๋ฆ: "max" }];
//1. T๋ number๋ก ํ์ ๋จ
console.log(filter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], (_) => _ > 5)); //[ 6, 7, 8, 9, 10 ]
//2. T๋ string์ผ๋ก ํ์ ๋จ
console.log(filter(["a", "b", "ab", "b", "c"], (_) => _ !== "b")); //[ 'a', 'ab', 'c' ]
//3. T๋ {์ด๋ฆ:string}์ผ๋ก ํ์ ๋จ
console.log(filter(names, (_) => _.์ด๋ฆ.endsWith("h"))); //[ { '์ด๋ฆ': 'smith' } ]
728x90