@arrows/composition

中文文档
1.2.2发布于 2020/01/23ISCCommonJS零依赖近 30 天下载 23.7万

Functional composition library

原始使用文档
文档目录16 节
  1. Table of contents
  2. Introduction
  3. Installation
  4. API reference
  5. chain
  6. chainRight
  7. compose
  8. curry
  9. pipe
  10. pipe.now
  11. rail
  12. rail.async
  13. railRight
  14. railRight.async
  15. tap
  16. License

arrows - composition

@arrows/composition

npm (scoped) CircleCI David (path) Codecov npm bundle size (scoped) GitHub

Table of contents

  1. Introduction
  2. Installation
  3. API reference
  4. License

Introduction

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.

Installation

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'

API reference

chain

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.

Parameters

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

Returns

  • Returns a final value.

Interface

(wrapping_function) => (fn, fn?, ..., fn?) => (initial_value) => result

Examples

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)

chainRight

Works like chain, but executes functions from right to left.

Parameters

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

Returns

  • Returns a final value.

Interface

(wrapping_function) => (fn, fn?, ..., fn?) => (initial_value) => result

Example

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)

compose

Chains provided functions from right to left.

Parameters

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

Returns

  • Returns a final value.

Interface

(fn, fn?, ..., fn?) => (initial_value) => result

Example

const { compose } = require('@arrows/composition')

const addPrefixes = compose(
  (text) => `prefix1-${text}`,
  (text) => `prefix2-${text}`,
)

addPrefixes('arrows') // -> "prefix1-prefix2-arrows"

curry

Wraps function as an automatically curried one.

Parameters

  • fn - an arbitrary function

Returns

  • Returns a curried version of the function.

Interface

(fn) =>  curried_fn

Example

const { curry } = require('@arrows/composition')

const rawAdd = (a, b) => a + b

const add = curry(rawAdd)

add(1, 2) // -> 3
add(1)(2) // -> 3

pipe

Chains provided functions from left to right.

Parameters

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

Returns

  • Returns a final value.

Interface

(fn, fn?, ..., fn?) => (initial_value) => result

Example

const { pipe } = require('@arrows/composition')

const addSuffixes = pipe(
  (text) => `${text}-suffix1`,
  (text) => `${text}-suffix2`,
)

addSuffixes('arrows') // -> "arrows-suffix1-suffix2"

pipe.now

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.

Parameters

  • 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

Returns

  • Returns a final value.

Interface

(initial_value, fn, fn?, ..., fn?) => result

Example

const { pipe } = require('@arrows/composition')

const result = pipe.now(
  'arrows',
  (text) => `${text}-suffix1`,
  (text) => `${text}-suffix2`,
) // -> "arrows-suffix1-suffix2"

rail

Works like pipe, but additionally:

  • if one of the functions throws or returns an error - returns that error,
  • if one of the functions returns undefined - passes previous argument to the next function.

Parameters

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

Returns

  • Returns a final value.

Interface

(fn, fn?, ..., fn?) => (initial_value) => result

Examples

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
*/

rail.async

Works similar to rail, but additionally, if argument is a promise - resolves that promise before passing to the next function.

Parameters

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

Returns

  • Returns a final value wrapped in a promise.

Interface

(fn, fn?, ..., fn?) => (initial_value) => result

Example

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"

railRight

Works like rail, but executes functions from right to left.

railRight.async

Works like railAsync, but executes functions from right to left.

tap

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.

Parameters

  • fn - an arbitrary function

  • arg - any value

Returns

  • Returns argument as-is.

Interface

(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
*/

License

Project is under open, non-restrictive ISC license.

版本与发布记录

@arrows/composition 共发布 16 个版本,首次发布于 2019/09/17;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.2.2latest2020/01/236 年前
1.2.12019/11/067 年前
1.2.02019/11/067 年前
1.1.22019/11/027 年前
1.1.12019/10/307 年前
1.1.02019/10/307 年前

关于 @arrows/composition 的常见问题

@arrows/composition 是什么?

Functional composition library

如何安装 @arrows/composition?

在项目目录运行 npm install @arrows/composition,或使用 pnpm add / yarn add / bun add。

@arrows/composition 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/arrows__composition 是否存在。

@arrows/composition 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@arrows/composition 可以商用吗?

@arrows/composition 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@arrows/composition 的下载量有多少?

根据 npm 官方下载统计,@arrows/composition 在 2026/10/07 – 2026/11/05 这 30 天内被下载 237,228 次,日均约 7,908 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@arrows/composition 还在维护吗?

最新版本 1.2.2 发布于 2020/01/23(6 年前);至今共发布 16 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/09/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。