我做了一个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()
最佳答案
许多函数库都带有可用于“链接”的管道函数。
pipe(findRepeatable, findMostRepeated)(myStr)
您自己实现起来很容易。
function pipe(...funcs) {
return function(value) {
for (func of funcs) {
value = value(func)
}
return value;
}
}
关于Javascript 链接多个函数而不是传递函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47951969/