-
-
Save xtuc/68f1e7def4b92ea3c7920b1dae0dc798 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
// compose function | |
String.prototype.ᐅ = function(f) { | |
return f(this) | |
} | |
function doubleSay (str) { | |
return str + ", " + str; | |
} | |
function capitalize (str) { | |
return str[0].toUpperCase() + str.substring(1); | |
} | |
function exclaim (str) { | |
return str + '!'; | |
} | |
let result = "hello" | |
.ᐅ (doubleSay) | |
.ᐅ (capitalize) | |
.ᐅ (exclaim) | |
result //=> "Hello, hello!" |
I prefer the ᐅ
symbol because it's look like the |>
symbol used in most functional programming languages. But it's not a valid identifier in JavaScript.
Function.prototype.ᐅ = function(f) {
const self = this
return function(...args) {
return f(self(...args))
}
}
const doubleSay = str => str + ", " + str
const capitalize = str => str[0].toUpperCase() + str.substring(1)
const exclaim = str => str + '!'
const program =
doubleSay
.ᐅ (capitalize)
.ᐅ (exclaim)
program('hello') //=> "Hello, hello!"
// compose function
const ƒ = (_, ...inputs) => inputs.reduce((res, fn) => fn(res))
const doubleSay = str => str + ", " + str
const capitalize = str => str[0].toUpperCase() + str.substring(1)
const exclaim = n => str => str + '!'.repeat(n)
let input = "hello"
let result = ƒ `
${input}
|> ${doubleSay}
|> ${capitalize}
|> ${exclaim(3)}
`
result //=> "Hello, hello!!!"
I'd use ø
because it's not used, and available in english and french.
Also it reminds of the mathematical composition operator (which is just o
).
@rickmed has a point here :D
@rickmed we could also add some arrow functions to get rid of the const self = this
. Although it might be less readable.
Function.prototype.ᐅ = function(f) {
return (...args) => f(this(...args))
}
const doubleSay = str => str + ", " + str
const capitalize = str => str[0].toUpperCase() + str.substring(1)
const exclaim = str => str + '!'
const program =
doubleSay
.ᐅ (capitalize)
.ᐅ (exclaim)
program('hello') //=> "Hello, hello!"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@steida But neither is working for string!