JavaScript 的 管道函数

等级 5388 次按键

管道创建一个函数管道,从左到右通过多个转换处理数据。

JavaScript 代码

// 使用reduce的管道函数(从左到右)
// 与从右到左的compose不同
1const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
2
// 定义单独的转换函数
3const trim = s => s.trim();
4const toLowerCase = s => s.toLowerCase();
// split把字符串拆成单词数组
5const split = s => s.split(" ");
// join用"-"把单词重新连接起来
6const join = arr => arr.join("-");
7
// 通过管道转换创建slugify函数
// 数据流: trim -> toLowerCase -> split -> join
8const slugify = pipe(trim, toLowerCase, split, join);
9
// " Hello World " -> "hello-world"
10console.log(slugify(" Hello World "));
// "JavaScript Is Fun" -> "javascript-is-fun"
11console.log(slugify("JavaScript Is Fun"));
// " ONE TWO THREE " -> "one-two-three"
12console.log(slugify(" ONE TWO THREE "));

运行结果

hello-world
javascript-is-fun
one-two-three
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 JavaScript 代码中需要输入的符号及其出现次数。

  • (× 16
  • )× 16
  • =× 13
  • .× 11
  • "× 10
  • ;× 9
  • >× 7
  • ,× 5
  • -× 1

JavaScript 等级 5 的更多代码示例

← 返回 JavaScript 打字练习