函数式编程学习笔记

94 阅读1分钟

课程链接

Brian Lonsdorf:Professor Frisby Introduces Composable Functional JavaScript Professor Frisby Introduces Composable Functional JavaScript

课程1

Create linear data flow with container style types (Box)

const Box = x =>
({
  map: f => Box(f(x)),
  fold: f => f(x),
  inspect: () => `Box(${x})`
})

const nextCharForNumberString = str =>
  Box(str)
  .map(s => s.trim())
  .map(r => parseInt(r))
  .map(i => i + 1)
  .map(i => String.fromCharCode(i))
  .fold(c => c.toLowerCase())

const result = nextCharForNumberString('  64 ')

console.log(result)
  • Box 返回一个对象,对象里的方法又返回了Box 的值,所以可以链式调用