Chaining Methods, also known as Cascading,是指以一行连续的代码在对象上重复调用一个方法。
编写这样的代码:
str.replace("k", "R").toUpperCase().substr(0,4);
不仅令人愉悦和方便,而且简洁明了。它使我们能够像句子一样阅读代码,在页面中流畅地流动。这也使我们摆脱了通常构造的单调,块状结构。
This blog讨论了一般的操作方法,但是考虑到扩展String原型对于我的情况就足够了,我不知道它是否过大。
基本上,我对Java语言的了解不足,无法做出判断,
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()
函数调用,但是让我们简化一下这个问题。
我该怎么办?