@applitools/functional-commons

中文文档
2.0.2发布于 2023/09/04Apache-2.0ESM + CJS零依赖近 30 天下载 54.1万
原始使用文档
文档目录30 节
  1. Install
  2. Usage
  3. API
  4. range(from, to, [step])
  5. cacheFunctionSync(f)
  6. cacheFunctionAsync(f, [options])
  7. throws_(err)
  8. objectFromEntries(entries)
  9. mapObject(object, mapFunc)
  10. mapValues(object, mapFunc)
  11. filterKeys(object, filterFunc)
  12. filterValues(object, filterFunc)
  13. filterEntries(object, filterFunc)
  14. failAfter(ms, errFactory)
  15. errFactory
  16. returns
  17. presult(promise)
  18. promise
  19. returns
  20. delay
  21. ms
  22. returns
  23. Example
  24. ptimeoutWithValue(promiseOrPromiseFunc, timeout, value)
  25. ptimeoutWithError(promiseOrPromiseFunc, timeout, error)
  26. ptimeoutWithFunction(promiseOrPromiseFunc, timeout, func)
  27. makeError(error, properties)
  28. zip(...arrays)
  29. `flatMap(array, [mapperFunction])
  30. makeThrottledFunction(func, [options])

functional-commons

A set of functional functions that everybody needs.

Install

npm install @applitools/functional-commons

Usage

Example using range:

const {range} = require('@applitools/functional-commons')

for (const i of range(0, 3)) {
  console.log(i)
}
// ==> outputs 0, 1, 2

API

range(from, to, [step])

Returns an array with the numbers from...to - 1 (and skips step numbers)

from (Number)

The first number in the array

to (Number)

The last number in the array will be smaller thanto

step (Number)

The delta to skip when creating the numbers in the array (default is 1)

Example

range(4, 7) // ==> [4, 5, 6]
range(4, 11, 2) // ==> [4, 6, 8, 10]

cacheFunctionSync(f)

Returns a function with same signature as f, but which memoizes the return value according to the arguments passed

f

Any function. The arguments passed to the function will be JSON.string-ified to enable caching.

returns function

The function will have the same signature as f, and which will return the same return value given similar arguments, but calling this function repeatedly with the same arguments will generate only one call to f.

Example

function square(x) {
  console.log('called')

  return x ** 2
}

const memoizedSquare = cacheFunctionSync(square)

console.log(memoizedSquare(4)) // prints "called" and "16"
console.log(memoizedSquare(4)) // prints only "16"
console.log(memoizedSquare(5)) // prints "called" and "25"

cacheFunctionAsync(f, [options])

Returns a function with same signature as f, but which memoizes the return value according to the arguments passed. f is an async function (returns a Promise)

f

Any async function. The arguments passed to the function will be JSON.string-ified to enable caching.

options

expireAfterMs

The cached value will expire after expireAfterMs milliseconds. Default is to never expire (udefined).

nowService

(Used for testing purposes) An object with a now function that returns milliseconds since Epoch time. The default is just Date, which makes it return the current time in milliseconds.

returns

The function will have the same signature as f, and which will return the same return value given similar arguments, but calling this function repeatedly with the same arguments will generate only one call to f.

Example

async function square(x) {
  console.log('called')

  return x ** 2
}

const memoizedSquare = cacheFunctionAsync(square)

console.log(await memoizedSquare(4)) // prints "called" and "16"
console.log(await memoizedSquare(4)) // prints only "16"
console.log(await memoizedSquare(5)) // prints "called" and "25"

throws_(err)

A function that throws err. Nice in places where you want an arrow function to just throw.

err

Any type. Usually inherits from Error, though.

returns

This function never returns. It always throws.

objectFromEntries(entries)

Turns an array of [key, value] pairs into an object.

entries

An array of 2-value arrays (also called "entries"), where the first value in the pair is the key, and the second is the value.

returns

An object whose properties correspond to the entries given

Example

console.log(objectFromEntries([['a', 4, 'b' , 5]])) // prints {a: 4, b: 5}

mapObject(object, mapFunc)

Returns a new object where all the entries in the input object are mapped using mapFunc.

object

Any object.

mapFunc

A function that maps an entry "pair" (an 2-element array where the first element is the key of the property, and the second is the value) to another entry.

returns

An object (prototyped from Object) with mapped properties.

Example

console.log(mapObject({a: 4, b: 5}, ([key, value]) => [key.toUpperCase(), value * 2])) // prints {A: 8, B: 10}

mapValues(object, mapFunc)

Returns a new object where all the values in the input object are mapped using mapFunc.

object

Any object.

mapFunc

A function that maps a value to another value

returns

An object (prototyped from Object) with mapped property values.

Example

console.log(mapObject({a: 4, b: 5}, (value) => value * 2)) // prints {a: 8, b: 10}

filterKeys(object, filterFunc)

Filters an object using a filter function that gets the key. Immutable.

object

Any JavaScript object that needs properties filtered.

filterFunc

A function that accepts the property name and returns a boolean of whether to keep the property or not (true means keep the property)

returns

A new object (who's prototype will be Object) with the same properties as object, minus the filtered ones.

Example

console.log(filterKeys({a: 4, b: 5}, key => key === 'b')) // prints {a: 4}

filterValues(object, filterFunc)

Filters an object using a filter function that gets the value. Immutable.

object

Any JavaScript object that needs properties filtered.

filterFunc

A function that accepts the property value and returns a boolean of whether to keep the property or not (true means keep the property)

returns

A new object (who's prototype will be Object) with the same properties as object, minus the filtered ones.

Example

console.log(filterKeys({a: 4, b: 5}, key => value === '5')) // prints {a: 4}

filterEntries(object, filterFunc)

Filters an object using a filter function that gets the entries. Immutable.

object

Any JavaScript object that needs properties filtered.

filterFunc

A function that accepts a 2-element array of [key, value] and returns a boolean of whether to keep the property or not (true means keep the property)

returns

A new object (who's prototype will be Object) with the same properties as object, minus the filtered ones.

Example

console.log(filterKeys({a: 4, b: 5}, ([key, value]) =>  key === 'b' && value === 5)) // prints {a: 4}

failAfter(ms, errFactory)

throws errFactory() after ms milliseconds

ms

The number of milliseconds to wait before throwing

errFactory

A function that when called returns the value that will be thrown

returns

Nothing. It always throws

Example

try {
  await failAfter(1000, () => new Error('oops'))
} catch(err) {
  console.log(err.message)
}

// prints 'oops' after a second

presult(promise)

Turns a Promise from a promise that is resolved or rejected, to a promise that is always resolved, but returns the err and result as a tuple, Scala/Go/Rust-style.

promise

A promise that will either be resolved or rejected

returns

A promise that always resolved to a 2-tuple:

  • If the oroginal promise is resolved with value, will resolve to [undefined, value]
  • If the oroginal promise is rejected with err, will resolve to [err, undefined]

Example

const [err, value] = await presult(Promise.resolve(4))
console.log(value) // prints '4'

const [err2, value2] = await presult(Promise.reject(new Error('oops')))
console.log(err2.message) // prints 'oops'

delay

An async function that delays a specific time

ms

The time to delay, in milliseconds

returns

returns undefined

Example

await delay(100) // waits for 100ms

ptimeoutWithValue(promiseOrPromiseFunc, timeout, value)

A function that races between a given promise, and a value that returns after a timeout.

promiseOrPromiseFunc

A promise, or a function that returns a promise, which will be called to get the promise.

If the value is a function, it will be called and passed a function (usually called hasAborted), which, if called, will return true if the timeout has already happened, and you can abort this function.

timeout

The number of milliseconds to timeout.

value

The value to return from this function if the timeout happened before the promise resolved.

Example

console.log(await ptimeoutWithValue(delay(10).then(_ => 43), 100, 42)) // prints "43"
console.log(await ptimeoutWithValue(delay(100).then(_ => 43), 10, 42)) // prints "42"

ptimeoutWithError(promiseOrPromiseFunc, timeout, error)

A function that races between a given promise, and throwing an exception after a timeout.

promiseOrPromiseFunc

A promise, or a function that returns a promise, which will be called to get the promise.

If the value is a function, it will be called and passed a function (usually called hasAborted), which, if called, will return true if the timeout has already happened, and you can abort this function.

timeout

The number of milliseconds to timeout.

error

The error to be thrown from this function if the timeout happened before the promise resolved.

Example

console.log(await ptimeoutWithError(delay(10).then(_ => 43), 100, new Error('oops'))) // prints "43"
console.log(await ptimeoutWithError(delay(100).then(_ => 43), 10, new Error('oops'))) // throws 'oops' error

ptimeoutWithFunction(promiseOrPromiseFunc, timeout, func)

A function that races between a given promise, and a value (created from function) that returns after a timeout.

promiseOrPromiseFunc

A promise, or a function that returns a promise, which will be called to get the promise.

If the value is a function, it will be called and passed a function (usually called hasAborted), which, if called, will return true if the timeout has already happened, and you can abort this function.

timeout

The number of milliseconds to timeout.

func

An async function that will be called to get the value to be returned if the timeout occured

Example

console.log(await ptimeoutWithValue(delay(10).then(_ => 43), 100, 42)) // prints "43"
console.log(await ptimeoutWithValue(delay(100).then(_ => 43), 10, 42)) // prints "42"

makeError(error, properties)

A function that adds properties to an error

error

The error to be modified. Note that this function mutabl changes this error.

If error is a string, then an Error is created with this string as the message.

properties

Additional properties that will be added to the error object, in a mutable way

returns

The error object passed, or if the error was a string, the newly generated error.

Example

console.log(Object.entries(makeError('oops', {code: 'OOPS', status: 500}))) // prints {code: 'OOPS', status: 500}

zip(...arrays)

Regular functional zip of arrays.

arrays

list of arrays to zip

returns

An array of arrays, that are the zip of the arrays gotten.

Example

console.log(zip([1, 2, 3], [4, 5, 6])) // prints [[1, 4], [2, 5], [3, 6]]

`flatMap(array, [mapperFunction])

flattens array (one level), along with mapping the values

array

An array of values, or arrays or values.

mapperFunction

A function that maps a value to another. Optional.

returns

The array flattened (one level only), and it's values mapped if there was a mapperFunction.

Example

console.log(flatMap([4, [5, 6], 7])) // prints [4, 5, 6, 7]
console.log(flatMap([4, [5, 6], 7], x => x * 2)) // prints [8, 10, 12, 14]

makeThrottledFunction(func, [options])

returns a function that is a proxy to func, except that calling it will throttle the calls to func.

func

The original function.

`options

maxCallsPerTimeSpan

The maximum number of calls allowed in the time span timeSpan. Default is 120.

timeSpan

The timeSpan we throttle for.

nowService

(Used for testing purposes) An object with a now function that returns milliseconds since Epoch time. The default is just Date, which makes it return the current time in milliseconds.

版本与发布记录

@applitools/functional-commons 共发布 47 个版本,首次发布于 2017/09/24;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.0.2latest2023/09/043 年前
2.0.12023/09/043 年前
2.0.02023/09/043 年前
1.6.02020/05/176 年前
1.5.52020/02/206 年前
1.5.42019/12/046 年前

关于 @applitools/functional-commons 的常见问题

如何安装 @applitools/functional-commons?

在项目目录运行 npm install @applitools/functional-commons,或使用 pnpm add / yarn add / bun add。

@applitools/functional-commons 支持 TypeScript 吗?

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

@applitools/functional-commons 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@applitools/functional-commons 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=8.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@applitools/functional-commons 可以商用吗?

@applitools/functional-commons 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@applitools/functional-commons 的下载量有多少?

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

@applitools/functional-commons 还在维护吗?

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