Skip to content

Instantly share code, notes, and snippets.

@xtuc

xtuc/compose.js Secret

Created July 3, 2017 11:14
Show Gist options
  • Save xtuc/68f1e7def4b92ea3c7920b1dae0dc798 to your computer and use it in GitHub Desktop.
Save xtuc/68f1e7def4b92ea3c7920b1dae0dc798 to your computer and use it in GitHub Desktop.
// 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!"
@katemihalikova
Copy link

// 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!!!"

@kapouer
Copy link

kapouer commented Jul 4, 2017

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).

@xaviervia
Copy link

@rickmed has a point here :D

@morkro
Copy link

morkro commented Jul 4, 2017

@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