在Javascript中定义链式字符串转换函数

时间:2018-07-16 01:30:42

标签: javascript ecmascript-6 chaining method-chaining

Chaining Methods, also known as Cascading,是指以一行连续的代码在对象上重复调用一个方法。

编写这样的代码:

str.replace("k", "R").toUpperCase().substr(0,4); 

不仅令人愉悦和方便,而且简洁明了。它使我们能够像句子一样阅读代码,在页面中流畅地流动。这也使我们摆脱了通常构造的单调,块状结构。

This blog讨论了一般的操作方法,但是考虑到扩展String原型对于我的情况就足够了,我不知道它是否过大。

基本上,我对Java语言的了解不足,无法做出判断,

  • 是否遵循上述一般方式
  • 或者只是扩展String原型,知道它是generally a bad practice
  • 或者可以使用function wrapper(或者完全不相关)
  • 我也知道以下是另一种选择,但是它很严格,也就是说,翻译成我的情况,这意味着字符串转换只能是
    replace("k", "R"),然后是toUpperCase(),然后是substr(0,4)。

// https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1
console.log('Begin');

const withConstructor = constructor => o => {
  const proto = Object.assign({},
Object.getPrototypeOf(o),
{ constructor }
  );
  return Object.assign(Object.create(proto), o);
};

const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
// or `import pipe from 'lodash/fp/flow';`
// Set up some functional mixins
const withFlying = o => {
  let isFlying = false;
  return {
...o,
fly () {
  isFlying = true;
  return this;
},
land () {
  isFlying = false;
  return this;
},
isFlying: () => isFlying
  }
};
const withBattery = ({ capacity }) => o => {
  let percentCharged = 100;
  return {
...o,
draw (percent) {
  const remaining = percentCharged - percent;
  percentCharged = remaining > 0 ? remaining : 0;
  return this;
},
getCharge: () => percentCharged,
get capacity () {
  return capacity
}
  };
};
const createDrone = ({ capacity = '3000mAh' }) => pipe(
  withFlying,
  withBattery({ capacity }),
  withConstructor(createDrone)
)({});
const myDrone = createDrone({ capacity: '5500mAh' });
console.log(`
  can fly:  ${ myDrone.fly().isFlying() === true }
  can land: ${ myDrone.land().isFlying() === false }
  battery capacity: ${ myDrone.capacity }
  battery status: ${ myDrone.draw(50).getCharge() }%
  battery drained: ${ myDrone.draw(75).getCharge() }%
`);
console.log(`
  constructor linked: ${ myDrone.constructor === createDrone }
`);

console.log('End');

为简单起见,我需要定义自己的函数,如

str.transform1("k", "R").transform2().transform3(0,4); 

具有相同的功能

str.replace("k", "R").toUpperCase().substr(0,4); 

实际上,每个函数都是一组复杂的replace()函数调用,但是让我们简化一下这个问题。

我该怎么办?

0 个答案:

没有答案