Last active
September 27, 2019 16:09
-
-
Save XoseLluis/59e5ca929e5ff4abcb2a311bfa0b5f32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("------------------"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment