Skip to content

Instantly share code, notes, and snippets.

@gaganjakhotiya
Created February 9, 2019 17:51
Show Gist options
  • Save gaganjakhotiya/e8ca1425b4ad3b66e71b8f6c03462069 to your computer and use it in GitHub Desktop.
Save gaganjakhotiya/e8ca1425b4ad3b66e71b8f6c03462069 to your computer and use it in GitHub Desktop.
PIping in JS, the Elm way!
// Elm lang supports creating functions which can be used like an infix operator
// Ex: 1 + 2 |> (\n -> n == 3) -- "|>" is the infix operator and the code returns True
// If we look at the type of this operator, it would look like:
// |> : a -> (a -> b) -> b
// Now, let's try to do this in JavaScript.
// Firstly, we need a piper which would take any data and return a pipe-able data-type
// Next, every function call - when piping - should return a pipe-able data type
// A pipe-able data type is capable of executing a specific function
// This specific function takes a function as an argument
// The function in the argument is passed the data stored in pipe-able data-type
function p(d) {
if (d === null || d === undefined) {
p.__proto__.p = p
return p
} else if (typeof d !== "function") {
d.__proto__.p = p
return d
} else {
o = this === p ? d.call() : d.call(null, this)
o = o === undefined || o === null ? p : o
o.__proto__.p = p
return o
}
}
// Usage
p(1 + 2)
.p(i => i == 3)
.p(b => b == true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment