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 🙏

© 2026 – Pkg Stats / Ryan Hefner

web-utils-kit

v1.3.1

Published

The web-utils-kit package provides a collection of well-tested and thoroughly documented utility functions for various web development needs. Each function adheres to a strict coding style and best practices to ensure consistency and maintainability.

Readme

Web Utils Kit

The web-utils-kit package provides a collection of well-tested and thoroughly documented utility functions for various web development needs. Each function adheres to a strict coding style and best practices to ensure consistency and maintainability.

Getting Started

Install the package:

npm i -S web-utils-kit

Project blueprint

  • src/index.ts is the flat consumer-facing package API. Consumers import supported functions and types directly from web-utils-kit.
  • src/validations/ owns validation functions and exposes them through a thin, explicit module entry file.
  • src/transformers/ groups date, JSON, number, and string transformations behind a thin, explicit module entry file.
  • src/utils/ groups async, collection, extraction, filtering, generation, Markdown, pagination, and sorting utilities behind a thin, explicit module entry file.
  • src/test-utils/ provides code-aware assertions for synchronous throws and promise rejections.
  • src/shared/ contains contracts and error definitions shared by the package modules.

Module entry files contain explicit named re-exports only. Implementation files export public symbols at their declarations, while constants and supporting validations, transformers, and utilities are package-internal and unsupported unless they are intentionally added to src/index.ts.

Each unit or integration test suite is colocated with, named after, and imports the implementation file it covers. Tests for the same implementation file remain together, with separate unit and integration files only when both test levels are needed. Entry-point tests are reserved for assertions about the flat package API.

The publish workflow runs the complete test suite, type checking, linting, formatting verification, and the package build before publishing to npm.

Examples

Validate a password:

import { isPasswordValid } from 'web-utils-kit';

isPasswordValid('zR<q%+r2C,&fy.SE&~.(REXTqe4K[?>G'); // true
isPasswordValid('some-weak-password'); // false

Sort a list of records:

import { sortRecords } from 'web-utils-kit';

[{ v: 1 }, { v: 2 }, { v: 3 }].sort(sortRecords('v', 'desc'));
// [{ v: 3 }, { v: 2 }, { v: 1 }]

Execute an asynchronous function persistently:

import { retryAsyncFunction } from 'web-utils-kit';

const res = await retryAsyncFunction(
  () => fetch('https://api.example.com/user/1'),
  [3, 5],
);
await res.json();
// {
//   uid: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d',
//   nickname: 'PythonWiz333'
// }

API Reference

Test Utilities

Asserts that a synchronous operation throws an error with the expected string or numeric code. Codes are resolved through error-message-utils, so encoded errors and objects carrying a code property are supported. When expectedMessage is provided, the extracted message must contain that text.

The helper returns undefined when the assertion passes. Otherwise, it throws an Error; code and message mismatches preserve the original thrown value as cause. Use expectToRejectCode for asynchronous operations.

import { expectToThrowCode } from 'web-utils-kit';

const error = Object.assign(new Error('Access denied'), { code: 'ACCESS_DENIED' });

expectToThrowCode(
  () => {
    throw error;
  },
  'ACCESS_DENIED',
  'Access denied',
);

Asserts that a PromiseLike rejects with an error carrying the expected string or numeric code. Codes are resolved through error-message-utils, so encoded errors and objects carrying a code property are supported. When expectedMessage is provided, the extracted rejection message must contain that text.

The returned promise resolves with undefined when the assertion passes. It rejects with an Error when the input resolves or the rejection does not match; code and message mismatches preserve the original rejected value as cause.

import { expectToRejectCode } from 'web-utils-kit';

const error = Object.assign(new Error('Access denied'), { code: 'ACCESS_DENIED' });

await expectToRejectCode(Promise.reject(error), 'ACCESS_DENIED', 'Access denied');

Validations

The maximum email length accepted by isEmailValid.

import { MAX_EMAIL_LENGTH } from 'web-utils-kit';

MAX_EMAIL_LENGTH; // 320

Verifies if a value is a valid string and its length is within a range (optional).

import { isStringValid } from 'web-utils-kit';

isStringValid('Hello world!'); // true
isStringValid('', 1, 5); // false
isStringValid('abcde', 1, 5); // true
isStringValid('abcdef', 1, 5); // false
isStringValid(' '); // false
isStringValid(' ', undefined, undefined, false); // true

Verifies if a value is a valid number and is within a range (optional). The minimum value defaults to Number.MIN_SAFE_INTEGER (-9007199254740991) while the maximum value defaults to Number.MAX_SAFE_INTEGER (9007199254740991).

import { isNumberValid } from 'web-utils-kit';

isNumberValid(1); // true
isNumberValid(2, 3, 5); // false
isNumberValid(3, 3, 5); // true
isNumberValid(6, 3, 5); // false

Verifies if a value is a valid integer and is within a range (optional). If a range is not provided, it will use the properties Number.MIN_SAFE_INTEGER & Number.MAX_SAFE_INTEGER.

import { isIntegerValid } from 'web-utils-kit';

isIntegerValid(1); // true
isIntegerValid(1.5); // false

Verifies if a value is a valid unix timestamp in milliseconds. The smallest value is set for the beginning of the Unix epoch (January 1st, 1970 - 14400000) on the numeric limit established by JavaScript (9007199254740991).

import { isTimestampValid } from 'web-utils-kit';

isTimestampValid(Date.now()); // true
isTimestampValid(14399999); // false
isTimestampValid(Number.MIN_SAFE_INTEGER + 1); // false

Verifies if a value is a valid numeric string.

import { isNumeric } from 'web-utils-kit';

isNumeric('14400000'); // true
isNumeric('123.55'); // true
isNumeric('-522.01'); // true
isNumeric('6,555.85'); // false
isNumeric('Hello world!'); // false

Verifies if a value is an actual object. It also validates if it has keys (optional).

import { isObjectValid } from 'web-utils-kit';

isObjectValid({}); // false
isObjectValid({}, true); // true
isObjectValid({ auth: 123, isAdmin: true }); // true
isObjectValid([0, 1, { foo: 'bar' }]); // false

Verifies if a value is an array. It also validates if it has elements inside (optional).

import { isArrayValid } from 'web-utils-kit';

isArrayValid([]); // false
isArrayValid([], true); // true
isArrayValid({ auth: 123, isAdmin: true }); // false

Verifies if a value is a valid email address with a maximum length of 320 characters.

import { isEmailValid } from 'web-utils-kit';

isEmailValid('[email protected]'); // true
isEmailValid('jesus@graterol'); // false

// forbid certain extensions
isEmailValid('[email protected]', ['.con']); // false

Verifies that a slug contains lowercase letters or digits separated by single hyphens and meets a length range (defaults to 2–16 characters).

import { isSlugValid } from 'web-utils-kit';

isSlugValid('python-wiz-333'); // true
isSlugValid('PythonWiz333'); // false
isSlugValid('hello-world', 2, 32); // true
isSlugValid('jesus@graterol'); // false

Verifies if a password meets the following requirements:

  • Meets a length range (Defaults to 8 - 2048)
  • At least one uppercase letter
  • At least one lowercase letter
  • At least one number
  • At least one special character
import { isPasswordValid } from 'web-utils-kit';

isPasswordValid('zR<q%+r2C,&fy.SE&~.(REXTqe4K[?>G'); // true
isPasswordValid('some-weak-password'); // false

Verifies if a value has the correct OTP Secret Format.

import { isOTPSecretValid } from 'web-utils-kit';

isOTPSecretValid('NB2RGV2KAY2CMACD'); // true

Verifies if a value has the correct OTP Token Format.

import { isOTPTokenValid } from 'web-utils-kit';

isOTPTokenValid('123456'); // true
isOTPTokenValid('1234567'); // false

Verifies if a value has a correct JWT Format: [Base64-URL Encoded Header].[Base64-URL Encoded Payload].[Signature]

import { isJWTValid } from 'web-utils-kit';

isJWTValid('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIzNDU2Nzg5LCJuYW1lIjoiSm9zZXBoIn0.OpOSSw7e485LOP5PrzScxHb7SR6sAOMRckfFwi4rp7o');
// true

Verifies if a value has a valid Authorization Header format based on the RFC6750. Example: Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ

import { isAuthorizationHeaderValid } from 'web-utils-kit';

isAuthorizationHeaderValid('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIzNDU2Nzg5LCJuYW1lIjoiSm9zZXBoIn0.OpOSSw7e485LOP5PrzScxHb7SR6sAOMRckfFwi4rp7o');
// true

Verifies if a value complies with semantic versioning.

import { isSemverValid } from 'web-utils-kit';

isSemverValid('1.0.0'); // true

Verifies if a value is a valid URL.

import { isURLValid } from 'web-utils-kit';

isURLValid('https://jesusgraterol.dev'); // true
isURLValid('jesusgraterol.dev'); // false

Verifies if a value is a valid UUID and that it matches a specific version.

import { isUUIDValid } from 'web-utils-kit';

isUUIDValid('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d', 4); // true
isUUIDValid('01695553-c90c-705a-b56d-778dfbbd4bed', 7); // true

Transformers

Formats a numeric value based on the user's default language.

import { prettifyNumber } from 'web-utils-kit';

prettifyNumber(1000.583); // '1,000.58'
prettifyNumber(2654.69642236, { maximumFractionDigits: 8, suffix: ' BTC' });
// '2,654.69642236 BTC'
prettifyNumber(1000, { minimumFractionDigits: 2, prefix: '$' });
// '$1,000.00'

Formats a numeric value as a percentage based on the user's default language.

import { prettifyPercentage } from 'web-utils-kit';

prettifyPercentage(10); // '10%'
prettifyPercentage(25.583, { maximumFractionDigits: 2 }); 
// '25.58%'
prettifyPercentage(2.65469642236, { maximumFractionDigits: 8, suffix: ' APY' }); 
// '2.65469642% APY'

Creates an instance of Date based on a value.

import { toDate } from 'web-utils-kit';

toDate('2026-06-15T16:01:04.228Z').toISOString(); 
// Date 2026-06-15T16:01:04.228Z

toDate(new Date('2026-06-15T16:01:04.228Z')).toISOString(); 
// Date 2026-06-15T16:01:04.228Z

toDate(1781539293658).toISOString(); 
// Date 2026-06-15T16:01:04.228Z

Formats a date instance based on a template.

  • date-short -> 12/05/2024 (Default)
  • date-medium -> December 5, 2024
  • date-long -> Thursday, December 5, 2024
  • time-short -> 12:05 PM
  • time-medium -> 12:05:20 PM
  • datetime-short -> 12/5/2024, 12:05 PM
  • datetime-medium -> December 5, 2024 at 12:05 PM
  • datetime-long -> Thursday, December 5, 2024 at 12:05:20 PM
import { prettifyDate } from 'web-utils-kit';

prettifyDate(new Date());
// '12/05/2024'
prettifyDate(new Date(), 'datetime-long');
// 'Thursday, December 5, 2024 at 12:05:20 PM'
prettifyDate(Date.now(), 'date-medium');
// 'December 5, 2024'

Formats a duration in milliseconds into a human-readable string.

import { prettifyTime } from 'web-utils-kit';

prettifyTime(59_999); // '59s'
prettifyTime(3_660_000); // '1h 1m'
prettifyTime(90_060_000); // '1d 1h 1m'

Formats a bytes value into a human readable format.

import { prettifyFileSize } from 'web-utils-kit';

prettifyFileSize(85545, 6); // '83.540039 kB'
prettifyFileSize(79551423); // '75.87 MB'

Formats the number that will be inserted in a badge so it doesn't take too much space. If the current count is 0, it returns undefined as the badge shouldn't be displayed.

import { prettifyBadgeCount } from 'web-utils-kit';

prettifyBadgeCount(0); // undefined
prettifyBadgeCount(11); // '9+'
prettifyBadgeCount(135, 99); // '99+'

Capitalizes the first letter of a string and returns the new value.

import { capitalizeFirst } from 'web-utils-kit';

capitalizeFirst('hello world'); // 'Hello world'

Converts a string value into Title Case.

import { toTitleCase } from 'web-utils-kit';

toTitleCase('hello world'); // 'Hello World'

Converts a string value into a slug.

import { toSlug } from 'web-utils-kit';

toSlug('HELLO WORLD!!@'); // 'hello-world'

Truncates a string to a specified length and appends an ellipsis if it exceeds that length.

import { truncateText } from 'web-utils-kit';

truncateText('This is a message', 18); // 'This is a message'
truncateText('This is a message', 17); // 'This is a message'
truncateText('This is a message', 16); // 'This is a mes...'
truncateText('This is a message', 15); // 'This is a me...'

Masks the middle of a string, keeping a specified number of visible characters at the start and end.

import { maskMiddle } from 'web-utils-kit';

maskMiddle('01021234567890123456', 4); // '0102...3456'
maskMiddle('01021234567890123456', 6, '********'); // '010212********123456'

Normalizes a query string by removing control characters, zero-width characters, and extra spaces, then converts it to lowercase. Optionally, it can truncate the string to a specified maximum length.

import { normalizeQuery } from 'web-utils-kit';

normalizeQuery('  Information     Sections  '); // 'information sections'
normalizeQuery('quick\u200Bsearch\u200Cresult\uFEFF'); // 'quicksearchresult'

Converts any value into a string. If the value is an object or an array, it will be stringified with JSON.stringify.

import { stringifyValue } from 'web-utils-kit';

stringifyValue(123.45); // '123.45'
stringifyValue({ name: 'Jane', count: 2 }); // '{"name":"Jane","count":2}'
stringifyValue({ name: 'Jane', roles: ['admin', 'editor'] }, 2); 
// '{\n  "name": "Jane",\n  "roles": [\n    "admin",\n    "editor"\n  ]\n}'

Applies substitutions to a string based on a provided object. The string can contain placeholders in the format of {{key}}, which will be replaced by the corresponding value from the substitutions object. If a placeholder does not have a corresponding key in the substitutions object, it will remain unchanged in the output string.

import { applySubstitutions } from 'web-utils-kit';

applySubstitutions('Hello, {{name}}! You have {{count}} new messages.', {
  name: 'John',
  count: 5,
}); 
// 'Hello, John! You have 5 new messages.'

Converts a time string into milliseconds. The time string should be in the format of "{value} {unit}", where the value is a number and the unit can be milliseconds, seconds, minutes, hours, days, weeks, months, or years. For example: "2 days", "5 minutes", "2 hours".

import { toMS } from 'web-utils-kit';

toMS('53 years'); // 1672552800000
toMS('53 days'); // 4579200000

Serializes a JSON object with the JSON.stringify method.

Serialization failures throw an Exception with code UNABLE_TO_SERIALIZE_JSON. Wrapped failures contribute only their readable message and are not attached as metadata or a cause.

import { stringifyJSON } from 'web-utils-kit';

stringifyJSON({ c: 8, b: [{ z: 6, y: 5, x: 4 }, 7], a: 3 });
// '{"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3}'

Stringifies a JSON object in a deterministic way, ensuring that the keys are sorted and the output is consistent.

Serialization failures throw an Exception with code UNABLE_TO_SERIALIZE_JSON. Wrapped failures contribute only their readable message and are not attached as metadata or a cause.

import { stringifyJSONDeterministically } from 'web-utils-kit';

stringifyJSONDeterministically({ c: 8, b: [{ z: 6, y: 5, x: 4 }, 7], a: 3 });
// '{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}'

Deserializes a JSON string with the JSON.parse method.

Parsing failures throw an Exception with code UNABLE_TO_DESERIALIZE_JSON. Wrapped failures contribute only their readable message and are not attached as metadata or a cause.

import { parseJSON } from 'web-utils-kit';

parseJSON('{ c: 8, b: [{ z: 6, y: 5, x: 4 }, 7], a: 3 }');
// {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3}

Creates a deep clone of an object by using the JSON.stringify and JSON.parse methods.

Clone failures throw an Exception with code UNABLE_TO_CREATE_DEEP_CLONE. Wrapped failures contribute only their readable message and are not attached as metadata or a cause.

import { createDeepClone } from 'web-utils-kit';

const a = { a: 'Hello', b: { c: 'World' } };
const b = createDeepClone(a);

b.b.c = 'Universe';

console.log(a.b.c); // 'World'
console.log(b.b.c); // 'Universe'

Removes null, undefined, empty objects ({}), and empty arrays ([]) from the given data recursively.

import { pruneJSON } from 'web-utils-kit';

pruneJSON({
  a: { b: { c: { d: {} }, x: undefined } },
  z: null,
  y: [[], [null, { foo: { x: { a: null } } }], {}],
});
// null

pruneJSON({
  a: { b: { c: { d: { z: undefined, x: [], p: { a: 1 } } }, x: undefined } },
  z: null,
  y: [[], [null, { foo: { x: { a: null } } }], {}],
})
// { a: { b: { c: { d: { p: { a: 1 } } } } } }

Utils

Generates a UUID based on a version.

import { generateUUID } from 'web-utils-kit';

generateUUID(4); // '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
generateUUID(7); // '01695553-c90c-705a-b56d-778dfbbd4bed'

Generates a string from randomly picked characters based on the length.

import { generateRandomString } from 'web-utils-kit';

generateRandomString(15); // 'IbnqwSPvZdXxVyS'

Generates a random decimal number greater than or equal to the minimum and less than the maximum.

import { generateRandomFloat } from 'web-utils-kit';

generateRandomFloat(1, 100); // 67.551

Generates a random integer constrained by the inclusive minimum and maximum values.

import { generateRandomInteger } from 'web-utils-kit';

generateRandomInteger(1, 100); // 71

Generates a sequence of numbers within a range based on a number of steps.

import { generateSequence } from 'web-utils-kit';

generateSequence(1, 10); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
generateSequence(1, 10, 2); // [1, 3, 5, 7, 9]

Generates a date ID string in the format "YYYY_MM_DD".

import { generateDateId } from 'web-utils-kit';

generateDateId() // '2026_06_26'
generateDateId(new Date()) // '2026_06_26'
generateDateId(new Date().getTime()) // '2026_06_26'
generateDateId('2022-01-07T12:30:09.449Z') // '2022_01_07'

Sorts a list of primitive values based on their type and a sort direction.

import { sortPrimitives } from 'web-utils-kit';

[1, 2, 3, 4, 5].sort(sortPrimitives('asc'));
// [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5].sort(sortPrimitives('desc'));
// [5, 4, 3, 2, 1]
['a', 'b', 'c'].sort(sortPrimitives('asc'));
// ['a', 'b', 'c']
['a', 'b', 'c'].sort(sortPrimitives('desc'));
// ['c', 'b', 'a']
[[3n, 1n, 4n, 2n, 5n]].sort(sortPrimitives('asc'));
// [1n, 2n, 3n, 4n, 5n]

Sorts a list of record values by key based on their type and a sort direction.

import { sortRecords } from 'web-utils-kit';

[{ v: 1 }, { v: 2 }, { v: 3 }].sort(sortRecords('v', 'asc'));
// [{ v: 1 }, { v: 2 }, { v: 3 }]
[{ v: 1 }, { v: 2 }, { v: 3 }].sort(sortRecords('v', 'desc'));
// [{ v: 3 }, { v: 2 }, { v: 1 }]
[{ v: 'a' }, { v: 'b' }, { v: 'c' }].sort(sortRecords('v', 'asc'));
// [{ v: 'a' }, { v: 'b' }, { v: 'c' }]
[{ v: 'a' }, { v: 'b' }, { v: 'c' }].sort(sortRecords('v', 'desc'));
// [{ v: 'c' }, { v: 'b' }, { v: 'a' }]
[{ v: 1n }, { v: 2n }, { v: 3n }].sort(sortRecords('v', 'desc'));
// [{ v: 3n }, { v: 2n }, { v: 1n }]

Sorts a list of record values by key, treating stringified bigints as actual bigints, based on a sort direction.

import { sortRecordsWithBigIntString } from 'web-utils-kit';

[{ v: '1' }, { v: '2' }, { v: '3' }].sort(sortRecordsWithBigIntString('v', 'asc'));
// [{ v: '1' }, { v: '2' }, { v: '3' }]
[
  { v: '9007199254740993' }, 
  { v: '-12' }, 
  { v: '0' }, 
  { v: '9007199254740992' }
].sort(sortRecordsWithBigIntString('v', 'desc'));
// [{ v: '9007199254740993' }, { v: '9007199254740992' }, { v: '0' }, { v: '-12' }]

Sorts a list of record values by key, treating date values as actual Date objects, based on a sort direction.

Missing, null, or invalid date values throw an Exception with the MIXED_OR_UNSUPPORTED_DATA_TYPES code. The exception does not add metadata, a cause, an HTTP status, or a response mapping.

import { sortRecordsWithDateValue } from 'web-utils-kit';

[
  { v: '2026-06-15T16:01:33.658Z' }, 
  { v: new Date('2026-05-15T16:01:33.658Z') }, 
  { v: new Date('2026-07-15T16:01:33.658Z').getTime() }
].sort(sortRecordsWithDateValue('v', 'asc'));
// [
//   { v: new Date('2026-05-15T16:01:33.658Z') }, 
//   { v: '2026-06-15T16:01:33.658Z' }, 
//   { v: new Date('2026-07-15T16:01:33.658Z').getTime() }
// ]

[
  { v: '2026-06-15T16:01:33.658Z' }, 
  { v: new Date('2026-05-15T16:01:33.658Z') }, 
  { v: new Date('2026-07-15T16:01:33.658Z').getTime() }
].sort(sortRecordsWithDateValue('v', 'desc'));
// [
//   { v: new Date('2026-07-15T16:01:33.658Z').getTime() }
//   { v: '2026-06-15T16:01:33.658Z' }, 
//   { v: new Date('2026-05-15T16:01:33.658Z') }, 
// ]

Creates a shallow copy of the input array and shuffles it, using a version of the Fisher-Yates algorithm.

import { shuffleArray } from 'web-utils-kit';

shuffleArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
// [4, 7, 5, 3, 6, 8, 9, 1, 2, 10]
shuffleArray(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
// ['d', 'j', 'c', 'a', 'g', 'e', 'b', 'f', 'i', 'h']
shuffleArray([{ a: 1 }, { b: 2 }, { c: 3 }, { d: 4 }, { e: 5 }])
// [ { c: 3 }, { d: 4 }, { a: 1 }, { b: 2 }, { e: 5 } ]

Splits an array into smaller arrays (batches) of a given size.

import { splitArrayIntoBatches } from 'web-utils-kit';

splitArrayIntoBatches(
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  3
)
// [
//   [1, 2, 3],
//   [4, 5, 6],
//   [7, 8, 9],
//   [10],
// ]

Applies non-nullish overrides to a defaults object and returns a new shallow object containing only the default keys. Missing, null, and undefined override values preserve their corresponding defaults.

import { applyDefaults } from 'web-utils-kit';

applyDefaults(
  { name: 'Anonymous', retryCount: 8, isEnabled: true },
  { name: 'Alice', retryCount: 0, isEnabled: false },
);
// { name: 'Alice', retryCount: 0, isEnabled: false }

Picks a list of properties from an object and returns a new object (shallow) with the provided keys.

import { pickProps } from 'web-utils-kit';

pickProps({ a: 1, b: 2, c: 3, d: 4 }, ['b', 'd'])
// { b: 2, d: 4 }

Omits a list of properties from an object and returns a new object (shallow) with only those keys that weren't omitted.

import { omitProps } from 'web-utils-kit';

omitProps({ a: 1, b: 2, c: 3, d: 4 }, ['b', 'd'])
// { a: 1, c: 3 }

Compares two objects or arrays deeply and returns true if they are equals.

import { isEqual } from 'web-utils-kit';

isEqual({ a: 2, c: 5, b: 3 }, { c: 5, b: 3, a: 2 });
// true
isEqual([{ a: 1, b: 2 }], [{ b: 2, a: 1 }]);
// true

Filters an array of primitives based on a given query and returns a shallow copy. IMPORTANT: Providing the queryProp makes the query very efficient as it only attempts to match the value of that property, instead of the whole item.

import { filterByQuery } from 'web-utils-kit';

filterByQuery(
  [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Chalie' },
    { id: 4, name: 'David' },
  ],
  'ali',
  { queryProp: 'name' }
);
// [
//   { id: 1, name: 'Alice' },
//   { id: 3, name: 'Chalie' },
// ]

filterByQuery(
  [
    { a: { x: 'Hello', y: ['yak', 123], p: { a: { b: 'croatoan' } }, z: { foo: 'bar' } } },
    { a: { x: 'Bye', y: ['Kok', 456], p: { a: { b: ['xaax'] } }, z: { foo: 'Haj' } } },
  ],
  'croatoan'
);
// [{ a: { x: 'Hello', y: ['yak', 123], p: { a: { b: 'croatoan' } }, z: { foo: 'bar' } } }]

Creates an asynchronous delay that resolves once the provided seconds have passed.

import { delay } from 'web-utils-kit';

await delay(3);
// ~3 seconds later

Executes an asynchronous function persistently, retrying on error with incremental delays defined in retryScheduleDuration (seconds).

import { retryAsyncFunction } from 'web-utils-kit';

const res = await retryAsyncFunction(
  () => fetch('https://api.example.com/user/1'),
  [3, 5],
);
await res.json();
// {
//   uid: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d',
//   nickname: 'PythonWiz333'
// }

Validates the format of an authorization header and extracts the token from it.

import { extractTokenFromAuthorizationHeader } from 'web-utils-kit';

extractTokenFromAuthorizationHeader('Bearer my-secret-token')
// my-secret-token

Validates the format of an email address and extracts the username from it.

import { extractEmailUsername } from 'web-utils-kit';

extractEmailUsername('[email protected]')
// johndoe

Extracts a string of initials from the provided value.

import { getInitials } from 'web-utils-kit';

getInitials('John Doe', 1); // 'J'
getInitials('John Doe', 2); // 'JD'

Gets the value of a property from the last item when the array length reaches the page size.

import { getNextPageParam } from 'web-utils-kit';

const entries = [
  { id: 'entry-1', reason: 'spam' },
  { id: 'entry-2', reason: 'abuse' },
];
const partialEntries = [{ id: 'entry-1', reason: 'spam' }];
const ENTRY_PAGE_SIZE = 2;

getNextPageParam('id', entries, ENTRY_PAGE_SIZE); // 'entry-2'
getNextPageParam('id', partialEntries, ENTRY_PAGE_SIZE); // undefined

Extracts the name of the first markdown heading in the given content.

import { extractFirstMarkdownHeadingName } from 'web-utils-kit';

extractFirstMarkdownHeadingName('# Output format\n\nReturn concise Markdown.')
// 'Output format'

Extracts the names of substitution placeholders in the given text.

import { extractSubstitutionPlaceholderNames } from 'web-utils-kit';

extractSubstitutionPlaceholderNames('Hello, {{name}}! Your name is {{name}} and you have {{count}} messages.')
// ['name', 'count']

Types

The UUID versions supported by this library.

type IUUIDVersion = 4 | 7;

The sort direction that can be applied to a list.

type ISortDirection = 'asc' | 'desc';

The configuration that will be used to prettify a number.

type INumberFormatConfig = {
  minimumFractionDigits: number; // Default: 0
  maximumFractionDigits: number; // Default: 2
  prefix: string; // Default: ''
  suffix: string; // Default: ''
};

The value that can be used to create a Date instance.

type IDateValue = Date | number | string;

A date can be prettified by choosing a template that meets the user's requirements.

  • date-short -> 12/05/2024 (Default)
  • date-medium -> December 5, 2024
  • date-long -> Thursday, December 5, 2024
  • time-short -> 12:05 PM
  • time-medium -> 12:05:20 PM
  • datetime-short -> 12/5/2024, 12:05 PM
  • datetime-medium -> December 5, 2024 at 12:05 PM
  • datetime-long -> Thursday, December 5, 2024 at 12:05:20 PM
type IDateTemplate = 'date-short' | 'date-medium' | 'date-long' | 'time-short' | 'time-medium' | 'datetime-short' | 'datetime-medium' | 'datetime-long';

A duration string composed of a numeric value followed by a supported time unit, with or without a space.

type IYears = 'years' | 'year';
type IMonths = 'months' | 'month';
type IWeeks = 'weeks' | 'week';
type IDays = 'days' | 'day';
type IHours = 'hours' | 'hour';
type IMinutes = 'minutes' | 'minute';
type ISeconds = 'seconds' | 'second';
type IMilliseconds = 'milliseconds' | 'millisecond';

export type IUnit =
  | IYears
  | IMonths
  | IWeeks
  | IDays
  | IHours
  | IMinutes
  | ISeconds
  | IMilliseconds;

export type ITimeString = `${number} ${IUnit}`;

The options that can be passed to the applySubstitutions function.

type ISubstitutionOptions = {
  jsonIndent: number;
};

Built With

  • TypeScript

Running the Tests

# integration & unit tests
npm run test

# integration tests
npm run test:integration

# unit tests
npm run test:unit

# benchmarks
npm run test:bench

License

MIT