javascript 可选的减少参数模式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 可选的减少参数模式相关的知识,希望对你有一定的参考价值。

function reducer(accumulator, value, index, array) {
  var intermediaryValue = accumulator + value;
  
  // at the end of the array iteration, perform additional logic
  if (index === array.length - 1) {
    return intermediaryValue / array.length;
  }
  // else just return the iterated value
  return intermediaryValue;
}

// how to use it with array.reduce

var data = [1,2,3,4,5,2,1];
var medium = data.reduce(reducer, 0);
// data structure
var data = [
  {
    name: 'han solo',
    jedi: false,
    parents: {
      father: {
        jedi: false
      }, 
      mother: {
        jedi: true
      }
    }
  },
  {
    name: 'anakin',
    jedi: true,
    parents: {
      mother: {
        jedi: true
      } // missing the father nested property
    }
  },
  ...
]

// returns the value if the nested property exists, else returns false
function fatherWasJedi(character) {
  var path = 'parents.father.jedi';
  return path.split('.').reduce((obj, field) => {
    if (obj) {
      return obj[field];
    }
    return false;
  }, character)
}

data.forEach(character => { return fatherWasJedi(character); })
function increment(input) {return input + 1}
function decrement(input) {return input - 1}
function double(input) {return input * 2}

var initial_value = 1;

// put a chain of functions in a pipeline array
var pipeline = [
  increment,
  double,
  decrement
];

//use reduce to call each function by order of the array and pass in the previous computed result
var final_value = pipeline.reduce((acc, fn) => {
  return fn(acc);
}, initial_value);

// or use reduceRight to reverse the function call order to start from the right
var final_value = pipeline.reduceRight((acc, fn) => {
  return fn(acc);
}, initial_value); // decrement will be called first instead of increment

以上是关于javascript 可选的减少参数模式的主要内容,如果未能解决你的问题,请参考以下文章

你可以在 Typescript 函数中有可选的解构参数吗?

JavaScript中的可选参数[重复]

23种设计模式—— 建造者模式

23种设计模式—— 建造者模式

23种设计模式—— 建造者模式

可选的SSRS参数