@codebundlesbyvik/js-helpers
TypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published

js-helpers

npm npm - downloads per week

0-dependency JavaScript helper functions for various operations, used across my projects.


Table of Contents


Compatibility

All helpers are compatible with the ECMAScript 2015 (ES6) specification except for fetchWithTimeout, which is an async function and thus requires an ECMAScript 2017 (ES8) compatible environment.

Some helpers utilize DOM methods and thus requires an environment that supports those.


Usage

With a module bundler

Install the package with npm.

npm install @codebundlesbyvik/js-helpers

Import the helpers you need...

import { getCssPropValue } from "@codebundlesbyvik/js-helpers";

... and compile your project with a module bundler.


Without a module bundler

Download the latest release from GitHub and import the helpers you need as an ES Module.


Functions


  • Required parameters are indicated with *.
  • Default values for required parameters are listed first in the array of accepted parameter value types.

createEl(tagName, attrs)

Create and return an HTMLElement.

Parameters

  • * tagName (String): The HTMLElement's tag name.
  • attrs (Object): Individual attribute - value pairs to set on the HTMLElement.

Special case is the textContent attribute. Use it to set the HTMLElement's textContent.

Example

const ATTRS = {
    class: "example-div",
    id: "example-div-1",
    ariaHidden: "true",
    textContent: "This is an example."
};

createEl("div", ATTRS);

// <div class="example-div" id="example-div-1" aria-hidden="true">
//     This is an example
// </div>

cssDurationToMs(duration)

Convert a CSS-style time duration value to a Number of milliseconds.

If the given value has no or an unrecognized unit, the returned value will be null.

Parameters

  • duration (String): 'CSS-style' time duration.

Supported units

  • ms: Milliseconds
  • s: Seconds
  • h: Hours
  • d: Days
  • w: Weeks

Example

cssDurationToMs("150ms");
// 150

cssDurationToMs("2s");
// 2000

cssDurationToMs("0.25d");
// 21600000

cssDurationToMs("-1w");
// -604800000

cssDurationToMs("1y");
// null

cssDurationToMs("1asdf");
// null

cssDurationToMs("20");
// null

fetchWithTimeout(resource, fetchOptions, timeoutDuration)

Make a fetch() call that's aborted by an AbortController after a specified amount of time.

Parameters

  • * resource (RequestInfo | URL): Location of the resource.
  • fetchOptions ({} | RequestInit): Options accepted by fetch().
  • timeoutDuration (8000 | Number): Time in milliseconds after which AbortController.abort() is called and the fetch() is aborted.

Example

// Make a GET request that's aborted if no response is returned within 8 seconds.
await fetchWithTimeout("https://example.com/api/endpoint");

// Make a POST request that's aborted if no response is returned within 10 seconds.
await fetchWithTimeout("https://example.com/api/endpoint", { method: "POST" }, 10000);

getAverage(array, round)

Get the average of an array of Numbers.

Parameters

  • * array (Number[]): Array to check.
  • round ("floor" | "ceil"): Rounding method to apply to the average.

Example

getAverage([1, 2, 3]);
// 2

getAverage([3, 8, 41, 88, 1024]);
// 232.8

getAverage([3, 8, 41, 88, 1024], "floor");
// 232

getAverage([0.1, 0.33, 0.82, 1], "ceil");
// 1

getCssPropValue(el, prop)

Get an Element's CSS property value.

If the property is not set or unknown, the returned value will be null.

Parameters

  • * el (Element): The target.
  • * prop (String): Element property to retrieve.

Example

const el = document.querySelector("#example-div-1");
// Has the following properties set:
// margin-bottom: 0.75rem;
// background-color: black;

getCssPropValue(el, "margin-bottom");
// "0.75rem"

getCssPropValue(el, "background-color");
// "black"

getCssPropValue(el, "box-shadow");
// null

getCssPropValue(el, "non-existent");
// null

getCssUnit(value)

Get the unit of a quantitative 'CSS-style' value.

If the value has no unit, the returned value will be null.

Parameters

  • value (String): 'CSS-style' value to get the unit from.

Example

getCssUnit("2px");
// "px"

getCssUnit(".5ms");
// "ms"

getCssUnit("100");
// null

getPseudoRandomIntBetween(min, max)

Generate and return a positive pseudo-random integer between two given integers.

⚠️ Makes use of Math.random(), which ISN'T cryptographically secure. YOU WILL BE FIRED if you misuse this function in an attempt to generate secure, random integers. ⚠️

Parameters

  • None
  • * min (Number): Positive integer relative to which the returned integer will be equal to or greater than.
  • * max (Number): Positive integer relative to which the returned integer will be smaller than.

Example

getPseudoRandomIntBetween(0, 10);
// 7

isMotionAllowed()

Check if prefers-reduced-motion is set to something other than reduce. Returns a Boolean.

Example

// 'prefers-reduced-motion' is set to 'reduce'.
isMotionAllowed();
// false

// 'prefers-reduced-motion' is set to 'no-preference'.
isMotionAllowed();
// true

// 'prefers-reduced-motion' is unsupported.
isMotionAllowed();
// true

wait(duration, resolveValue, abortSignal)

Wait for a given amount of time before continuing script execution.

setTimeout() wrapped in a Promise, which is optionally resolved with resolveValue and cancellable via an AbortController.

Parameters

  • * duration (Number): Time in milliseconds after which script execution will continue.
  • resolveValue (Any valid Promise.resolve() value): Value which the promise will be resolved with.
  • abortSignal (AbortSignal): AbortController.signal which the timeout can be cancelled with.

Example

// Wait for 3 seconds before doing something else.
await wait(3000);

// Wait for 5 seconds before doing something else - or less if aborted earlier.
const abortController = new AbortController();
await wait(5000, "5 seconds have passed", abortController.signal);

Migrating

From version 1

Function parameters are now type checked. The following breaking changes were made:

  • Removed createEls()
    • Write this code yourself - it was just a for loop.
  • Removed getRandomIntUnder()
    • Use getPseudoRandomIntBetween(0, x) instead.
  • getCssUnit(): Removed support for y unit - will now return null.
  • wait(): Now takes in an abortSignal instead of an abortController.

From @codebundlesbyvik/js-*-operations

Function parameters are now type checked. The following breaking changes were made:

  • Removed createEls()
    • Write this code yourself - it was just a for loop.
  • Removed getRandomIntUnder()
    • Use getPseudoRandomIntBetween(0, x) instead.
  • Renamed getPropValue() > getCssPropValue()
  • Renamed getUnit() > getCssUnit()
  • Renamed timeToMs() > cssDurationToMs()

More changes were made other than the ones listed above. Problems caused by incompatible changes should be easy to debug by the error thrown.


License

MIT © 2024 Viktor Chin-Kon-Sung

Package Sidebar

Install

npm i @codebundlesbyvik/js-helpers

Weekly Downloads

7

Version

2.1.0

License

MIT

Unpacked Size

21.7 kB

Total Files

33

Last publish

Collaborators

  • codebundlesbyvik