Created
December 18, 2021 09:51
-
-
Save Rowadz/afe7c94b2a314c6ab1303cef4918409c to your computer and use it in GitHub Desktop.
pip and asynchronous pipe functions in JS
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
Function.prototype.pipe = function (start, ...funcs) { | |
return funcs.reduce((prev, func) => func(prev), start) | |
} | |
const func01 = (prev) => prev + 1 | |
const func02 = (prev) => prev + 1 | |
const func03 = (prev) => prev + 1 | |
const func04 = (prev) => prev + 1 | |
const func05 = (prev) => prev + 1 | |
const { pipe } = Function | |
const result = func05(func04(func03(func02(func01(1))))) | |
const result2 = pipe(1, func01, func02, func03, func04, func05) | |
console.log(result, result2) | |
const asyncFunc01 = async (prev) => prev + 1 | |
const asyncFunc02 = async (prev) => prev + 1 | |
const asyncFunc03 = async (prev) => prev + 1 | |
const asyncFunc04 = async (prev) => prev + 1 | |
const asyncFunc05 = async (prev) => prev + 1 | |
Function.prototype.asyncPipe = async function (start, ...funcs) { | |
let res = start | |
for await (const func of funcs) { | |
res = await func(res) | |
} | |
return res | |
} | |
const asyncRes = async () => { | |
const result = await Promise.resolve(1) | |
.then(asyncFunc01) | |
.then(asyncFunc02) | |
.then(asyncFunc03) | |
.then(asyncFunc04) | |
.then(asyncFunc05) | |
const { asyncPipe } = Function | |
const result2 = await asyncPipe( | |
1, | |
asyncFunc01, | |
asyncFunc02, | |
asyncFunc03, | |
asyncFunc04, | |
asyncFunc05 | |
) | |
console.log(result, result2) | |
} | |
asyncRes() | |
// elixir example | |
/* | |
defmodule Star do | |
def print_stars do | |
items = [1, 2, 3, 4, 5] | |
items | |
|> Enum.with_index | |
|> Enum.each(fn({_, i}) -> IO.puts(String.duplicate("*", i + 1)) | |
end) | |
end | |
end | |
/* |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment