JavaScript 与函数式编程

Created at 2020-01-01

前言

看到一些 JavaScript 的代码,突然很想做一个函数式编程的分享,不是什么伟大的技巧,把握了函数式编程的一些思想,有助于我们写出更好理解的代码。能不能减少 bug 我不知道,反正给人看,应该是更好理解的。

参考链接

What is functional programming?

  • 一种编程范式
  • 一种代码风格
  • 一种潮流观念

看一个例子

var points = [0, 50, 0, 100, 0, 200] // 表示一条 polyline

for (var length = points.length, i = length - 2; i >= 2; i -= 2) {
  var x = (points[i - 2] + points[i]) / 2
  var y = (points[i + 1] + points[i - 1]) / 2

  points.splice(i, 0, x, y) // 给现有 polyline 两点之间加点
}

console.log(points)

JavaScript es6 函数式编程入门经典

  1. currypartial application
  2. compose、pipe
  3. functor
  4. monad

function pipe(...fns) {
    return (arg) => {
        for (let fn of fns) arg = fn(arg)
        return arg
    }
}

let test = pipe((v) => v + 2, (v) => v * 2)
test(2)

In mathematics, specifically category theory, a functor is a mapping between categories. 

In functional programming, monads are a way to structure computations as a sequence of steps, where each step not only produces a value but also some extra information about the computation, such as a potential failure, non-determinism, or side effect. 

“Once you understand monads, you immediately become incapable of explaining them to anyone else” Lady Monadgreen’s curse ~ Gilad Bracha (used famously by Douglas Crockford)

Algebraic Effects

Hope you guys enjoyed😊