javascript - 调用多种转换方法的更简洁的方法是什么?

标签 javascript method-chaining

我需要对一个变量调用多个转换方法。在 JavaScript 中,有哪些干净的方法可以做到这一点?是否过度设计它来创建一个类,以便我可以进行方法链接?

这是我想要整理的示例:

let value = 'foo';

value = transformValueFn1(value);
value = transformValueFn2(value);
value = replaceCertainChars(value);
value = encodeAsHtml(value);
// etc 

return value

最佳答案

在变压器数组上使用reduce

let value = 'foo';

const newValue = [
  transformValueFn1,
  transformValueFn2,
  replaceCertainChars,
  encodeAsHtml
].reduce((val, fn) => fn(val), value)


function transformValueFn1(val) {
  console.log('transformValueFn1', val);
  return val;
}

function transformValueFn2(val) {
  console.log('transformValueFn2', val)
  return val;
}

function replaceCertainChars(val) {
  console.log('replaceCertainChars', val)
  return val;
}

function encodeAsHtml(val) {
  console.log('encodeAsHtml', val)
  return val;
}

If you're doing this more than once or twice, a class would make the most sense IMO, though you could also use an array of the functions and reduce – CertainPerformance

关于javascript - 调用多种转换方法的更简洁的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57492765/

相关文章:

javascript - 如何在不使用原型(prototype)的情况下链接函数?

javascript - meteor 内容不显示

函数中的 JavaScript 作用域或 AngularJS Promise $q

javascript - 如何编写自己的 `reduce` 函数?

python - 如何在 Python 中实现 Selenium 多个 WebDriverWait 的方法链接

javascript - Underscore.js _.tap() 函数什么是方法链?

javascript - 改进Jquery代码实现

javascript - 如何让 document.write 和 ajax 发挥良好作用?

Java(处理1.5.1): Fluent interface @ multilevel inheritance via generics

java - Mockito - stub 由模拟对象方法返回的对象的方法