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

@thalesrc/js-utils

v3.2.6

Published

Javascript utility functions for web development

Downloads

1,297

Readme

@thalesrc/js-utils

Javascript utility functions for web development

travis codecov npm npm TypeScript npm

Motivation

Collecting commonly used utility functions in a package.

Goals

  • Typescript support
  • Tree-shaking
  • No dependencies
  • High performance
  • Documentation
  • High test coverage
  • Static/Prototype method support

Installation

  • npm: npm install @thalesrc/js-utils --save
  • yarn: yarn add @thalesrc/js-utils
  • pnpm: pnpm i -S @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"]

Find By Key

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}

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

Limit

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

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

Uniquify By Key

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

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

Compact

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}

Deepest

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

Chain

Chains promises in a sequential order

import { chain } from '@thalesrc/js-utils/promise';

const lastResult = await chain([() => getUserDetails(), ({photoUrl}) => getUserPhoto(photoUrl)]);

Never

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 => {
    ...
  });
}

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

Try One By One

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

Limit

Limits the string to n character

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

const str = 'foobarbaz';

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

Etc.

Arrayize

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

Compact

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}

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

Limit

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

Open Promise

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}`

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

License

MIT