Skip to content
/ flocky Public

A utility library with clarity and efficiency at the core and no dependencies

License

Notifications You must be signed in to change notification settings

devoxa/flocky

Repository files navigation

flocky

A utility library with clarity and efficiency at the core and no dependencies

Package Version Build Status Code Coverage

InstallationUsageAPI ReferenceContributorsLicense


Installation

yarn add @devoxa/flocky

Usage

import { sum } from '@devoxa/flocky'
sum([1, 2, 3])
// -> 6

API Reference

average(array)

Compute the average of the values in an array.

flocky.average([1, 4, 2, -4, 0])
// -> 0.6

Source • Minify: 77 B • Minify & GZIP: 79 B

chunk(array, size)

Split an array of elements into groups of size. If the array can't be split evenly, the final chunk will contain the remaining elements.

flocky.chunk([1, 2, 3, 4, 5, 6, 7], 3)
// -> [[1, 2, 3], [4, 5, 6], [7]]

Source • Minify: 105 B • Minify & GZIP: 101 B

clone(value)

Create a deep clone of value. This method only supports types native to JSON, so all primitive types, arrays and objects.

const original = [{ a: 1 }, { b: 2 }]
const clone = flocky.clone(original)
original[0] === clone[0]
// -> false

Source • Minify: 69 B • Minify & GZIP: 69 B

compact(array)

Create an array with all falsy (undefined, null, false, 0, NaN, '') values removed.

flocky.compact([1, 2, 3, null, 4, false, 0, NaN, 5, ''])
// -> [1, 2, 3, 4, 5]

Source • Minify: 61 B • Minify & GZIP: 64 B

debounce(func, wait)

Create a debounced function that delays invoking func until wait milliseconds have elapsed since the last time the debounced function was invoked.

const func = () => console.log('Heavy processing happening')
const debouncedFunc = flocky.debounce(func, 250)

Source • Minify: 131 B • Minify & GZIP: 113 B

duplicates(array, identity?)

Create a version of an array, in which only the duplicated elements are kept. The order of result values is determined by the order they occur in the array. Can be passed an optional identity function to select the identifying part of objects.

flocky.duplicates([1, 1, 2, 4, 2, 1, 6])
// -> [1, 2, 1]

flocky.duplicates(['foo', 'bar', 'foo', 'foobar'])
// -> ['foo']

const input = [{ id: 1, a: 1 }, { id: 1, a: 2 }, { id: 2, a: 3 }, { id: 1, a: 4 }]
flocky.duplicates(input, (element) => element.id)
// -> [{ id: 1, a: 2 }, { id: 1, a: 4 }]

Source • Minify: 277 B • Minify & GZIP: 147 B

escapeRegExp(string)

Escape special characters in a string for use in a regular expression.

flocky.escapeRegExp('Hey. (1 + 1 = 2)')
// -> 'Hey\\. \\(1 \\+ 1 = 2\\)'

Source • Minify: 93 B • Minify & GZIP: 90 B

flatten(object)

Flattens a nested object into an object with dot notation keys.

flocky.flatten({ a: { b: 1, c: 2 }, d: { e: { f: 3 } } })
// -> { 'a.b': 1, 'a.c': 2, 'd.e.f': 3 }

Source • Minify: 172 B • Minify & GZIP: 136 B

get(object, path, defaultValue?)

Get the value at a path of an object (with an optional defaultValue)

⚠️ Using this method will ignore type information, and you will have to type the return type yourself. If you can, it is always better to access properties directly, for example with the "optional chaining" operator.

const object = {a: {b: {c: 1}}}
flocky.get(object, 'a.b.c')
// -> 1

const object = {a: {b: {c: 1}}}
flocky.get(object, 'x.x.x')
// -> undefined

const object = {a: {b: {c: 1}}}
flocky.get(object, 'x.x.x', 'default')
// -> 'default'

SourceBenchmark • Minify: 424 B • Minify & GZIP: 266 B

hash(data)

Create a hashed string representation of the passed in data.

⚠️ This function is not cryptographically secure, use Argon2id, scrypt or bcrypt for anything security related.

flocky.hash('some really long string')
// -> 'x1nr7uiv'

flocky.hash({id: 'AAA', name: 'BBB'})
// -> 'x16mynva'
Implementation Details

This method uses Murmur3 because it is small, fast and has fairly good collision characteristics (about 1 in 36000).

SourceBenchmark • Minify: 552 B • Minify & GZIP: 332 B

identifier()

Generate a random identifier with UUID v4 format.

flocky.identifier()
// -> 'bfc8d57e-b9ab-4245-836e-d1fd99602e30'

Source • Minify: 275 B • Minify & GZIP: 196 B

matchAll(regExp, string)

Find all matches of a regular expression in a string.

flocky.matchAll(/f(o+)/g, 'foo bar baz foooo bar')
// -> [
// ->   { match: 'foo', subMatches: ['oo'], index: 0 },
// ->   { match: 'foooo', subMatches: ['oooo'], index: 12 },
// -> ]

Source • Minify: 178 B • Minify & GZIP: 133 B

max(array)

Compute the maximum of the values in an array.

flocky.max([1, 4, 2, -3, 0])
// -> 4

Source • Minify: 58 B • Minify & GZIP: 63 B

memoize(func, options?)

Create a function that memoizes the return value of func.

const func = (a, b) => a + b
const memoizedFunc = flocky.memoize(func)
const memoizedFuncWithTtl = flocky.memoize(func, { ttl: 30 * 1000 })
memoizedFunc(1, 2)
// -> 3
Implementation Details

This method's implementation is based on fast-memoize, with some improvements for variadic performance and additional support for a TTL based cache.

SourceBenchmark • Minify: 962 B • Minify & GZIP: 441 B

min(array)

Compute the minimum of the values in an array.

flocky.min([1, 4, 2, -3, 0])
// -> -3

Source • Minify: 58 B • Minify & GZIP: 63 B

omit(object, keys)

Create an object composed of all existing keys that are not specified in keys.

const object = { a: 1, b: 2, c: 3 }
flocky.omit(object, ['a'])
// -> { b: 2, c: 3 }

SourceBenchmark • Minify: 143 B • Minify & GZIP: 129 B

percentile(array, k)

Compute the kth percentile of the values in an array.

flocky.percentile([90, 85, 65, 72, 82, 96, 70, 79, 68, 84], 0.9)
// -> 90.6

Source • Minify: 217 B • Minify & GZIP: 156 B

pick(object, keys)

Create an object composed of the specified keys.

const object = { a: 1, b: 2, c: 3 }
flocky.pick(object, ['a', 'c'])
// -> { a: 1, c: 3 }

SourceBenchmark • Minify: 97 B • Minify & GZIP: 93 B

promisePool(promiseFunctions, limit)

Run multiple promise-returning functions in parallel with limited concurrency.

await flocky.promisePool([
  () => Promise.resolve(1),
  () => Promise.resolve(2),
  () => Promise.resolve(3),
  () => Promise.resolve(4),
], 2)
// -> [1, 2, 3, 4]

Source • Minify: 182 B • Minify & GZIP: 142 B

promiseTimeout(promise, timeoutMs)

Reject a promise if it does not resolve within timeoutMs.

⚠️ When the timeout is hit, a promise rejection will be thrown. However, since promises are not cancellable, the execution of the promise itself will continue until it resolves or rejects.

await flocky.promiseTimeout(Promise.resolve(1), 10)
// -> 1

Source • Minify: 305 B • Minify & GZIP: 181 B

random(lower, upper, float?)

Generate a random number between lower and upper (inclusive). If float is true or lower or upper is a float, a float is returned instead of an integer.

flocky.random(1, 10)
// -> 8

flocky.random(1, 20, true)
// -> 14.94849340769861

flocky.random(2.5, 3.5)
// -> 3.2341312319841373

Source • Minify: 219 B • Minify & GZIP: 128 B

randomString(length)

Generate a random alphanumeric string with length characters.

flocky.randomString(5)
// -> 'tfl0g'

Source • Minify: 230 B • Minify & GZIP: 201 B

range(start, end, step?)

Generate an array of numbers progressing from start up to and including end.

flocky.range(0, 5)
// -> [0, 1, 2, 3, 4, 5]

flocky.range(-5, -10)
// -> [-5, -6, -7, -8, -9, -10]

flocky.range(-6, -12, 2)
// -> [-6, -8, -10, -12]

Source • Minify: 131 B • Minify & GZIP: 111 B

roundTo(number, precision)

Round a floating point number to precision decimal places.

flocky.roundTo(3.141592653589, 4)
// -> 3.1416

flocky.roundTo(1.005, 2)
// -> 1.01

flocky.roundTo(1111.1, -2)
// -> 1100
Implementation Details

This method avoids floating-point errors by adjusting the exponent part of the string representation of a number instead of multiplying and dividing with powers of 10. The implementation is based on this example by Lam Wei Li.

Source • Minify: 209 B • Minify & GZIP: 150 B

sample(array)

Get a random element from the array.

flocky.sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
// -> 8

Source • Minify: 79 B • Minify & GZIP: 79 B

shuffle(array)

Create an array of shuffled values.

flocky.shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
// -> [3, 7, 2, 1, 10, 4, 6, 9, 5, 8]
Implementation Details

This method uses a modern version of the Fisher-Yates shuffle.

Source • Minify: 152 B • Minify & GZIP: 131 B

sleep(ms)

Return a promise that waits for ms milliseconds before resolving.

await flocky.sleep(25)

Source • Minify: 73 B • Minify & GZIP: 78 B

slugify(string)

Generate a URL-safe slug of a string.

flocky.slugify(' Issue #123 is _important_! :)')
// -> 'issue-123-is-important'

Source • Minify: 114 B • Minify & GZIP: 104 B

sum(array)

Compute the sum of the values in an array.

flocky.sum([1, 4, 2, -4, 0])
// -> 3

Source • Minify: 60 B • Minify & GZIP: 67 B

throttle(func, wait)

Create a throttled function that invokes func at most every wait milliseconds. If the invocation is throttled, func will be invoked with the last arguments provided.

const func = () => console.log('Heavy processing happening')
const throttledFunc = flocky.throttle(func, 250)

Source • Minify: 209 B • Minify & GZIP: 156 B

toMap(array, key, target?)

Create a lookup map out of an array of objects, with a lookup key and an optional target.

flocky.toMap(
  [
    { id: 1, name: 'Stanley', age: 64 },
    { id: 2, name: 'Juliet', age: 57 },
    { id: 3, name: 'Alex', age: 19 }
  ],
  'id'
)
// -> {
// ->   1: { id: 1, name: 'Stanley', age: 64 },
// ->   2: { id: 2, name: 'Juliet', age: 57 },
// ->   3: { id: 3, name: 'Alex', age: 19 }
// -> }

flocky.toMap(
  [
    { id: 1, name: 'Stanley', age: 64 },
    { id: 2, name: 'Juliet', age: 57 },
    { id: 3, name: 'Alex', age: 19 }
  ],
  'name',
  'age'
)
// -> { Stanley: 64, Juliet: 57, Alex: 19 }

Source • Minify: 95 B • Minify & GZIP: 95 B

unflatten(object)

Unflattens an object with dot notation keys into a nested object.

flocky.unflatten({ 'a.b': 1, 'a.c': 2, 'd.e.f': 3 })
// -> { a: { b: 1, c: 2 }, d: { e: { f: 3 } } }

Source • Minify: 199 B • Minify & GZIP: 145 B

unique(array, identity?)

Create a duplicate-free version of an array, in which only the first occurrence of each element is kept. The order of result values is determined by the order they occur in the array. Can be passed an optional identity function to select the identifying part of objects.

flocky.unique([1, 1, 2, 4, 2, 1, 6])
// -> [1, 2, 4, 6]

flocky.unique(['foo', 'bar', 'foo', 'foobar'])
// -> ['foo', 'bar', 'foobar']

const input = [{ id: 1, a: 1 }, { id: 1, a: 2 }, { id: 2, a: 3 }, { id: 1, a: 4 }]
flocky.unique(input, (element) => element.id)
// -> [{ id: 1, a: 1 }, { id: 2, a: 3 }]

SourceBenchmark • Minify: 238 B • Minify & GZIP: 153 B

Contributors

Thanks goes to these wonderful people (emoji key):


David Reeß

💻 📖 ⚠️

Jeff Hage

💻

darthmaim

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT

About

A utility library with clarity and efficiency at the core and no dependencies

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published