npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@applitools/functional-commons

v2.0.2

Published

<!-- markdownlint-disable MD024 -->

Downloads

948,483

Readme

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.