Get unlimited public & private packages + team-based management with npm Teams.Learn more »

@thalesrc/js-utils

2.0.6 • Public • Published

@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

Async Map

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]

Compact

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"];

Difference

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"]

Intersection

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"]

Remove

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"]

Replace

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"];

Uniquify

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"]

Function

Debounce

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

Defer

Delays the execution of the passed function

import { defer } from "@thalesrc/js-utils/function";
 
const result = await defer(() => aFunctionToDeferThatReturnsHello());
 
console.log(result); // 'hello'

Noop

Noop function

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

Of

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

Merge

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

Min-Max

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

Clone

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

Promise

Revert

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);
 });

Timeout

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"));

Try Catch

Merges result and error in the same callback

import { tryCatch } from "@thalesrc/js-utils/promise";
 
const promise = anAsyncCall();
 
const [error, result] = await tryCatch(promise);

Etc.

Is Falsy

Returns whether the entered value is falsy

import { isFalsy } from "@thalesrc/js-utils";
 
isFalsy(undefined); // true
isFalsy(true); // false

Is Truthy

Returns whether the entered value is truthy

import { isTruthy } from "@thalesrc/js-utils";
 
isTruthy(undefined); // false
isTruthy(true); // true

Open Promise

A promise constructor to resolve or reject from outside

import { OpenPromise } from "@thalesrc/js-utils";
 
const aPromiseWillBeResolvedLater = new OpenPromise();
 
aPromiseWillBeResolvedLater.promise.then(val => console.log(val));
 
aPromiseWillBeResolvedLater.resolve({x: 1});
// logs `{x: 1}`

Smart Map

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"

Unique Id

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

Import utils from legacy folder

Example:

import { tryCatch } from "@thalesrc/js-utils/legacy/promise";
 
const promise = anAsyncCall();
 
const [error, result] = await tryCatch(promise);

License

MIT

Install

npm i @thalesrc/js-utils

DownloadsWeekly Downloads

16

Version

2.0.6

License

MIT

Unpacked Size

181 kB

Total Files

210

Last publish

Collaborators

  • avatar