Skip to content

thalesrc/js-utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@thalesrc/js-utils

Javascript utility functions for web development

travis codecov npm npm TypeScript npm Join the chat at https://gitter.im/thalesrc_js-utils/Lobby

Motivation

Collecting commonly used utility functions in a package.

Goals

  • Typescript support
  • Tree-shaking
  • No dependencies
  • High performance
  • Documentation
  • Well tested
  • Static/Prototype method support

Installation

  • npm: npm install @thalesrc/js-utils --save
  • yarn: yarn add @thalesrc/js-utils

Documentation

See: thalesrc.github.io/js-utils

Functions

Array

Maps an array asynchronously

import { asyncMap } "@thalesrc/js-utils/array";

const array = [1, 2, 3];

const result = await asyncMap(array, async value => {
 return await addOneAfterASecond(value);
});

console.log(result); // [2, 3, 4]

Filters falsy values of an array

import { compact } from "@thalesrc/js-utils/array";

const arr = [undefined, "", false, 0, 1, "1", null];
const compacted = compact(arr); // [1, "1"];

Gets the difference of the two arrays or sets

import { difference } from "@thalesrc/js-utils/array";

const base = ["a", "b", "c", "d", "a", "b", "c", "d"];

difference(base, ["a", "b"]); // ["c", "d", "c", "d"]
difference(base, ["a", "b"], true); // ["c", "d", "a", "b", "c", "d"]

Finds an object in an array by matching the value set on the key

import { findByKey } from "@thalesrc/js-utils/array";

const array = [{a: 1}, {a: 2}, {a: 3}];

findByKey(array, "a", 2); // {a: 2}

Gets the intersection of the two arrays or sets

import { intersection } from "@thalesrc/js-utils/array";

const base = ["a", "b", "c", "d", "a", "b", "c", "d"];

intersection(base, ["a", "b", "x"]); // ["a", "b", "a", "b"]
intersection(base, ["a", "b", "x"], false); // ["a", "b"]

Returns first n children of an array

import { limit } from "@thalesrc/js-utils/array";

const array = ["a", "b", "c", "d", "e", "f"];

limit(array, 3); // ["a", "b", "c"]

Removes an item from an array

import { remove } from "@thalesrc/js-utils/array";

const array = ["a", "b", "c", "a", "b", "c"];

remove(array, "b"); // ["a", "c", "a", "b", "c"]
remove(array, "b", true); // ["a", "c", "a", "c"]

Replaces an item with passed one of an array

import { replace } from "@thalesrc/js-utils/array";

const array = ["a", "b", "c", "a", "b", "c"];

replace(array, "b", "x"); // ["a", "x", "c", "a", "b", "c"]
replace(array, {startingIndex: 3, deleteCount: 1, itemsToReplace: ['x', 'y']}); // ["a", "b", "c", "x", "y", "b", "c"];

const config = new Map();
config.set("a", "x")
config.set("b", "y");

replace(array, {itemsToReplace: config}); // ["x", "y", "c", "a", "b", "c"];
replace(array, {itemsToReplace: config, multi: true}); // ["x", "y", "c", "x", "y", "c"];

Removes repeated items from the array

import { uniquify } "@thalesrc/js-utils/array";

const array = ["a", "b", "c", "a", "b", "c"];

uniquify(array); // ["a", "b", "c"]

Removes objects from the array which the value of its specifed key included before by another

import { uniquifyByKey } "@thalesrc/js-utils/array";

const array = [{a: 1}, {a: 1}, {a: 2}, {a: 3}, {a: 3}, {a: 4}];

uniquifyByKey(array, 'a'); // [{a: 1}, {a: 2}, {a: 3}, {a: 4}]

Function

Debounces a function that delays invoking until after configured time have elapsed since the last time the debounced function was invoked

import { debounce } from "@thalesrc/js-utils/promise";

function foo() {
  console.log("hello");
}

for (let i = 0; i < 10; i++) {
  debounce(foo);
}

// logs "hello" only once

Delays the execution of the passed function

import { defer } from "@thalesrc/js-utils/function";

const result = await defer(() => aFunctionToDeferThatReturnsHello());

console.log(result); // 'hello'

Noop function

import { noop } from "@thalesrc/js-utils/function";

noop();

Creates a function which returns the specified value

import { of } from "@thalesrc/js-utils/function";

const base = [1, 2, 5, {}, "x", "y"];

base.map(of('hi')); // ["hi", "hi", "hi", "hi", "hi", "hi"]

Map

Merges two maps

import { merge } from "@thalesrc/js-utils/map";

const first = new Map();
first.set("a", 1);

const second = new Map();
second.set("b", 2);
merge(first, second); // [{key: "a", value: 1}, {key: "b", value: 2}]

Math

Limits the value by specified range

import { minMax } from "@thalesrc/js-utils/math";

const limitedValue = minMax(200, 300, Math.random() * 1000); // Outputs between 200-300

Object

A function to deep clone anything (recursively)

import { clone } from "@thalesrc/js-utils/object";

const object = {a: 1, b: {c: true, d: ["x", "y"]}};

const clonedObject = clone(object);
// {a: 1, b: {c: true, d: ["x", "y"]}}
// object.b.d === clonedObject.b.d // false

Removes null and undefined values and their keys from an object

import { compact } from "@thalesrc/js-utils/object";

const a = {
 x: null,
 y: undefined,
 z: 20
};

compact(a); // {z: 20}

Get deepest value in an object chain

import { deepest } from "@thalesrc/js-utils/object";

const a = {x: null};
const b = {x: a};
const c = {x: b};

deepest(c, 'x'); // {x: null} (a)

Promise

A promise which never resolves

import { never, NEVER } from '@thalesrc/js-utils/promise';

function foo(promise = never()) {
  promise.then(val => {
    ...
  });
}

// or

function foo(promise = NEVER) {
  promise.then(val => {
    ...
  });
}

Exchanges resolve state with rejection of a promise

import { revert } from "@thalesrc/js-utils/promise";

const errorPromise = Promise.reject(new Error('foo'));

revert(errorPromise)
 .then(err => {
   console.log("this will be logged", err);
 })
 .catch(res => {
   console.log("this won't be logged", res);
 });

Returns a promise which resolves after specified time

import { timeout } from "@thalesrc/js-utils/promise";

timeout(1000)
 .then(() => console.log("will be logged after a second"));

Merges result and error in the same callback

import { tryCatch } from "@thalesrc/js-utils/promise";

const promise = anAsyncCall();

const [error, result] = await tryCatch(promise);

Tries a set of promises one by one with given order. Breaks the call when a promise resolved. Otherwise keeps trying incoming promises until the list is finished.

import { tryOneByOne } from "@thalesrc/js-utils/promise";

async function fooFunction() {
  const foo = await tryOneByOne([
    () => someCall(),
    (err) => anotherCall(),
    (err) => fooPromise()
  ]);

  // do stuff
}

String

Limits the string to n character

import { limit } from "@thalesrc/js-utils/string";

const str = 'foobarbaz';

limit(str, 3); // 'foo'

Etc.

Encapsulates a non array value with an array that contains it unless the value is already an array

import { arrayize } from "@thalesrc/js-utils";

const foo = 'foo';
const bar = ['bar'];
const fooArr = arrayize(foo); // ['foo'];
const barArr = arrayize(bar); // ['bar'];

Filters falsy values of the given array Removes null and undefined values and their keys from an object

import { compact } from "@thalesrc/js-utils";

const arr = [undefined, "", false, 0, 1, "1"];
const compacted = compact(arr); // [1, "1"];

const object = {
 x: null,
 y: undefined,
 z: 20
};

const compacted = compact(object); // {z: 20}

Returns whether the entered value is falsy

import { isFalsy } from "@thalesrc/js-utils";

isFalsy(undefined); // true
isFalsy(true); // false

Returns whether the entered value is truthy

import { isTruthy } from "@thalesrc/js-utils";

isTruthy(undefined); // false
isTruthy(true); // true

Limits the string or array to n character

import { limit } from "@thalesrc/js-utils";

const str = 'foobarbaz';
const array = ["a", "b", "c", "d", "e", "f"];

limit(str, 3); // 'foo'
limit(array, 3); // ["a", "b", "c"]

A promise constructor to resolve or reject from outside

import { OpenPromise } from "@thalesrc/js-utils";

const aPromiseWillBeResolvedLater = new OpenPromise();

aPromiseWillBeResolvedLater.then(val => console.log(val));

aPromiseWillBeResolvedLater.resolve({x: 1});
// logs `{x: 1}`

Like WeakMap but can also store values using primitive keys

See: WeakMap

import { SmartMap } from "@thalesrc/js-utils";

const aMap = new SmartMap();

aMap.set("foo", "foo");
aMap.set(1, "thales rocks");
console.log(aMap.size) // 2

aMap.set({}, "thales rocks again");
console.log(aMap.size) // 2

const anObject = {};
aMap.set(anObject, "thales rocks again and again");
console.log(aMap.size) // 3
console.log(aMap.get(anObject)) // "thales rocks again and again"

Starts a new counter for every unique prefix and if a prefix is given, returns the id by prefixing it, otherwise returns the id as number

import { uniqueId } from "@thalesrc/js-utils";

uniqueId(); // 0
uniqueId(); // 1
uniqueId("some-str"); // "some-str-0";
uniqueId("some-str"); // "some-str-1";
uniqueId(); // 3

Static/Prototype Methods

You may use any of these methods by adding them to the constructors or prototypes to native objects in main file.

Prototype Example:

// main.ts
import "@thalesrc/js-utils/array/proto/compact";

// somewhere else
const arr = [undefined, "", false, 0, 1, "1", null];
const compacted = arr.compact(); // [1, "1"];

Static Example:

// main.ts
import "@thalesrc/js-utils/promise/static/timeout";

// somewhere else
Promise.timeout(1000)
 .then(() => console.log("will be logged after a second"));

Legacy Typescript Support

Install legacy build

npm install @thalesrc/js-utils@legacy --save

License

MIT