pipe函数

接受一组函数Array[fn1, fn2, fn3, ...]作为参数, 前一个函数返回值作为后一个函数的参数

const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)

函数柯里化

const multiply = (a) => (b) => (c) => a*b*c;
multiply(2)(3)(4);
const multiply5 = multiply(5);

那么pipe函数使用方式 pipe(fn1, fn2, ...)(x)

ES5写法

"use strict";
var pipe = function pipe() {
  for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
    fns[_key] = arguments[_key];
  }
  return function (x) {
    return fns.reduce(function (v, f) {
      return f(v);
    }, x);
  };
};

promise版本

function pipePromise(...fns) {
  return function(x) {
    return fns.reduce((p, fn)=> {
      return p.then(fn)
    }, Promise.resolve(x))
  }
}

compose函数

ramdacompose函数例子如下

const classyGreeting = (firstName, lastName) => "The name's " + lastName + ", " + firstName + " " + lastName
const yellGreeting = R.compose(R.toUpper, classyGreeting);
yellGreeting('James', 'Bond'); //=> "THE NAME'S BOND, JAMES BOND"
 
R.compose(Math.abs, R.add(1), R.multiply(2))(-4) //=> 7

可以看出compose函数与pipe执行顺序相反, reverse参数或者使用refuceRight从右向左执行

isObjectEqual比较对象字段相等

function isObjectEqual(a: Record<string, any>, b:Record<string, any>) {
  if(!a || !b) return false;
  const aProps = Object.getOwnPropertyName(a);
  const bProps = Object.getOwnPropertyName(b);
  if(aProps.length !== bProps.length) return false;
  for(let i = 0; i < aProps.length; i++) {
    const propName = aProps[i];
    const propA = a[propName];
    const propB = b[propName];
    if(!b.hasOwnProperty(propName)) return false;
    if(propA instanceof Object) {
      if(!isObjectEqual(propA, propB)) return false;
    } else if(propA !== propB) {
      return false;
    }
  }
}