Generic library for functional programming & working with functions.
- Source:
Methods
(inner) exec()
- Source:
Immediately execute the given function.
const {exec} = require('ferrum');
// Normal scopes cannot return values
let r;
{
let x = 42, y = 5;
r = x + y;
}
// Can be rewritten as
const r = exec(() => {
let x = 42, y = 5;
return x + y;
});
(inner) identity()
- Source:
Just a function that returns it's argument!
const {identity, list, filter} = require('ferrum');
identity(null) # => null
identity(42) # => 42
// Identity is sometimes useful in higher order functions like
// filter(); this example for instance removes all values from
// the list that are falsy
pipe(
[null, "asd", "", "foo"],
filter(identity),
list
);
// => ["asd", "foo"]
(inner) pipe(val, …fns) → {Any}
- Source:
Pipeline a value through multiple function calls.
// Sometimes you get very nested function invocations:
pipe(
[1,2,null,3,4,null,5,1,3,2,null,1,4],
filter(identity),
uniq,
map(plus(2)),
)
console.log(pipe(
4,
(x) => x+2,
(x) => x*3
));
// => 18
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
Any | The value to pipe through the functions |
|
fns |
function |
<repeatable> |
Multiple functions |
Returns:
- Type
- Any
(inner) compose(…fns) → {function}
- Source:
Function composition.
const fn = compose(
(x) => x+2,
(x) => x*3
);
console.log(fn(4)); // => 18
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
fns |
function |
<repeatable> |
Multiple functions |
Returns:
All the functions in the sequence composed into one
- Type
- function
(inner) withFunctionName(name, fn, Just)
- Source:
Manually assign a name to a function.
Parameters:
| Name | Type | Description |
|---|---|---|
name |
String | The new name of the function. |
fn |
function | The function to assign a name to |
Just |
function | returns |
(inner) curry()
- Source:
Autocurry a function!
https://en.wikipedia.org/wiki/Currying
Any function that has a fixed number of parameters may be curried! Curried parameters will be in reverse order. This is useful for functional programming, because it allows us to use function parameters in the suffix position when using no curring:
const toNumber = (seq) => map(seq, n => Number(n));
// is the same as
const toNumber = map(n => Number(n))
// or even
const toNumber = map(Number);
Note how in the second version we specified the last parameter first due to currying.
Reverse order only applies in separate invocations:
const sum = (seq) => foldl(seq, 0, (a, b) => a+b);
// is the same as
const sum = foldl(0, (a, b) => a+b);
// or even
concat = sum = foldl(0, plus);
Note how in version two, we specify the parameters in order 2, 3, and then 1:
fn(a, b, c) <=> fn(c)(b)(a) <=> fn(b, c)(a)