Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var _ = require('lodash');
- class Formatter{
- constructor(repetitions){
- this.repetitions = repetitions;
- }
- format1(txt){
- return `${"[" .repeat(this.repetitions)} ${txt} ${"]" .repeat(this.repetitions)}`;
- }
- format2(txt){
- return `${"(" .repeat(this.repetitions)} ${txt} ${")" .repeat(this.repetitions)}`;
- }
- }
- let cities = [
- "Paris",
- null,
- "Toulouse",
- "Xixon",
- "",
- "Berlin"
- ];
- let result = _.reverse(
- _.take(
- _.compact(cities)
- , 3
- )
- );
- console.log(result);
- console.log("------------------");
- result = _.flow([
- _.compact,
- (ar) => _.take(ar, 3),
- _.reverse
- ])(cities);
- console.log(result);
- console.log("------------------");
- result = _.chain(cities)
- .compact()
- .take(3)
- .reverse()
- .value();
- console.log(result);
- console.log("------------------");
- //when composing methods, we'll need to provide the right "this" value
- let formatter = new Formatter(2);
- //here we're missing the "this"
- let formatFn = _.flow([
- formatter.format1,
- formatter.format2
- ]);
- console.log(formatFn("hi"));
- // hi
- console.log("------------------");
- //_.flow will pass as "this" to each function the "this" bound to the created function, so let's do a bind:
- let boundFormatFn = formatFn.bind(formatter);
- console.log(boundFormatFn("hi"));
- // (( [[ hi ]] ))
- console.log("------------------");
- //if _.flow were not providing that feature, we could create wrapping functions for each method call
- let formatFn2 = _.flow([
- (st) => formatter.format1(st),
- (st) => formatter.format2(st)
- ]);
- console.log(formatFn2("hi"));
- //(( [[ hi ]] ))
- console.log("------------------");
- //or call bind in each method-function being composed:
- let formatFn3 = _.flow([
- formatter.format1.bind(formatter),
- formatter.format2.bind(formatter)
- ]);
- console.log(formatFn3("hi"));
- //(( [[ hi ]] ))
- console.log("------------------");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement