函数式编程

函数是一等公民

函数是一等公民的表现:

  1. 函数可以储存为变量
let four = () => 4
  1. 函数可作为数组的一个元素
let four = [4, () => 4]
  1. 函数可作为对象的成员
let four = {num: 4, func: () => 4}
  1. 函数可以在使用时直接创造出来
let four = 2 + (() => 2)()
  1. 函数可作为参数传递给另一个函数
let four = (num, f) => num + f()

four(2, () => 2)
  1. 函数可以被另一函数返回
let four = () => () => 4

其实,满足第5点或第6点的函数被称为 高阶函数

Applicative编程

Applicative编程是函数式编程的一部分(特殊的函数式编程形式),其典型的代表就是 mapreduce 以及 filter 函数。

Applicative编程的其它实例:

  • reduceRight
  • find
  • reject
  • all
  • any
  • sortBy | groupBy | countBy

函数柯里化

函数柯里化可以保存某些需要多次调用的操作,还可以将多个参数分割,每次只传递一个参数,让函数看起来就像是在一步步的操作数据。

一阶柯里化:

function curry(func) {
    return arg => func(arg)
}

使用示例:

const add3 = curry((a) => a+3)
add3(2)

二阶柯里化(这里选择从右到左):

function curry2(func) {
  return first => last => func(last, first);
}

使用示例:

const add = curry2((a, b) => a+b)
add(2)(3) // 5
add('curry!')('hello ') // 'hello curry!'

三阶柯里化(从右到左调用参数):

function curry3(func) {
  return first => middle => last => func(last, middle, first);
}

使用示例:

const splice = curry3((a, b, c) => c + b + a)
splice(2)(3)(4) // 9
splice('hello ')('curry')('!') // 'hello curry!'

curry => partial => compose

递归

相互递归

实现判断奇偶性就是一个相互递归的很好的例子:

function odd(n) {
    if(n === 0) return false;
    return even(Math.abs(n) - 1);
}
function even(n) {
    if(n === 0) return true;
    return odd(Math.abs(n) - 1);
}

递归实现深克隆

简单版本:

function deepClone(obj) {
    if(x == null || typeof obj !== 'object') {
        return obj;
    }
    let temp = new obj.constructor();
    for(let key in obj) 
        if(obj.hasOwnProperty(key))
            temp[key] = deepClone(obj[key])
    return temp;
}

JS函数式库

可编译为js的函数式编程语言

0%