GeezerVison is showing github.com — Add compose with loop · HowProgrammingWorks/Composition@6263462
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboard +30Lines changed: 30 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const compose = (...fns) => (...args) => { |
| 4 | + if (fns.length === 0) return args[0]; |
| 5 | + |
| 6 | + let res = fns[0](...args); |
| 7 | + for (let i = 1; i < fns.length; i++) { |
| 8 | + res = fns[i](res); |
| 9 | + } |
| 10 | + return res; |
| 11 | +}; |
| 12 | + |
| 13 | +// Usage |
| 14 | + |
| 15 | +const upperCapital = s => s.replace( |
| 16 | + /\w+/g, |
| 17 | + word => word.charAt(0).toUpperCase() + word.substr(1) |
| 18 | +); |
| 19 | + |
| 20 | +const lower = s => (typeof s === 'string' ? s.toLowerCase() : ''); |
| 21 | + |
| 22 | +const trim = s => s.trim(); |
| 23 | + |
| 24 | +const s = ' MARCUS AURELIUS '; |
| 25 | +console.log(s); |
| 26 | +console.log('lower(' + s + ') = ' + lower(s)); |
| 27 | +console.log('upperCapital(' + s + ') = ' + upperCapital(s)); |
| 28 | + |
| 29 | +const capitalize = compose(trim, lower, upperCapital); |
| 30 | +console.log('capitalize(' + s + ') = ' + capitalize(s)); |