官术网_书友最值得收藏!

Functions as first-class citizens

It is common to find mentions of functions as first-class citizens in the FP literature. We say that a function is a first-class citizen when it can do everything that a variable can do, which means that functions can be passed to other functions as an argument. For example, the following function takes a function as its second argument:

function find<T>(arr: T[], filter: (i: T) => boolean) {
return arr.filter(filter);
}

find(heroes, (h) => h.name === "Spiderman");

Or, it is returned by another function. For example, the following function takes a function as its only argument and returns a function:

function find<T>(filter: (i: T) => boolean) {
return (arr: T[]) => {
return arr.filter(filter);
}
}

const findSpiderman = find((h: Hero) => h.name === "Spiderman");
const spiderman = findSpiderman(heroes);

Functions can also be assigned to variables. For example, in the preceding code snippet, we assigned the function returned by the find function to a variable named findSpiderman:

const findSpiderman = find((h: Hero) => h.name === "SPiderman");

Both JavaScript and TypeScript treat functions as first-class citizens.

主站蜘蛛池模板: 青浦区| 龙井市| 龙川县| 延庆县| 思茅市| 柳江县| 常宁市| 长岛县| 方正县| 得荣县| 岢岚县| 岑溪市| 诸暨市| 天柱县| 姜堰市| 琼海市| 浙江省| 鄯善县| 望都县| 信宜市| 手游| 和龙市| 夏津县| 长葛市| 营山县| 神木县| 嘉善县| 临江市| 仙居县| 凤阳县| 龙游县| 台安县| 古浪县| 林芝县| 合川市| 洞口县| 汝南县| 响水县| 铜山县| 外汇| 曲阳县|