Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端需要知道的一些概念 #26

Open
kangkai124 opened this issue Jun 3, 2019 · 2 comments
Open

前端需要知道的一些概念 #26

kangkai124 opened this issue Jun 3, 2019 · 2 comments

Comments

@kangkai124
Copy link
Owner

如函数式编程,柯里化等。

@kangkai124
Copy link
Owner Author

kangkai124 commented Jun 3, 2019

命令式编程 vs 声明式编程

命令式,关注 how to do

声明式,关注 do what

const numbers = [1,2,3,4,5];

// 命令式
const doubleWithImp = [];
for(let i=0; i<numbers.length; i++) {
    const numberdouble = numbers[i] * 2;
    doubleWithImp.push(numberdouble)
}

// 声明式
const doubleWithDec = numbers.map(number => number * 2);

console.log(doubleWithImp)
console.log(doubleWithDec)

什么是函数式编程

纯函数:没有副作用的函数,相同输入相同输出

不可变:不能改变数据

高阶函数:函数作为参数

柯里化

提前接收部分参数,延迟执行,不立即输出结果,返回一个接受剩余参数的函数。

const curry = (fn, arity = fn.length, ...args) => 
    arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args)

curry(Math.pow)(2)(10); // 1024
curry(Math.min, 3)(10)(50)(2); // 2

@kangkai124
Copy link
Owner Author

Curry 柯里化

函数柯里化,是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数。

原理:当接收的参数数量小于函数需要的参数时,就存着现有的参数,继续等待参数的进入。等参数数量足够的时候,就执行函数。

const curry = (fn, arity = fn.length, ...args) =>
  arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);

使用:

function sumFn (a, b, c) {
  return a + b + c
}
const sum = curry(sumFn)
sum(1)(2)(3)
sum(1)(2, 3)
sum(1, 2, 3)
function func1 (a,b,c) {
  console.log(a, b, c)
}

var func2 = func1.bind(null, 1)
func2(2, 3)
// 1 2 3

var func3 = func2.bind(null, 'a')
func3('b')
// 1 "a" "b"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant