JavaScript 的 管道组合
等级 5604 次按键
这实现了用于函数组合模式的pipe和compose。
JavaScript 代码
// pipe: 从左到右的函数组合// 值按顺序流经函数: f1 -> f2 -> f31const pipe = (...fns) => (value) =>2 fns.reduce((acc, fn) => fn(acc), value);3 // compose: 从右到左的函数组合(传统方式)// 值逆序流经函数: f3 <- f2 <- f14const compose = (...fns) => (value) =>5 fns.reduceRight((acc, fn) => fn(acc), value);6 // 简单的转换函数7const double = x => x * 2;8const addTen = x => x + 10;9const square = x => x * x;10 // pipe: 5 -> double -> addTen -> square// 5 -> 10 -> 20 -> 40011const piped = pipe(double, addTen, square);// compose(square, addTen, double)先应用double,再addTen,最后square// 相同结果: 5 -> 10 -> 20 -> 40012const composed = compose(square, addTen, double);13 14console.log("Piped:", piped(5));15console.log("Composed:", composed(5));16 // 实际示例: 名称处理管道17const processName = pipe( // 去掉首尾空格18 str => str.trim(), // 全部转为小写: "john doe"19 str => str.toLowerCase(), // 将每个单词的首字母大写: "John Doe"20 str => str.split(" ").map(w => w[0].toUpperCase() + w.slice(1)).join(" ")21);22console.log(processName(" john DOE "));运行结果
Piped: 400 Composed: 400 John Doe
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 JavaScript 代码中需要输入的符号及其出现次数。
(× 26)× 26=× 21.× 18>× 13,× 12;× 11"× 10:× 2*× 2