Javascript链多个函数而不是传递函数作为参数

时间:2017-12-23 11:10:37

标签: javascript ecmascript-6

我做了一个findMaxChar计数算法练习,设法让它工作但我的调用方法可以改进。

const myStr = 'Lorem Ipsummm'

function findRepeatable(myStr){
  let charMap = {}
  for(let char of myStr){
    if(charMap[char]) {
      charMap[char]++
    }else{
      charMap[char] = 1
    }
  }
  return charMap
}

function findMostRepeated(obj){
   let maxChar = '',
   max = 0
   for(let char in obj){
     if(obj[char] > max){
       max = obj[char]
       maxChar = char
     }
  }

  return `${maxChar}: ${max}`
}

console.log(findMostRepeated(findRepeatable(myStr)))

我正在传递函数作为参数,我怎样才能使它像这样链接

findMostRepeated()
.findRepeatable()

https://jsbin.com/katixefoxe/edit?html,js,console

3 个答案:

答案 0 :(得分:1)

许多函数库都带有一个管道函数,可以用于"链接"。

pipe(findRepeatable, findMostRepeated)(myStr)

自己很容易实现。

function pipe(...funcs) {
  return function(value) {
    for (func of funcs) {
      value = value(func)
    }

    return value;
  }
}

答案 1 :(得分:0)

 class CharMap extends Map {
  constructor(str){
    super();
    for(var char of str)
      this.add(char);
  }
  add(char){
    this.set(char, (this.get(char) || 0) + 1);
  }
  max(){
    return this.sortDesc()[0];
  }
  sortDesc(){
    return [...this].sort(([char, a], [char2, b]) => b - a);
  }
 }

所以你可以这样做:

 const map = new CharMap("abbccddeee");
 console.log(map.max());

获取字符及其计数:

 const [char, count] = map.max();

答案 2 :(得分:0)

尝试:

const myStr = 'Lorem Ipsummm'
var myObj ={
  charMap:{},
findRepeatable:function (myStr){

  for(let char of myStr){
if(this.charMap[char]) {
  this.charMap[char]++
}else{
  this.charMap[char] = 1
}
  }
  return this;
},
findMostRepeated: function (obj){
   let maxChar = '',
   max = 0
   for(let char in this.charMap){
     if(this.charMap[char] > max){
       max = this.charMap[char]
       maxChar = char
     }
  }

  return `${maxChar}: ${max}`;
}
}

的console.log(myObj.findRepeatable(myStr中).findMostRepeated())