2.18.3 • Published 4 months ago

@qntm-code/utils v2.18.3

Weekly downloads
33
License
MIT
Repository
github
Last release
4 months ago

@qntm-code/utils

A collection of useful utility functions with associated TypeScript types.

GitHub release Tests codecov Quality Gate Status Reliability Rating Vulnerabilities Bugs Security Rating Maintainability Rating

Install

You can install via npm or yarn.

npm

npm install --save @qntm-code/utils

yarn

yarn add @qntm-code/utils

Documentation

This documentation is written in TypeScript, however this library works fine in vanilla JavaScript too.

Generic Helpers


isNullOrUndefined

Determines whether a given value is null or undefined.

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isNullOrUndefined } from '@qntm-code/utils';

const value = getTheValue();

if (isNullOrUndefined(value)) {
  // Do something
}

clone

Recursively (deep) clones native types, like Object, Array, RegExp, Date, Map, Set, Symbol, Error, moment as well as primitives.

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to clone
instanceClone((value: T) => T) or booleantrueSee description below

Return type: T

instanceClone

This paramater specifies whether or not to clone instances (objects that are from a custom class or are not created by the Object constructor. This value may be true or the function use for cloning instances.

When an instanceClone function is provided, it will be invoked to clone objects that are not "plain" objects (as defined by isPlainObject). If instanceClone is not specified, the function will not attempt to clone non-plain objects, and will simply copy the object reference.

Example:

import { clone } from '@qntm-code/utils';

const value: number[] = [1, 2, 3];
const clonedValues = clone(value);
clone performance comparison

The following benchmarks were run on a 2023 Macbook Pro with a M2 Pro chip and 32GB of RAM.

PackageOperations per second
@qntm-code/utils.clone127338
clone-deep115475
lodash.cloneDeep73027

merge

Merges two objects x and y deeply, returning a new merged object with the elements from both x and y.

If an element at the same key is present for both x and y, the value from y will appear in the result.

Merging creates a new object, so that neither x or y is modified.

Note: By default, arrays are merged by concatenating them.

Method arguments:

ParameterTypeOptionalDescription
xanyfalseThe first object to merge
yanyfalseThe second object to merge
optionsanytrueSee description below
merge options
arrayMerge

There are multiple ways to merge two arrays, below are a few examples but you can also create your own custom function.

Your arrayMerge function will be called with three arguments: a target array, the source array, and an options object with these properties:

  • isMergeableObject(value)
  • cloneUnlessOtherwiseSpecified(value, options)

example: overwrite target array:

Overwrites the existing array values completely rather than concatenating them:

import { merge } from '@qntm-code/utils';

const overwriteMerge = (destinationArray, sourceArray, options) => sourceArray;

merge([1, 2, 3], [3, 2, 1], { arrayMerge: overwriteMerge }); // => [3, 2, 1]

example: combine arrays:

Combines objects at the same index in the two arrays.

import { merge } from '@qntm-code/utils';

const combineMerge = (target, source, options) => {
  const destination = target.slice();

  source.forEach((item, index) => {
    if (typeof destination[index] === 'undefined') {
      destination[index] = options.cloneUnlessOtherwiseSpecified(item, options);
    } else if (options.isMergeableObject(item)) {
      destination[index] = merge(target[index], item, options);
    } else if (target.indexOf(item) === -1) {
      destination.push(item);
    }
  });
  return destination;
};

merge([{ a: true }], [{ b: true }, 'ah yup'], { arrayMerge: combineMerge }); // => [{ a: true, b: true }, 'ah yup']
isMergableObject

By default, merge clones every property from almost every kind of object.

You may not want this, if your objects are of special types, and you want to copy the whole object instead of just copying its properties.

You can accomplish this by passing in a function for the isMergeableObject option.

If you only want to clone properties of plain objects, and ignore all "special" kinds of instantiated objects, you probably want to drop in isPlainObject.

import { merge, isPlainObject } from '@qntm-code/utils';

function SuperSpecial() {
  this.special = 'oh yeah man totally';
}

const instantiatedSpecialObject = new SuperSpecial();

const target = {
  someProperty: {
    cool: 'oh for sure',
  },
};

const source = {
  someProperty: instantiatedSpecialObject,
};

const defaultOutput = merge(target, source);

defaultOutput.someProperty.cool; // => 'oh for sure'
defaultOutput.someProperty.special; // => 'oh yeah man totally'
defaultOutput.someProperty instanceof SuperSpecial; // => false

const customMergeOutput = merge(target, source, {
  isMergeableObject: isPlainObject,
});

customMergeOutput.someProperty.cool; // => undefined
customMergeOutput.someProperty.special; // => 'oh yeah man totally'
customMergeOutput.someProperty instanceof SuperSpecial; // => true
customMerge

Specifies a function which can be used to override the default merge behaviour for a property, based on the property name.

The customMerge function will be passed the key for each property, and should return the function which should be used to merge the values for that property.

It may also return undefined, in which case the default merge behaviour will be used.

const alex = {
  name: {
    first: 'Alex',
    last: 'Alexson',
  },
  pets: ['Cat', 'Parrot'],
};

const tony = {
  name: {
    first: 'Tony',
    last: 'Tonison',
  },
  pets: ['Dog'],
};

const mergeNames = (nameA, nameB) => `${nameA.first} and ${nameB.first}`;

const options = {
  customMerge: key => {
    if (key === 'name') {
      return mergeNames;
    }
  },
};

const result = merge(alex, tony, options);

result.name; // => 'Alex and Tony'
result.pets; // => ['Cat', 'Parrot', 'Dog']
Merge performance comparison

The following benchmarks go through the merge test suite and were run on a 2023 Macbook Pro with a M2 Pro chip and 32GB of RAM.

PackageOperations per second
@qntm-code/utils.merge28332
deepmerge23497

difference

Creates an array of array values not included in the other given array using isEqual for equality comparisons. The order and references of result values are determined by the first array.

Method arguments:

ParameterTypeOptionalDescription
arrayArrayfalseThe array to check
valuesArrayfalseThe array to check against

Return type: Array<any>

Example:

import { difference } from '@qntm-code/utils';

const diff = difference([1, 2], [2, 3]);
// returns [1]

formatTime

Formats a given time to a human readable string.

Method arguments:

ParameterTypeOptionalDescription
timenumberfalseThe time to format
optionsFormatTimeOptionstrueThe options to use for formatting

Return type: string

Example:

import { formatTime } from '@qntm-code/utils';

const formattedTime = formatTime(71000, {
  hourSuffix: ' HOURS',
  minuteSuffix: ' MINUTES',
  secondSuffix: ' SECONDS',
});

// formattedTime = '00 HOUR 01 MINUTE 11 SECONDS'
FormatTimeOptions
ParameterTypeDefaultDescription
forceAllUnitsbooleantrueWhether to force all units to be displayed
timeUnitTimeUnitTimeUnit.MillisecondsThe time unit that is being provided
secondsDecimalPlacesnumber0The number of decimal places to display for seconds
padDecimalsbooleanfalseWhether to pad decimals with 0s to match the number provided for secondsDecimalPlaces
hourSuffixstringhThe suffix to use for hours
minuteSuffixstringmThe suffix to use for minutes
secondSuffixstringsThe suffix to use for seconds

insertAtIndex

Inserts a string value at a given index in a source string.

Method arguments:

ParameterTypeOptionalDescription
sourcestringfalseThe source string
valuestringfalseThe value to insert
indexnumberfalseThe index to insert at

Return type: string

import { insertAtIndex } from '@qntm-code/utils';

insertAtIndex('<strong>', '/', 1);

// returns '</strong>'

isBoolean

Checks if a given value is a boolean.

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isBoolean } from '@qntm-code/utils';

const value = getBoolean();

if (isBoolean(value)) {
  // Do something
}

isDate

Checks if a given value is a Date object.

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isDate } from '@qntm-code/utils';

const value = getDate();

if (isDate(value)) {
  // Do something
}

isEmpty

Checks if a given value is empty.

Method arguments:

ParameterTypeOptionalDescription
valuestring, Array, objectfalseThe value to check

Return type: boolean

Example:

import { isEmpty } from '@qntm-code/utils';

const value: string = getName();

if (isEmpty(value)) {
  // Do something
}

isNaNStrict

Determines whether a given value is a NaN instance

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isNaNStrict } from '@qntm-code/utils';

const value = getTheValue();

if (isNaNStrict(value)) {
  // Do something
}

isNumber

Determines whether a given value is a number

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isNumber } from '@qntm-code/utils';

const value = getTheValue();

if (isNumber(value)) {
  // Do something
}

isObject

Determines whether a given value is an object

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isObject } from '@qntm-code/utils';

const value = getTheValue();

if (isObject(value)) {
  // Do something
}

isString

Determines whether a given value is a string

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isString } from '@qntm-code/utils';

const value = getTheValue();

if (isString(value)) {
  // Do something
}

isEqual

Performs a deep comparison between two values to determine if they are equivalent.

Note: This method supports comparing nulls, undefineds, booleans, numbers, strings, Dates, objects, Functions, Arrays, RegExs, Maps, Sets, Typed Arrays, and Moments.

Object objects are compared by their own, not inherited, enumerable properties.

Functions and DOM nodes are compared by strict equality, i.e. ===.

The order of the array items must be the same for the arrays to be equal.

Method arguments:

ParameterTypeOptionalDescription
aEqualityTypefalseThe first value to compare
bEqualityTypefalseThe second value to compare

Return type: boolean

Example:

import { isEqual } from '@qntm-code/utils';

const a: Array<number> = getSensorAReadings();
const b: Array<number> = getSensorBReadings();

if (isEqual(a, b)) {
  // Do a thing
}
isEqual performance comparison

The following benchmarks go through the isEqual test suite and were run on a 2023 Macbook Pro with a M2 Pro chip and 32GB of RAM.

PackageOperations per second
@qntm-code/utils.isEqual218781
fast-deep-equal192329
underscore.isEqual65518
util.isDeepStrictEqual39740
lodash.isEqual18842
ramda.equals10231
assert.deepStrictEqual215

To run the benchmarks yourself, clone the repo, install the dependencies and run yarn benchmark.

EqualityType

An EqualityType can be an IndividualEqualityType or an array of mixed IndividualEqualityTypes

IndividualEqualityType

The equality types allowed are:

  • null
  • undefined
  • boolean
  • number
  • string
  • Date
  • object
  • Function

isRegExp

Determines whether a given value is a regular expression

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isRegExp } from '@qntm-code/utils';

const value = getTheValue();

if (isRegExp(value)) {
  // Do something
}

isArguments

Determines whether a given value is an arguments object

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isArguments } from '@qntm-code/utils';

const value = getTheValue();

if (isArguments(value)) {
  // Do something
}

isBuffer

Determines whether a given value is a buffer

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isBuffer } from '@qntm-code/utils';

const value = getTheValue();

if (isBuffer(value)) {
  // Do something
}

isError

Determines whether a given value is an error

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isError } from '@qntm-code/utils';

const value = getTheValue();

if (isError(value)) {
  // Do something
}

isGeneratorObject

Determines whether a given value is a generator object

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isGeneratorObject } from '@qntm-code/utils';

const value = getTheValue();

if (isGeneratorObject(value)) {
  // Do something
}

isPlainObject

Determines whether a given value is a plain object

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isPlainObject } from '@qntm-code/utils';

const value = getTheValue();

if (isPlainObject(value)) {
  // Do something
}

isReactElement

Determines whether a given value is a React element

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: boolean

Example:

import { isReactElement } from '@qntm-code/utils';

const value = getTheValue();

if (isReactElement(value)) {
  // Do something
}

typeOf

Returns the type of a given value

Method arguments:

ParameterTypeOptionalDescription
valueanyfalseThe value to check

Return type: ValueType | string

Example:

import { typeOf, ValueType } from '@qntm-code/utils';

const value = getTheValue();

if (typeOf(value) === ValueType.string) {
  // Do something
}

randomNumberBetweenRange

Returns a random whole number between a given range

Method arguments:

ParameterTypeOptionalDescription
minnumberfalseThe minimum number the function can return
maxnumberfalseThe maximum number the function can return

Return type: number

Example:

import { randomNumberBetweenRange } from '@qntm-code/utils';

const random = randomNumberBetweenRange(2, 10);

Async helpers


asyncEvery

Allows you to run Array.every() with an async predicate function and await the result.

Method arguments:

ParameterTypeOptionalDescription
itemsArrayfalseThe items to iterate over
predicateFunctionfalseA predicate function to run for each item

Callback arguments:

ParameterTypeOptionalDescription
itemTtrueThe current item from the loop
indexnumbertrueThe index of the given in the array
arrayArraytrueThe array provided

Return type:

Promise<boolean>;

Example:

import { asyncEvery } from '@qntm-code/utils';

async function doAThing(): Promise<void> {
  // Array of items to iterate over
  const items: Array<string> = ['a', 'b', 'c'];

  const result = await asyncEvery(items, async item => await someAsynchronousOperation(item));

  functionToRunWhenAllItemsAreProcessed(result);
}

asyncFilter

Allows you to run Array.filter() with an async predicate function and await the result.

Method arguments:

ParameterTypeOptionalDescription
itemsArrayfalseThe items to iterate over
predicateFunctionfalseA predicate function to run for each item

Callback arguments:

ParameterTypeOptionalDescription
itemTtrueThe current item from the loop
indexnumbertrueThe index of the given in the array
arrayArraytrueThe array provided

Return type:

Promise<T[]>;

Example:

import { asyncFilter } from '@qntm-code/utils';

async function doAThing(): Promise<void> {
  // Array of items to iterate over
  const items: Array<string> = ['a', 'b', 'c'];

  const results = await asyncFilter(items, async item => await someAsynchronousOperation(item));

  functionToRunWhenAllItemsAreProcessed(results);
}

asyncForEach

Allows you to iterate over an array asynchronously.

Method arguments:

ParameterTypeOptionalDescription
itemsArrayfalseThe items to iterate over
callbackFunctionfalseA callback function to run for each item

Callback arguments:

ParameterTypeOptionalDescription
itemTtrueThe current item from the loop
indexnumbertrueThe index of the given in the array
arrayArraytrueThe array provided

Return type:

Promise<void>;

Example:

import { asyncForEach } from '@qntm-code/utils';

async function doAThing(): Promise<void> {
  // Array of items to iterate over
  const items: Array<string> = ['a', 'b', 'c'];

  await asyncForEach(items, async item => await someAsynchronousOperation(item));

  functionToRunWhenAllItemsAreProcessed();
}

asyncSome

Allows you to run Array.some() with an async predicate function and await the result.

Method arguments:

ParameterTypeOptionalDescription
itemsArrayfalseThe items to iterate over
predicateFunctionfalseA predicate function to run for each item

Callback arguments:

ParameterTypeOptionalDescription
itemTtrueThe current item from the loop
indexnumbertrueThe index of the given in the array
arrayArraytrueThe array provided

Return type:

Promise<boolean>;

Example:

import { asyncSome } from '@qntm-code/utils';

async function doAThing(): Promise<void> {
  // Array of items to iterate over
  const items: Array<string> = ['a', 'b', 'c'];

  const result = await asyncSome(items, async item => await someAsynchronousOperation(item));

  functionToRunWhenAllItemsAreProcessed(result);
}

delay

Delays an async function using await given an optionally provided duration.

Method arguments:

ParameterTypeOptionalDescription
durationnumbertrueThe number of milliseconds to delay by

Return type:

Promise<void>;

Example:

import { delay } from '@qntm-code/utils';

async function doAThing(): Promise<void> {
  const value = calculateAThing();

  await delay(200);

  operateOnCalculatedValue(value);
}

Date helpers


convertTimeUnit

Converts a value of a given TimeUnit into another TimeUnit.

Method arguments:

ParameterTypeOptionalDescription
valuenumberfalseThe value to convert
sourceUnitTimeUnit (Excluding Month/Months and Year/Years)falseThe time unit the provided value is in
resultUnitTimeUnit (Excluding Month/Months and Year/Years)falseThe time unit you wish to convert your value to

Return type: number

Example:

import { convertTimeUnit, TimeUnit } from '@qntm-code/utils';

const weeks: number = 24;
const minutes: number = convertTimeUnit(weeks, TimeUnit.Weeks, TimeUnit.Minutes);

Vanilla JS Example:

import { convertTimeUnit } from '@qntm-code/utils';

const weeks = 24;
const minutes = convertTimeUnit(weeks, 'weeks', 'minutes');

msToUnit

Converts milliseconds into a TimeUnit.

Method arguments:

ParameterTypeOptionalDescription
valuenumberfalseThe value in milliseconds
unitTimeUnit (Excluding Month/Months and Year/Years)falseThe time unit you wish to convert your value to

Return type: number

Example:

import { msToUnit, TimeUnit } from '@qntm-code/utils';

const milliseconds: number = 4567876;
const hours: number = msToUnit(milliseconds, TimeUnit.Hours);

Example:

import { msToUnit } from '@qntm-code/utils';

const milliseconds = 4567876;
const hours = msToUnit(milliseconds, 'hours');

unitToMs

Converts a TimeUnit into milliseconds.

Method arguments:

ParameterTypeOptionalDescription
valuenumberfalseThe value to convert
unitTimeUnit (Excluding Month/Months and Year/Years)falseThe time unit of the value you provided

Return type: number

Example:

import { unitToMs, TimeUnit } from '@qntm-code/utils';

const days: number = 10;
const milliseconds: number = unitToMs(days, TimeUnit.Days);

Example:

import { unitToMs } from '@qntm-code/utils';

const days = 10;
const milliseconds = unitToMs(days, 'days');

compareDates

Determines if date a is before/before or same/same/after or same/or after to date b. If you want to limit the granularity to a unit other than milliseconds, pass it as the second parameter.

When including a second parameter, it will match all units equal or larger. For example, if passing in month will check month and year, or if passing in day will check day, month, and year.

ParameterTypeOptionalDescription
aDatefalseThe first date to compare
comparatorDateComparatorfalseThe comparator to use for the comparison
bDatefalseThe second date to compare
unitTimeUnittrueThe time unit to limit the comparison to.
Defaults to milliseconds if omitted

Return type: boolean

Example:

import { compareDates, DateComparator, TimeUnit } from '@qntm-code/utils';

const a: Date = new Date(2023, 0, 1, 12, 0, 0, 0);
const b: Date = new Date(2023, 0, 1, 9, 0, 1, 12);

compareDates(a, DateComparator.Before, b, TimeUnit.Year); // false
compareDates(a, DateComparator.BeforeOrSame, b, TimeUnit.Day); // true
compareDates(a, DateComparator.Same, b, TimeUnit.Month); // true
compareDates(a, DateComparator.AfterOrSame, b, TimeUnit.Hour); // true
compareDates(a, DateComparator.After, b, TimeUnit.Minute); // false

DateComparator

A TypeScript enum of available options to provide to date comparison functions. For vanilla JS just use the string values from the value column.

Enum KeyValue
Before<
BeforeOrSame<=
Same===
AfterOrSame>=
After>

TimeUnit

A TypeScript enum of available options to provide to time unit conversion functions. For vanilla JS just use the string values from the value column.

Enum KeyValue
Millisecondmillisecond
Millisecondsmilliseconds
Secondsecond
Secondsseconds
Minuteminute
Minutesminutes
Hourhour
Hourshours
Dayday
Daysdays
Weekweek
Weeksweeks
Monthmonth
Monthsmonths
Yearyear
Yearsyears

isSameDate

Determines if two dates are the same. If you want to limit the granularity to a unit other than milliseconds, pass it as the second parameter.

When including a second parameter, it will match all units equal or larger. For example, if passing in month will check month and year, or if passing in day will check day, month, and year.

Method arguments:

ParameterTypeOptionalDescription
aDatefalseThe first date to compare
bDatefalseThe second date to compare
unitTimeUnittrueThe time unit to limit the comparison to. Defaults to milliseconds if omitted

Return type: boolean

Example:

import { isSameDate, TimeUnit } from '@qntm-code/utils';

const a: Date = new Date(2023, 0, 1, 12, 0, 0, 0);
const b: Date = new Date(2023, 0, 1, 9, 0, 1, 12);
const c: Date = new Date(2023, 6, 1, 0, 0, 0, 0);

if (isSameDate(a, b)) {
  // This will not run as the dates are not the same
}

if (isSameDate(a, b, TimeUnit.Day)) {
  // This will run as the dates are the same day
}

if (isSameDate(a, b, TimeUnit.Hour)) {
  // This will not run as the dates are not the same hour
}

if (isSameDate(a, c, TimeUnit.Day)) {
  // This will not run because even though the dates are the same day, the months are not the same
}

addToDate

Returns a new date object with a given amount of a given TimeUnit added to it.

ParameterTypeDescription
dateDateThe date to add to
amountanyThe amount to add
unitTimeUnitThe unit to add

Example:

import { addToDate, TimeUnit } from '@qntm-code/utils';

const date: Date = new Date();

const thisTimeTomorrow: Date = addToDate(date, 1 TimeUnit.Day);
Special considerations for months and years

If the day of the month on the original date is greater than the number of days in the final month, the day of the month will change to the last day in the final month.

import { addToDate, TimeUnit } from '@qntm-code/utils';

const date: Date = new Date('2023-01-31'); // 31 January

const nextMonth: Date = addToDate(date, 1, TimeUnit.Month); // 28 February

There are also special considerations to keep in mind when adding time that crosses over daylight saving time. If you are adding years, months, weeks, or days, the original hour will always match the added hour.

Adding a month will add the specified number of months to the date.

const date = new Date('2023-02-28'); // February 28
const newDate = addToDate(date, 1, TimeUnit.Month); // March 28
const date = new Date('2023-03-25T06:00:00.000Z'); // The day before BST in the UK
date.getHours(); // 6
const newDate = addToDate(date, 1, TimeUnit.Day).getHours(); // 6

If you are adding hours, minutes, seconds, or milliseconds, the assumption is that you want precision to the hour, and will result in a different hour.

const date = new Date('2023-03-25T06:00:00.000Z'); // The day before BST in the UK
date.getHours(); // 6
const newDate = addToDate(date, 24, TimeUnit.Hours).getHours(); // 7

subtractFromDate

Returns a new date object with a given amount of a given TimeUnit subracted from it.

This is exactly the same as moment#add, only instead of addToDate, it subtracts time.

ParameterTypeDescription
dateDateThe date to subtract from
amountanyThe amount to subtract
unitTimeUnitThe unit to subtract

Example:

import { subtractFrom, TimeUnit } from '@qntm-code/utils';

const date: Date = new Date();

const thisTimeTomorrow: Date = subtractFrom(date, 1 TimeUnit.Day);

getToday

Gets a Date for the start of the given day.

Return type: Date

Example:

import { getToday } from '@qntm-code/utils';

const today: Date = getToday();

getWeekOfYear

Gets the week number of the year for the given date. It will use today's date if no date is provided.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: number

Example:

import { getWeekOfYear } from '@qntm-code/utils';

const weekNumber: number = getWeekOfYear(new Date('2023-12-30')); // 52

getMonthNames

Gets the month names for the provided locale.

ParameterTypeOptionalDefault valueDescription
optionsGetMonthNamesOptions{ locale: navigator.language, format: 'long' }The options to use when getting the month names

Return type: Array<string>

Example:

import { getMonthNames, GetMonthNamesOptions } from '@qntm-code/utils';

const options: GetMonthNamesOptions = {
  locale: 'en-GB',
  format: 'short',
};

const monthNames: Array<string> = getMonthNames(options); // ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', Dec']
GetMonthNamesOptions
ParameterTypeOptionalDefault valueDescription
localestringtruenavigator.languageThe locale to use when getting the month names
formatstringtruelongThe format to use when getting the month names. Options are numeric, 2-digit, long, short, or narrow

getEndOfDay

Takes an optional date and returns a new Date object set to the end of the given/current day.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getEndOfDay } from '@qntm-code/utils';

const endOfCurrentDay: Date = getEndOfDay();

getEndOfHour

Takes an optional date and returns a new Date object set to the end of the given/current hour.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getEndOfHour } from '@qntm-code/utils';

const endOfCurrentHour: Date = getEndOfHour();

getEndOfMinute

Takes an optional date and returns a new Date object set to the end of the given/current minute.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getEndOfMinute } from '@qntm-code/utils';

const endOfCurrentMinute: Date = getEndOfMinute();

getEndOfMonth

Takes an optional date and returns a new Date object set to the end of the given/current month.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getEndOfMonth } from '@qntm-code/utils';

const endOfCurrentMonth: Date = getEndOfMonth();

getEndOfSecond

Takes an optional date and returns a new Date object set to the end of the given/current second.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getEndOfSecond } from '@qntm-code/utils';

const endOfCurrentSecond: Date = getEndOfSecond();

getEndOfWeek

Takes an optional date and returns a new Date object set to the end of the given/current week.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getEndOfWeek } from '@qntm-code/utils';

const endOfCurrentWeek: Date = getEndOfWeek();

getEndOfYear

Takes an optional date and returns a new Date object set to the end of the given/current year.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getEndOfYear } from '@qntm-code/utils';

const endOfCurrentYear: Date = getEndOfYear();

getStartOfDay

Takes an optional date and returns a new Date object set to the start of the given/current day.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getStartOfDay } from '@qntm-code/utils';

const startOfCurrentDay: Date = getStartOfDay();

getStartOfHour

Takes an optional date and returns a new Date object set to the start of the given/current hour.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getStartOfHour } from '@qntm-code/utils';

const startOfCurrentHour: Date = getStartOfHour();

getStartOfMinute

Takes an optional date and returns a new Date object set to the start of the given/current minute.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getStartOfMinute } from '@qntm-code/utils';

const startOfCurrentMinute: Date = getStartOfMinute();

getStartOfMonth

Takes an optional date and returns a new Date object set to the start of the given/current month.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getStartOfMonth } from '@qntm-code/utils';

const startOfCurrentMonth: Date = getStartOfMonth();

getStartOfSecond

Takes an optional date and returns a new Date object set to the start of the given/current second.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getStartOfSecond } from '@qntm-code/utils';

const startOfCurrentSecond: Date = getStartOfSecond();

getStartOfWeek

Takes an optional date and returns a new Date object set to the start of the given/current week.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getStartOfWeek } from '@qntm-code/utils';

const startOfCurrentWeek: Date = getStartOfWeek();

getStartOfYear

Takes an optional date and returns a new Date object set to the start of the given/current year.

ParameterTypeOptionalDefault valueDescription
dateDatetruenew Date()The date to modify

Return type: Date

Example:

import { getStartOfYear } from '@qntm-code/utils';

const startOfCurrentYear: Date = getStartOfYear();

setEndOfDay

Takes a given date and mutates it to the end of the given day.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setEndOfDay } from '@qntm-code/utils';

const now: Date = new Date();
const endOfCurrentDay: Date = setEndOfDay(now);

setEndOfHour

Takes a given date and mutates it to the end of the given hour.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setEndOfHour } from '@qntm-code/utils';

const now: Date = new Date();
const endOfCurrentHour: Date = setEndOfHour(now);

setEndOfMinute

Takes a given date and mutates it to the end of the given minute.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setEndOfMinute } from '@qntm-code/utils';

const now: Date = new Date();
const endOfCurrentMinute: Date = setEndOfMinute(now);

setEndOfMonth

Takes a given date and mutates it to the end of the given month.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setEndOfMonth } from '@qntm-code/utils';

const now: Date = new Date();
const endOfCurrentMonth: Date = setEndOfMonth(now);

setEndOfSecond

Takes a given date and mutates it to the end of the given second.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setEndOfSecond } from '@qntm-code/utils';

const now: Date = new Date();
const endOfCurrentSecond: Date = setEndOfSecond(now);

setEndOfWeek

Takes a given date and mutates it to the end of the given week.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setEndOfWeek } from '@qntm-code/utils';

const now: Date = new Date();
const endOfCurrentWeek: Date = setEndOfWeek(now);

setEndOfYear

Takes a given date and mutates it to the end of the given year.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setEndOfYear } from '@qntm-code/utils';

const now: Date = new Date();
const endOfCurrentYear: Date = setEndOfYear(now);

setStartOfDay

Takes a given date and mutates it to the start of the given day.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setStartOfDay } from '@qntm-code/utils';

const now: Date = new Date();
const startOfCurrentDay: Date = setStartOfDay(now);

setStartOfHour

Takes a given date and mutates it to the start of the given hour.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setStartOfHour } from '@qntm-code/utils';

const now: Date = new Date();
const startOfCurrentHour: Date = setStartOfHour(now);

setStartOfMinute

Takes a given date and mutates it to the start of the given minute.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setStartOfMinute } from '@qntm-code/utils';

const now: Date = new Date();
const startOfCurrentMinute: Date = setStartOfMinute(now);

setStartOfMonth

Takes a given date and mutates it to the start of the given month.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setStartOfMonth } from '@qntm-code/utils';

const now: Date = new Date();
const startOfCurrentMonth: Date = setStartOfMonth(now);

setStartOfSecond

Takes a given date and mutates it to the start of the given second.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setStartOfSecond } from '@qntm-code/utils';

const now: Date = new Date();
const startOfCurrentSecond: Date = setStartOfSecond(now);

setStartOfWeek

Takes a given date and mutates it to the start of the given week.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setStartOfWeek } from '@qntm-code/utils';

const now: Date = new Date();
const startOfCurrentWeek: Date = setStartOfWeek(now);

setStartOfYear

Takes a given date and mutates it to the start of the given year.

ParameterTypeOptionalDescription
dateDatefalseThe date to modify

Return type: Date

Example:

import { setStartOfYear } from '@qntm-code/utils';

const now: Date = new Date();
const startOfCurrentYear: Date = setStartOfYear(now);

DOM helpers


getAncestors

Gets all the elements that a given element is nested within

ParameterTypeOptionalDefault valueDescription
elementHTMLElementfalseThe HTML element you want to find the ancestors for

Example:

import { getAncestors } from '@qntm-code/utils';

const ancestors: HTMLElement[] = getAncestors(document.getElementById('my-element'));

getNonInlineParent

Gets the first parent of an element that isn't display: inline. Returns null if no matching element

ParameterTypeOptionalDefault valueDescription
elementHTMLElementfalseThe HTML element you want to non display: inline parent for

Example:

import { getNonInlineParent } from '@qntm-code/utils';

const nonInlineParent: HTMLElement | null = getNonInlineParent(document.getElementById('my-element'));

getPositionedParent

Gets the first parent element with a relative or absolute position

ParameterTypeOptionalDefault valueDescription
elementHTMLElementfalseThe HTML element you want to find the ancestors for

Example:

import { getPositionedParent } from '@qntm-code/utils';

const ancestors: HTMLElement = getPositionedParent(document.getElementById('my-element'));

getScrollParent

Gets the scrollable parent element of a given element

ParameterTypeOptionalDefault valueDescription
elementHTMLElementfalseThe HTML element you want to find the scroll parent for
xbooleantruetrueWhether to check if the element can scroll on the x axis
ybooleantruetrueWhether to check if the element can scroll on the y axis

Example:

import { getScrollParent } from '@qntm-code/utils';

const scrollParent: HTMLElement | null = getScrollParent(document.getElementById('my-element'));

isDisplayInline

Return whether an element is display: inline

ParameterTypeOptionalDefault valueDescription
elementHTMLElementfalseThe HTML element you want to check for display: inline

Example:

import { isDisplayInline } from '@qntm-code/utils';

const inline: boolean = isDisplayInline(document.getElementById('my-element'));

isVisible

Return whether an element is practically visible, considering things like dimensions of 0, opacity, visibility: hidden and overflow: hidden, and whether the item is scrolled off screen

ParameterTypeOptionalDefault valueDescription
elementHTMLElementfalseThe HTML element you want to check for visibility

Example:

import { isVisible } from '@qntm-code/utils';

const visible: boolean = isVisible(document.getElementById('my-element'));

Types


Dictionary

Reusable dictionary type for typed maps

Example:

import { Dictionary } from '@qntm-code/utils';

const dictionary: Dictionary<string> = {
  a: 'yes',
  b: 'no',
};

Attribution

2.18.3

4 months ago

2.18.2

4 months ago

2.18.1

5 months ago

2.17.0

10 months ago

2.18.0

10 months ago

2.15.1

11 months ago

2.16.0

10 months ago

2.15.0

1 year ago

2.13.0

1 year ago

2.14.0

1 year ago

2.11.0

1 year ago

2.12.0

1 year ago

2.10.0

1 year ago

2.9.0

1 year ago

2.12.1

1 year ago

2.8.1

1 year ago

1.7.3

2 years ago

1.2.4

2 years ago

2.8.0

1 year ago

2.7.4

2 years ago

2.7.3

2 years ago

2.7.5

2 years ago

1.7.5

2 years ago

1.7.4

2 years ago

2.7.2

2 years ago

2.7.1

2 years ago

2.7.0

2 years ago

2.6.3

2 years ago

2.6.2

3 years ago

2.6.1

3 years ago

2.6.0

3 years ago

2.5.0

3 years ago

2.4.1

3 years ago

2.4.0

3 years ago

2.5.2

3 years ago

2.5.1

3 years ago

2.4.2

3 years ago

2.5.3

3 years ago

2.3.0

3 years ago

2.2.0

3 years ago

2.1.0

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.2.3

3 years ago

1.2.2

3 years ago

1.2.1

3 years ago

1.2.0

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.1

4 years ago

1.0.0

4 years ago