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

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.

主站蜘蛛池模板: 绿春县| 祥云县| 灌云县| 沙洋县| 娄烦县| 永昌县| 连州市| 丹阳市| 贵德县| 文成县| 遵义市| 徐汇区| 西安市| 玉环县| 阳朔县| 扎兰屯市| 自治县| 凤城市| 广宁县| 托里县| 理塘县| 岫岩| 上栗县| 安国市| 宜丰县| 凤城市| 鄂伦春自治旗| 涿州市| 长丰县| 金华市| 集贤县| 海门市| 定襄县| 嘉义县| 疏勒县| 通榆县| 德令哈市| 昂仁县| 榆中县| 县级市| 伊川县|