thread-f v1.0.0
thread-f
Clojure style threading of functions in JavaScript.
Inpsired by the threading macros in Clojure.
Usage
Instead of writing
var x = foo(bar(something(whatever(n), 2), {}));
var y = foo(bar({}, something(2, whatever(n))));
write
var threadF = require('thread-f');
var x = threadF.first(n, [
whatever,
[something, 2],
[bar, {}],
foo
]);
var x = threadF.last(n, [
whatever,
[something, 2],
[bar, {}],
foo
]);
This makes this chain of functions easier to read and change.
threadFirst
will apply each function in the specified order, using the return value as first
arguments for the next. threadLast
does the same but passes the value as the last argument.
Each entry in the functions array can be either a plain function or an array. If it's an array, the first element will be used as the function and the rest as additional arguments.
Using [foo, 1, 2, 3]
as a functions entry for threadF.first
will result in calling foo(x, 1, 2, 3)
while using it with threadF.last
will result in foo(1, 2, 3, x)
.
API
thread
threadF.thread(first, value, functions, thisArg)
first
(bool): wether to apply the value as first argument.value
(any): the value to be threading through the functionsfunctions
(array): Array of function or arrays, when encountering an array, the first element will be used a s the function, the rest as additional arguments.thisArg
(any): value that will be bound to each function'sthis
when calling it
first
threadF.first(value, functions, thisArg)
(same as for thread
with the first
argument bound to true
)
last
threadF.last(value, functions, thisArg)
(same as for thread
with the first
argument bound to false
)
8 years ago