The library contains a collection of higher-order functions for composing your applications with reusable functions.
All chain-like functions are manually chunked (segmented). It is a deliberate decision (to not use automatic currying) to allow a function to accept a variadic number of arguments in a segment, which leads in my opinion to a nicer to use API (and is faster as a bonus).
The library has built-in type definitions, which provide an excellent IDE support.
Via NPM:
npm i @arrows/composition
Via Yarn:
yarn add @arrows/composition
All modules can be imported independently (to reduce bundle size), here are some import methods (you can use either CommonJS or ES modules):
import composition from '@arrows/composition'
import { pipe } from '@arrows/composition'
import pipe from '@arrows/composition/pipe'
Allows you to build your own, chain-like functions
Executes provided functions from left to right, passing the result from one function to the other. Accepts a wrapping function which can execute additional instructions before executing each passed function.
Arguments listed below have to be passed separately, as segments.
wrappingFn
- two-argument function thats is responsible for executing each function in a chain.
...fns
- an arbitrary number of one-argument functions to be executed in a chain
initialArg
- initial argument, passed to the first function in a chain (through a wrapping function)
Arguments of a wrapping function:
fn
- function in a chain
input
- current value
isLast
- boolean flag indicating if a function is a last one in a chain
(wrapping_function) => (fn, fn?, ..., fn?) => (initial_value) => result
const { chain } = require('@arrows/composition')
// Create custom wrapping function:
const wrappingFn = (fn, input) => {
console.log(input)
return fn(input)
}
// Create reusable chain-like function:
const pipeWithLog = chain(wrappingFn)
// Create concrete function
const calculate = pipeWithLog((x) => x + 1, (x) => x * 2)
console.log(calculate(0))
// -> 0
// -> 1
// -> 2 (final result)
Works like chain, but executes functions from right to left.
Arguments listed below have to be passed separately, as segments.
wrappingFn
- two-argument function thats is responsible for executing each function in a chain.
...fns
- an arbitrary number of one-argument functions to be executed in a chain
initialArg
- initial argument, passed to the first function in a chain (through a wrapping function)
Arguments of a wrapping function:
fn
- function in a chain
input
- current value
isLast
- boolean flag indicating if a function is a last one in a chain
(wrapping_function) => (fn, fn?, ..., fn?) => (initial_value) => result
const { chainRight } = require('@arrows/composition')
// Create custom wrapping function:
const wrappingFn = (fn, input) => {
console.log(input)
return fn(input)
}
// Create reusable chain-like function:
const composeWithLog = chainRight(wrappingFn)
// Create concrete function
const calculateRight = composeWithLog((x) => x + 1, (x) => x * 2)
console.log(calculateRight(0))
// -> 0
// -> 0
// -> 1 (final result)
Chains provided functions from right to left.
Arguments listed below have to be passed separately, as segments.
...fns
- an arbitrary number of one-argument functions to be executed in a chain
initialArg
- initial argument, passed to the first function in a chain
(fn, fn?, ..., fn?) => (initial_value) => result
const { compose } = require('@arrows/composition')
const addPrefixes = compose(
(text) => `prefix1-${text}`,
(text) => `prefix2-${text}`,
)
addPrefixes('arrows') // -> "prefix1-prefix2-arrows"
Wraps function as an automatically curried one.
fn
- an arbitrary function(fn) => curried_fn
const { curry } = require('@arrows/composition')
const rawAdd = (a, b) => a + b
const add = curry(rawAdd)
add(1, 2) // -> 3
add(1)(2) // -> 3
Chains provided functions from left to right.
Arguments listed below have to be passed separately, as segments.
...fns
- an arbitrary number of one-argument functions to be executed in a chain
initialArg
- initial argument, passed to the first function in a chain
(fn, fn?, ..., fn?) => (initial_value) => result
const { pipe } = require('@arrows/composition')
const addSuffixes = pipe(
(text) => `${text}-suffix1`,
(text) => `${text}-suffix2`,
)
addSuffixes('arrows') // -> "arrows-suffix1-suffix2"
Chains provided functions from left to right, takes an initial value as a first argument.
Provides an alternative API with better type inference for immediately evaluated calculations.
initialArg
- initial argument, passed to the first function in a chain...fns
- an arbitrary number of one-argument functions to be executed in a chain(initial_value, fn, fn?, ..., fn?) => result
const { pipe } = require('@arrows/composition')
const result = pipe.now(
'arrows',
(text) => `${text}-suffix1`,
(text) => `${text}-suffix2`,
) // -> "arrows-suffix1-suffix2"
Works like pipe, but additionally:
Arguments listed below have to be passed separately, as segments.
...fns
- an arbitrary number of one-argument functions to be executed in a chain
initialArg
- initial argument, passed to the first function in a chain
(fn, fn?, ..., fn?) => (initial_value) => result
Automatically passing down an error:
const { rail } = require('@arrows/composition')
const { filter, map, reduce } = require('@arrows/array')
const sumDogsAge = rail(
filter((pet) => pet.specie === 'dog'),
map((pet) => {
if (pet.age < 0) {
throw new Error('Wrong age!')
}
return pet.age
}),
reduce((a, b) => a + b, 0),
)
const pets = [
{ specie: 'dog', name: 'Charlie', age: 4 },
{ specie: 'cat', name: 'Luna', age: 6 },
{ specie: 'dog', name: 'Ollie', age: -10 },
]
const result = sumDogsAge(pets)
if (result instanceof Error) {
console.log('Oops!')
} else {
console.log(`Sum: ${result}`)
}
// -> "Oops!"
Automatically passing previous argument, if function returns undefined
:
const { rail } = require('../../lib/index')
const addUser = rail(
(user) => ({ type: 'user', data: user }),
(entry) => {
console.log(`Saving ${entry.data.name} to the database.`)
// Returns undefined, argument will be automatically
// passed to the next function.
},
(entry) => `Saved user: ${entry.data.name}`,
)
const user = { name: 'Joe' }
console.log(addUser(user))
/* Output:
Saving Joe to the database.
Saved user: Joe
*/
Works similar to rail, but additionally, if argument is a promise - resolves that promise before passing to the next function.
Arguments listed below have to be passed separately, as segments.
...fns
- an arbitrary number of one-argument functions to be executed in a chain
initialArg
- initial argument, passed to the first function in a chain
(fn, fn?, ..., fn?) => (initial_value) => result
Automatically passing down an error:
const { railAsync } = require('../../lib/index')
const dbFake = {
id: 0,
save() {
const result = Promise.resolve(this.id)
this.id++
return result
},
}
const addArticle = railAsync(
(article) => ({ type: 'article', data: article }),
(entry) => dbFake.save(entry),
(id) => `Article id: ${id}`,
)
const main = async () => {
const article = {
title: 'Railway oriented programming',
content: 'Lorem ipsum...',
}
const result = await addArticle(article)
console.log(result)
}
main() // -> "Article id: 0"
Works like rail, but executes functions from right to left.
Works like railAsync, but executes functions from right to left.
Executes provided function with provided argument and returns an argument without changes.
Useful for executing void functions without breaking the chain.
Note: rail*
functions handle this automatically, so you can use void functions directly.
fn
- an arbitrary function
arg
- any value
(fn, arg) => arg
Example:
const { pipe, tap } = require('../../lib/index')
const { sort, reduce, _rest, _butLast } = require('@arrows/array')
const sumNotes = pipe(
sort((a, b) => a - b),
tap(console.log),
_rest,
tap(console.log),
_butLast,
tap(console.log),
reduce((a, b) => a + b, 0),
)
const notes = [16, 17.5, 19, 15, 18]
console.log(sumNotes(notes))
/* Output:
[ 15, 16, 17.5, 18, 19 ]
[ 16, 17.5, 18, 19 ]
[ 16, 17.5, 18 ]
51.5
*/
Project is under open, non-restrictive ISC license.