0-dependency JavaScript helper functions for various operations, used across my projects.
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.
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.
Download the latest release from GitHub and import the helpers you need as an ES Module.
- createEl
- cssDurationToMs
- fetchWithTimeout
- getAverage
- getCssPropValue
- getCssUnit
- getPseudoRandomIntBetween
- isMotionAllowed
- wait
- Required parameters are indicated with *.
- Default values for required parameters are listed first in the array of accepted parameter value types.
Create and return an HTMLElement
.
-
*
tagName
(String
): TheHTMLElement
's tag name. -
attrs
(Object
): Individual attribute - value pairs to set on theHTMLElement
.
Special case is the textContent
attribute. Use it to set the HTMLElement
's textContent
.
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>
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
.
-
duration
(String
): 'CSS-style' time duration.
-
ms
: Milliseconds -
s
: Seconds -
h
: Hours -
d
: Days -
w
: Weeks
cssDurationToMs("150ms");
// 150
cssDurationToMs("2s");
// 2000
cssDurationToMs("0.25d");
// 21600000
cssDurationToMs("-1w");
// -604800000
cssDurationToMs("1y");
// null
cssDurationToMs("1asdf");
// null
cssDurationToMs("20");
// null
Make a fetch()
call that's aborted by an AbortController
after a specified amount of time.
-
*
resource
(RequestInfo | URL
): Location of the resource. -
fetchOptions
({} | RequestInit
): Options accepted byfetch()
. -
timeoutDuration
(8000 | Number
): Time in milliseconds after whichAbortController.abort()
is called and thefetch()
is aborted.
// 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);
Get the average of an array of Number
s.
-
*
array
(Number[]
): Array to check. -
round
("floor" | "ceil"
): Rounding method to apply to the average.
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
Get an Element
's CSS property value.
If the property is not set or unknown, the returned value will be null
.
-
*
el
(Element
): The target. -
*
prop
(String
):Element
property to retrieve.
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
Get the unit of a quantitative 'CSS-style' value.
If the value has no unit, the returned value will be null
.
-
value
(String
): 'CSS-style' value to get the unit from.
getCssUnit("2px");
// "px"
getCssUnit(".5ms");
// "ms"
getCssUnit("100");
// null
Generate and return a positive pseudo-random integer between two given integers.
- 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.
getPseudoRandomIntBetween(0, 10);
// 7
Check if prefers-reduced-motion
is set to something other than reduce
. Returns a Boolean
.
// '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 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
.
-
*
duration
(Number
): Time in milliseconds after which script execution will continue. -
resolveValue
(Any validPromise.resolve()
value): Value which the promise will be resolved with. -
abortSignal
(AbortSignal
):AbortController.signal
which the timeout can be cancelled with.
// 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);
Function parameters are now type checked. The following breaking changes were made:
-
Removed
createEls()
- Write this code yourself - it was just a
for
loop.
- Write this code yourself - it was just a
-
Removed
getRandomIntUnder()
- Use
getPseudoRandomIntBetween(0, x)
instead.
- Use
-
getCssUnit()
: Removed support fory
unit - will now returnnull
. -
wait()
: Now takes in anabortSignal
instead of anabortController
.
Function parameters are now type checked. The following breaking changes were made:
-
Removed
createEls()
- Write this code yourself - it was just a
for
loop.
- Write this code yourself - it was just a
-
Removed
getRandomIntUnder()
- Use
getPseudoRandomIntBetween(0, x)
instead.
- Use
-
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.
MIT © 2024 Viktor Chin-Kon-Sung