- CompatResolver
Framework for resolving functions with different names & availabilities across browsers.
- Point2D
Represents a point in 2D space.
- ScrollbarStatus
Describes the scrollability of an element on its axes.
- MediaBreakpoint
A breakpoint following a mobile-first philosophy.
- Emitter
Browser-friendly Emitter class.
- listenerOptions :
EventListenerOptionsCompat
- compatCancelAnimationFrame :
CompatResolver.<CompatCancelAnimationFrame>
- compatNow :
CompatResolver.<CompatNow>
- compatRequestAnimationFrame :
CompatResolver.<CompatRequestAnimationFrame>
- setUpInterfaceDetection(win, doc)
Adds
hover
andtouch
classes once to the documentElement when mouse/stylus & touch events detected.- setUpTabFocus() ⇒
function
Adds event listeners to window, setting
tab-focus
andtab-focus-within
classes on focused elements.- allowValues(allowedValues, subject) ⇒
Array
Filter unknown values out of a given array.
- arraysAreEqual(a, b, strict) ⇒
boolean
Check whether 2 arrays are equal.
- assertArray(value, [minLength], [fill]) ⇒
Array
Make sure that a value is an array.
- copyArray(arr) ⇒
Array
Get a copy of an array.
- denyValues(deniedValues, subject) ⇒
Array
Filter known values out of a given array.
- flatten(arr, [depth]) ⇒
Array
Flatten an array up to a set number of levels.
- getIndexedValue(arr, idx, key) ⇒
Object
|undefined
Get indexed entry of an array by the indexed property.
- indexArray(arr, uniqueKey) ⇒
Index an array of objects to quickly access its entries by a unique key.
- rotateArray(arr, [rotation]) ⇒
Array
Get a rotated copy of an array.
- shuffleArray(arr) ⇒
Array
Shuffle the elements of an array.
- uniq(arr) ⇒
Array
Strip array to unique values.
- getHTML(url, headers, body) ⇒
Promise.<RequestUtilResponse>
Get HTML via AJAX.
- getJSON(url, headers, body) ⇒
Promise.<RequestUtilResponse>
Get JSON via AJAX.
- makeVerbosePromise(promise) ⇒
VerbosePromise.<T>
Add status props to a Promise.
- request(method, type, url, headers, body) ⇒
Promise.<RequestUtilResponse>
Make simple AJAX requests
- unwrapPromises(...promises) ⇒
Array.<*>
Unwrap promises once resolved.
- convertPxToRem(px, useRealValue) ⇒
number
Convert a pixel value to the equivalent rem value.
- convertRemToPx(rem, useRealValue) ⇒
number
Convert a rem value to a pixel value
- ensureCSSUnits(value, units, fallback) ⇒
string
- getEm(el) ⇒
number
Get the em (font size) of an element.
- getRem() ⇒
number
Get the em (font size) of an element.
- parseCSSColor(color) ⇒
ParsedCSSColor
Parse a CSS color string into red, green, blue, and alpha components.
- parseCSSTime(cssTimeStr) ⇒
number
Parse a CSS time string into ms.
- byNumericValue(a, b) ⇒
number
Compare 2 values numerically.
- compareProps(prop, subjectA, subjectB) ⇒
number
Compare a property of 2 objects.
- polyfill(scope, methodName, resolver) ⇒
void
- calculateScrollbarWidth() ⇒
number
Calculate the width of the native scrollbars.
detectBrowser() ⇒string
Try to determine the client browser.
isDev() ⇒boolean
Try to identify development environment from location host TLD.
- setUpMediaQueries(breakpoints) ⇒
Object
Get an object of preset matchMedia media queries.
- dispatchCustomEvent(eventType, [target], [options]) ⇒
boolean
Dispatch a custom event.
- getEventPath(event) ⇒
Array.<EventTarget>
Get the bubble path of an event.
- onDocReady(fn)
Vanilla JS replacement for jQuery document ready.
- fallbackUntil(validate, ...values) ⇒
*
Return the first argument that satisfies a validation callback.
- fallbackUntilAsync(validate, ...values) ⇒
Promise.<?*>
Resolve to the first argument that satisfies an async validation callback.
- batch(...fns) ⇒
function
Create one function that runs multiple functions on the same arguments.
- batchApply(fn, argsArray, thisArg) ⇒
Array
Call one function multiple times with an array of values/value arrays to pass to each call.
- compose(...fns) ⇒
function
Compose multiple functions into one function.
- debounce(fn, wait, [leading]) ⇒
Debounce a function by setting a minimum elapsed time between invocations.
- makeValidator(fns, strictMode) ⇒
function
Turn a series of functions into a testing function.
- partial(fn, ...partials) ⇒
function
Partially apply arguments to a function without setting
this
.- partialRight(fn, ...partials) ⇒
function
Partially apply arguments to a function from right-to-left without setting
this
.- sequence(...fns) ⇒
function
Sequence multiple functions into one function.
- throttle(fn, wait) ⇒
function
Throttle a high-frequecy and/or resource intensive function.
- capMinMax(min, max, value) ⇒
number
Cap a value to between minimum and maximum values.
- toDecimal(digitsAfterDecimal, value) ⇒
number
Cast a single value to decimal of specified precision.
- toInteger(value) ⇒
number
Cast a single value to integer.
- toNumber(value, [fallback]) ⇒
number
Cast value to number.
- preloadImage(sources) ⇒
Promise.<boolean>
Preload an image for the browser, resolves to success/error state.
- testImageURL(url) ⇒
Promise.<boolean>
Test if an image URL is valid.
- applyEventListeners(eventTarget, listeners)
Add listeners for multiple events to one DOM element.
- createElem(tagName, props, ...children) ⇒
HTMLElement
Create an HTMLElement.
- getPageOffset(el) ⇒
Point2D
Get the full page offset for an element.
- getParents(node, includeSelf) ⇒
Array.<Node>
Get all parent elements for an element.
- getScrollParent(node) ⇒
Node
Get the scroll parent of an element.
- isInDom(targetNode) ⇒
boolean
Determine whether a DOM object is in the current DOM.
- isInViewport(el) ⇒
boolean
Check if any part of an element is within the viewport.
- isSameOrChildNode(potentialParentNode, targetNode) ⇒
boolean
Determine whether a DOM object is the same or parent of another DOM object.
- isScrollable(node) ⇒
ScrollbarStatus
Check whether a node has currently scrollable overflow.
- scrollIntoView(el, [offset])
Scroll the window to the vertical position of an element.
- setPrefixedStyle(elem, styleName, styleValue, prefixValues)
Apply a style to a DOM element with vendor prefixes.
- allowProps(allowedProps, subject) ⇒
Object
Remove unknown properties from a given object (DESTRUCTIVE).
- denyProps(deniedProps, subject) ⇒
Object
Remove known properties from a given object (DESTRUCTIVE).
- diff(source, compareTo, [depth]) ⇒
Object
Get the difference between one object and another recursively.
- extend(target, extensions, [depth]) ⇒
Object
Copy properties from one object to another recursively.
- hasAllProps(proplist, subject) ⇒
boolean
Verify that an object has all of the supplied properties.
- hasAnyProps(proplist, subject) ⇒
boolean
Verify that an object has at least one of the supplied properties.
- matchProps(prop, subjectA, subjectB) ⇒
boolean
Check a property of 2 objects to see if the values match.
- snapshot(obj) ⇒
Object
Snapshot the properties of an object.
- camelCase(str) ⇒
string
Camel case a string.
- copyToClipboard(str)
Copy a string to the users clipboard.
- formatSeconds(seconds, [forceHours]) ⇒
string
Get a formatted string representation of time in seconds.
- getUniqueId() ⇒
string
Get a unique id string.
- kebabCase(str) ⇒
string
Kebab case a string.
- leftPad(str, length, [char]) ⇒
string
Add left padding to a string.
- lowerCaseFirst(str) ⇒
string
Lower case the first letter of a string.
- lowerCaseWords(str) ⇒
string
Lower case the first letter of each word in a string.
- pascalCase(str) ⇒
string
Pascal case a string.
- pathJoin(...segments) ⇒
string
Join path segments.
- percentage(fraction) ⇒
string
Turn a fractional number into a percentage string.
- sentenceCase(str) ⇒
string
Sentence case a string.
- snakeCase(str) ⇒
string
Snake case a string.
- stripCase(str) ⇒
string
Strip the case of a string.
- stripEnd(match, str) ⇒
string
Strip substrings from the end of a string.
- stripStart(match, str) ⇒
string
Strip substrings from the start of a string.
- titleCase(str) ⇒
string
Title case a string.
- titleSnakeCase(str) ⇒
string
Title snake case a string (aka PHP class case).
- upperCaseFirst(str) ⇒
string
Upper case the first letter of a string.
- upperCaseWords(str) ⇒
string
Upper case the first letter of each word in a string.
- upperSnakeCase(str) ⇒
string
Upper snake case a string (aka constant case).
- areSameType(value, ...values) ⇒
boolean
Check whether any number of values are of the same type.
- isArray(value) ⇒
boolean
Check if value is an Array
- isCallable(fn) ⇒
boolean
Determine whether a value is a callable function
- isDomObject(value) ⇒
boolean
Check if a value is a DOM object, a.k.a. Node
- isInt(value) ⇒
boolean
Reliable method of determining if int
- isNumber(value) ⇒
boolean
Check if value is a number
- isNumeric(value) ⇒
boolean
Check if value is numeric
- isObject(value) ⇒
boolean
Determine whether a value is an Object
- isPojo(value) ⇒
boolean
Determine whether a value is a Plain Old Javascript Object (POJO)
- isString(value) ⇒
boolean
Check if a value is a string
- parseBool(value) ⇒
boolean
Parse for boolean.
Rect properties
Time constants.
Properties
Name | Type | Description |
---|---|---|
SECOND | number |
1 second in milliseconds. |
MINUTE | number |
1 minute in milliseconds. |
HOUR | number |
1 hour in milliseconds. |
DAY | number |
1 day in milliseconds. |
WEEK | number |
1 week in milliseconds. |
MONTH | number |
1 month in milliseconds. |
YEAR | number |
1 year in milliseconds. |
SECONDS_PER_HOUR | number |
|
SECONDS_PER_DAY | number |
Common frequency periods (time from peak to peak).
Properties
Name | Type | Description |
---|---|---|
HZ_15 | number |
Period for frequency of 15Hz. Visual updates throttled to 15Hz will feel slow. |
HZ_30 | number |
Period for frequency of 30Hz. Visual updates throttled to 30Hz may be noticed by users, but should be acceptable. |
HZ_60 | number |
Period for frequency of 60Hz. Users shouldn't be able to detect visual updates throttled to 60Hz. |
FPS_15 | number |
Alias of FREQ.HZ_15. |
FPS_30 | number |
Alias of FREQ.HZ_30. |
FPS_60 | number |
Alias of FREQ.HZ_60. |
Properties
Name | Type | Description |
---|---|---|
red | number |
Red value of parsed color. |
green | number |
Green value of parsed color. |
blue | number |
Blue value of parsed color. |
alpha | number |
Alpha value of parsed color. |
value | string |
The CSS color string for the parsed color. |
listenerOptions : EventListenerOptionsCompat
🔒 Read only
Adds hover
and touch
classes once to the documentElement when mouse/stylus & touch events detected.
Param | Type | Description |
---|---|---|
win | Window |
Window to listen for events. |
doc | Document |
Document to recieve classes. |
Adds event listeners to window, setting tab-focus
and tab-focus-within
classes on focused elements.
Returns: function
- Teardown function to remove listeners.
Properties
Name | Type | Description |
---|---|---|
normal | boolean | EventListenerOptions |
Listener will behave as default. |
passive | boolean | EventListenerOptions |
Listener will be passive if supported. |
capture | boolean | EventListenerOptions |
Listener will dispatched as the event bubbles down. |
passiveCapture | boolean | EventListenerOptions |
Listener will capture and be passive if supported. |
Filter unknown values out of a given array.
Returns: Array
- Filtered array.
Param | Type | Description |
---|---|---|
allowedValues | Array |
Array of allowed values/objects. |
subject | Array |
Array to filter. |
Example
allow([2,4], [1,1,2,3,4,4,4,5,9]); // -> [2,4,4,4]
Check whether 2 arrays are equal.
Param | Type | Description |
---|---|---|
a | Array |
First array. |
b | Array |
Second array. |
strict | boolean |
Whether to evaluate each item, or just compare JSON strings. |
Make sure that a value is an array.
Param | Type | Default | Description |
---|---|---|---|
value | * |
Value to check. | |
[minLength] | number |
0 |
Minimum length for returned array. |
[fill] | * |
Value to insert when filling. If function, will be called with the current index, inserting the returned value. |
Get a copy of an array.
Get a copy of an array. Just aliases Array.prototype.slice to better communicate intent.
Param | Type |
---|---|
arr | Array |
Example
let a = [1,2,3];
let b = copyArray(a);
a == b; // -> false
arraysAreEqual(a,b); // -> true
Filter known values out of a given array.
Returns: Array
- Filtered array.
Param | Type | Description |
---|---|---|
deniedValues | Array |
Array of denied values/objects. |
subject | Array |
Array to filter. |
Example
var nums = [1,1,2,3,4,4,4,5,9];
nums = denyValues([2,4], nums); // -> [1,1,3,5,9]
Flatten an array up to a set number of levels.
Param | Type | Default | Description |
---|---|---|---|
arr | Array |
Array to flatten. | |
[depth] | number |
1 |
Max depth of flattening. |
Example
flatten([1,2,[3,4],5]); // -> [1,2,3,4,5]
flatten([1,2,[3,[4]],5], 1); // -> [1,2,3,[4],5]
flatten([1,2,[3,[[[[4]]]]],5], Infinity); // -> [1,2,3,4,5]
Get indexed entry of an array by the indexed property.
Get indexed entry of an array by the indexed property.
- Assumes
idx
is up to date witharr
.
Param | Type | Description |
---|---|---|
arr | Array.<Object> |
Array of indexed objects |
idx | Map.<K, number> |
Array index |
key | K |
Example
const fruitsInKitchen = [
{ name: "banana" },
{ name: "kiwi" },
];
const [fruitsByName] = indexArray(fruitsInKitchen, "name");
getIndexedValue(fruitsInKitchen, fruitsByName, "kiwi"); // => { name: "kiwi" }
Index an array of objects to quickly access its entries by a unique key.
Returns: Index object and prefilled accessor function
Param | Type | Description |
---|---|---|
arr | Array.<T> |
|
uniqueKey | string |
Key for a property that will be unique for each member of the array. |
Example
const fruitsInKitchen = [
{ name: "banana" },
{ name: "kiwi" },
{ name: "mango" },
];
const [fruitsByName, getFruitsByName] = indexArray(fruitsInKitchen, "name");
fruitsByName.get("kiwi"); // => { name: "kiwi" }
getFruitsByName("mango"); // => { name: "mango" }
getFruitsByName("banana") === fruitsInKitchen[0]; // => true
Get a rotated copy of an array.
Param | Type | Default | Description |
---|---|---|---|
arr | Array |
||
[rotation] | number |
1 |
Index to rotate to / Number of places to rotate by. |
Example
let arr = [1,2,3,4];
rotateArray(arr); // -> [2,3,4,1]
rotateArray(arr, 3); // -> [4,1,2,3]
rotateArray(arr, -2); // -> [3,4,1,2]
Shuffle the elements of an array.
Shuffle the elements of an array. Uses the Durstenfeld shuffle.
- Shuffles in place, use
arr.slice(0)
to get a copy of the array to shuffle.
Param | Type |
---|---|
arr | Array |
Example
const numbers = [1,2,3,4,5];
shuffleArray(numbers); // -> [1,4,2,5,3]
Strip array to unique values.
Returns: Array
- Array of unique values.
Param | Type | Description |
---|---|---|
arr | Array |
An array. |
Example
uniq([1, 1, 3, 'cat', 1, 'cat']); // -> [1, 3, 'cat']
Get HTML via AJAX.
Param | Type | Description |
---|---|---|
url | string |
The URL to request. |
headers | Object.<string, *> |
Object of key:value headers. |
body | string , Document , Blob , BufferSource , FormData , URLSearchParams , ReadableStream |
Request body. |
Get JSON via AJAX.
Param | Type | Description |
---|---|---|
url | string |
The URL to request. |
headers | Object.<string, *> |
Object of key:value headers. |
body | string , Document , Blob , BufferSource , FormData , URLSearchParams , ReadableStream |
Request body. |
Add status props to a Promise.
This function allow you to modify a JS Promise by adding some status properties.
But modified according to the specs of promises : https://promisesaplus.com/
Param | Type |
---|---|
promise | Promise.<T> |
Make simple AJAX requests
Link: XMLHttpRequest.responseType
Param | Type | Description |
---|---|---|
method | string |
Request method, case insensitive. |
type | XMLHttpRequestResponseType |
Response type. |
url | string |
The URL to request. |
headers | Object.<string, *> |
Object of key:value headers. |
body | string , Document , Blob , BufferSource , FormData , URLSearchParams , ReadableStream |
Request body. |
Unwrap promises once resolved.
Unwrap promises once resolved.
! Make sure all individual promises have potential rejections handled, as each will be await
-ed without error handling.
Param | Type |
---|---|
...promises | Promise.<*> |
Properties
Name | Type | Description |
---|---|---|
isFulfilled | boolean |
Promise has been resolved. |
isRejected | boolean |
Promise has been rejected. |
isPending | boolean |
Promise is not yet settled. |
Convert a pixel value to the equivalent rem value.
Param | Type |
---|---|
px | number |
useRealValue | boolean |
Convert a rem value to a pixel value
Param | Type |
---|---|
rem | number |
useRealValue | boolean |
Param | Type | Description |
---|---|---|
value | string |
CSS value as string. |
units | Array.<string> |
Units to check for at the end of the value string. |
fallback | string |
Unit to add if no matching unit detected. |
Get the em (font size) of an element.
Param | Type | Description |
---|---|---|
el | Element |
Element to get em value from. |
Get the em (font size) of an element.
parseCSSColor(color) ⇒ ParsedCSSColor
Parse a CSS color string into red, green, blue, and alpha components.
Parse a CSS color string into red, green, blue, and alpha components.
- Passing an invalid color will return the components for transparent black, with an empty string as the
value
property.
Param | Type | Description |
---|---|---|
color | string |
CSS color value, case-insensitive. |
Parse a CSS time string into ms.
Param | Type | Description |
---|---|---|
cssTimeStr | string |
Valid CSS time in seconds or milliseconds |
Compare 2 values numerically.
Compare 2 values numerically.
- Non-numeric values are considered "greater".
Param | Type |
---|---|
a | * |
b | * |
Compare a property of 2 objects.
Returns: number
- 0 if equal, 1 if more, -1 if less.
Param | Type | Description |
---|---|---|
prop | string |
The property by which to evaluate. |
subjectA | Object |
The object to evaluate. |
subjectB | Object |
Another object to evaluate. |
Framework for resolving functions with different names & availabilities across browsers.
Properties
Name | Type |
---|---|
candidates | Array.<CompatResolverCandidate> |
scope | Object |
Param | Type |
---|---|
candidates | Array.<CompatResolverCandidate> |
[scope] | Object |
Add additional candidates to an existing CompatResolver instance.
Param | Type | Default | Description |
---|---|---|---|
fn | string , function |
Either the member name of a candidate function within the scope , or a function that returns a candidate function. |
|
[scope] | Object |
An optional scope object to check for the candidate function, defaults to scope of the CompatResolver instance. | |
[prepend] | boolean |
false |
Whether to prepend the candidate to the list, default false . |
Resolve the candidates to a usable implementation.
Returns: T
- Resolved compat function.
Param | Type | Default | Description |
---|---|---|---|
[forceEvaluation] | boolean |
false |
Force (re)evaluation of candidates. |
compatCancelAnimationFrame : CompatResolver.<CompatCancelAnimationFrame>
compatNow : CompatResolver.<CompatNow>
compatRequestAnimationFrame : CompatResolver.<CompatRequestAnimationFrame>
Param | Type | Description |
---|---|---|
scope | Object |
Method/function scope. |
methodName | string |
Method name. |
resolver | CompatResolver , Array.<CompatResolverCandidate> |
Param | Type |
---|---|
handle | number |
A cross-browser function for calculating timings.
Defaults to performance.now
, falling back to Date.now
.
Param | Type |
---|---|
callback | FrameRequestCallback |
Properties
Name | Type | Description |
---|---|---|
fn | string | function |
Either the member name of a candidate function within the scope , or a function that returns a candidate function. |
scope | Object |
An optional scope object to check for the candidate function, defaults to the global object (window in browsers, global for node) |
Represents a point in 2D space.
Throws:
TypeError
Param | Type |
---|---|
coordinates | Object |
coordinates.x | number |
coordinates.y | number |
The X coordinate.
The Y coordinate.
Describes the scrollability of an element on its axes.
- ScrollbarStatus
- .ScrollbarStatus
- .any :
boolean
- .both :
boolean
- .x :
boolean
- .y :
boolean
Param | Type | Description |
---|---|---|
status | Object |
|
status.any | boolean |
Element can scroll vertically or horizontally. |
status.both | boolean |
Element can scroll vertically and horizontally. |
status.x | boolean |
Element can scroll horizontally. |
status.y | boolean |
Element can scroll vertically. |
Element can scroll vertically or horizontally.
Element can scroll vertically and horizontally.
Element can scroll horizontally.
Element can scroll vertically.
A breakpoint following a mobile-first philosophy.
Breakpoint identifier.
Minumum viewport width.
Breakpoint unit.
The breakpoint media query.
mediaBreakpoint.next : MediaBreakpoint
A link to the "next" breakpoint, assuming in order of increasing viewport widths.
Calculate the width of the native scrollbars.
Returns: number
- Width of native browser scrollbars in px.
Try to determine the client browser.
Returns: string
- Detected browser.
Try to identify development environment from location host TLD.
Returns: boolean
- Whether it was able to detect current environment as 'dev'.
Get an object of preset matchMedia media queries.
Param | Type | Description |
---|---|---|
breakpoints | Array.<MediaBreakpoint> |
Array of Breakpoint objects. |
Dispatch a custom event.
Dispatch a custom event of type eventType
on target
, defaults to document.
- Returns true on success, false on failure.
Param | Type | Default | Description |
---|---|---|---|
eventType | string |
The event type. | |
[target] | EventTarget |
document |
The element to dispatch the event. |
[options] | Object |
Event options. | |
[options.bubbles] | boolean |
false |
Whether the event will bubble. |
[options.cancelable] | boolean |
false |
Whether the event is cancelable. |
[options.composed] | boolean |
false |
Whether the event is composed. |
[options.detail] | * |
Any data to pass to the event handler. |
Get the bubble path of an event.
Param | Type |
---|---|
event | Event |
Vanilla JS replacement for jQuery document ready.
Param | Type | Description |
---|---|---|
fn | function |
Callback for on document ready. |
Return the first argument that satisfies a validation callback.
Return the first argument that satisfies a validation callback, or the last value provided.
- Returns
undefined
if no values are passed.
Throws:
TypeError
If the callback isn't callable.
Param | Type | Description |
---|---|---|
validate | function |
Validation callback. |
...values | * |
Variable number of candidate values. |
Resolve to the first argument that satisfies an async validation callback.
Resolve to the first argument that satisfies an async validation callback, or the last value provided.
- Resolves to
undefined
if no values are passed.
Throws:
TypeError
If the callback isn't callable.
See: fallbackUntil
Param | Type | Description |
---|---|---|
validate | function |
Validation callback. |
...values | * |
Variable number of candidate values. |
Create one function that runs multiple functions on the same arguments.
Create one function that runs multiple functions on the same arguments.
- Returned function returns array of results in order of original args.
Param | Type | Description |
---|---|---|
...fns | function |
Callable functions. |
Example
var abc = batch(a, b, c);
abc(x); // -> [a(x), b(x), c(x)];
Call one function multiple times with an array of values/value arrays to pass to each call.
Returns: Array
- Array of returns from each call of fn.
Param | Type | Description |
---|---|---|
fn | function |
Function to call. |
argsArray | Array.<Array> |
Array of arguments for function. |
thisArg | * |
Value to set as this for the function. |
Example
batchApply(Math.pow, [[2, 2], [10, 3]]) // -> [4, 1000]
Compose multiple functions into one function.
Param | Type | Description |
---|---|---|
...fns | function |
Callable functions. |
Example
var abc = compose(a, b, c);
abc(x); // -> a(b(c(x)))
Debounce a function by setting a minimum elapsed time between invocations.
Debounce a function by setting a minimum elapsed time between invocations.
- When called before the elapsed time, will return the last result
- Debounced function has 2 methods:
- flush(), which cancels the timer and immediately returns the result of the invoked function, and
- cancel(), which just cancels the timer.
Returns: Debounced function.
Param | Type | Default | Description |
---|---|---|---|
fn | function |
Function to debounce. | |
wait | number |
Minimum elapsed time between invoking fn . |
|
[leading] | boolean |
false |
Optional. Whether to invoke the function the first time is is called before waiting. Default false. |
Turn a series of functions into a testing function.
Param | Type | Description |
---|---|---|
fns | Array.<function()> |
Array of functions to test arguments. |
strictMode | * , boolean |
Whether tested arguments have to pass all. tests (true/false -> AND/OR) |
Partially apply arguments to a function without setting
this
.
Partially apply arguments to a function without setting this
.
- Use
_
as a placeholder value, final arguments will fill those positions from left-to-right, appending any remaining arguments.
Param | Type | Description |
---|---|---|
fn | function |
Function to partially apply. |
...partials | * |
Arguments to partially apply to fn . |
Properties
Name | Type | Description |
---|---|---|
placeholder | string |
"_", can be used as placeholder instead of the string literal. |
Example
let forceGreaterThanZero = partial(Math.max, 0);
forceGreaterThanZero(myNum) // ~= Math.max(0, myNum)
Partially apply arguments to a function from right-to-left without setting
this
.
Partially apply arguments to a function from right-to-left without setting this
.
- Use
_
as a placeholder value, final arguments will replace those positions from right-to-left, prepending any remaining arguments.
Param | Type | Description |
---|---|---|
fn | function |
Function to partially apply. |
...partials | * |
Arguments to partially apply to fn . |
Properties
Name | Type | Description |
---|---|---|
placeholder | string |
"_", can be used as placeholder instead of the string literal. |
Example
let divide = (a, b) => a / b;
let divideBy2 = partialRight(divide, 2);
divideBy2(myNum) // ~= divide(myNum, 2)
Example
let addThenMultiply = (a, b, c) => (a + b) * c;
let add2ThenMultiply = partialRight(divide, 2, partialRight.placeholder);
add2ThenMultiply(1, 3) // === addThenMultiply(1, 2, 3) === 9
Sequence multiple functions into one function.
Param | Type | Description |
---|---|---|
...fns | function |
Callable functions. |
Example
var abc = sequence(a, b, c);
abc(x); // -> c(b(a(x)))
Throttle a high-frequecy and/or resource intensive function.
Returns: function
- Throttled function.
Param | Type | Description |
---|---|---|
fn | function |
Function to throttle. |
wait | number |
Minimum number of millseconds to wait between calls. |
Cap a value to between minimum and maximum values.
Param | Type | Description |
---|---|---|
min | number |
Minimum acceptable value. |
max | number |
Maximum acceptable value. |
value | number |
Value to cap. |
Cast a single value to decimal of specified precision.
Cast a single value to decimal of specified precision.
- Returns 0 if an array with length < 1 or string with non-numeral characters.
Param | Type | Description |
---|---|---|
digitsAfterDecimal | number |
Integer number of significant digits after decimal. |
value | * |
Cast a single value to integer.
Cast a single value to integer.
- returns 0 if an array with length < 1 or string with non-numeral characters
Param | Type |
---|---|
value | * |
Cast value to number.
Param | Type | Default | Description |
---|---|---|---|
value | * |
Value to attept converting to number. | |
[fallback] | number |
0 |
Number to return if value cannot be successfully converted to number. Default 0. |
Preload an image for the browser, resolves to success/error state.
Param | Type | Description |
---|---|---|
sources | Object |
|
sources.srcset | string |
A valid srcset attribute string for an image element. |
sources.sizes | string |
A valid sizes attribute string for an image element. |
sources.src | string |
A valid src attribute string for an image element. |
Test if an image URL is valid.
Test if an image is "good". Fails if:
url
is empty or null, ORurl
is the same as the URL of the page the user is currently on, OR- the image is corrupted in some way that prevents it from being loaded, OR
- the image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, OR
- the image is in a format not supported by the user agent.
Param | Type | Description |
---|---|---|
url | string |
An image src URL. |
Add listeners for multiple events to one DOM element.
Param | Type | Description |
---|---|---|
eventTarget | Element |
eventTarget DOM element to add event listeners. |
listeners | Array.<Array> |
listeners Array of addEventListener argument sets. |
Create an HTMLElement.
Create an HTMLElement.
- returns null for invalid tagName
See: ParentNode.append
Param | Type | Description |
---|---|---|
tagName | string |
Element tag name. |
props | Object |
Element properties. Unrecognized props are kebab-cased and set as attributes. |
...children | Node , string |
Element child nodes. |
getPageOffset(el) ⇒ Point2D
Get the full page offset for an element.
Param | Type | Description |
---|---|---|
el | Element |
Element of which to find offset. |
Get all parent elements for an element.
Param | Type | Description |
---|---|---|
node | Node |
Node to get parents of. |
includeSelf | boolean |
Whether to include starting node. |
Get the scroll parent of an element.
Param | Type |
---|---|
node | Node |
Determine whether a DOM object is in the current DOM.
Param | Type | Description |
---|---|---|
targetNode | Node |
DOM object to check. |
Check if any part of an element is within the viewport.
Param | Type |
---|---|
el | HTMLElement |
Determine whether a DOM object is the same or parent of another DOM object.
Param | Type | Description |
---|---|---|
potentialParentNode | Node |
Parent DOM object to check lineage. |
targetNode | Node |
Child DOM object. |
isScrollable(node) ⇒ ScrollbarStatus
Check whether a node has currently scrollable overflow.
Param | Type |
---|---|
node | Node |
Scroll the window to the vertical position of an element.
Param | Type | Default | Description |
---|---|---|---|
el | Element , string |
Element or selector to scroll into view. | |
[offset] | number |
0 |
Cast to int, vertical pixel offset from element. |
Apply a style to a DOM element with vendor prefixes.
Param | Type | Description |
---|---|---|
elem | Element , jQuery |
Element to apply styles to. |
styleName | string |
The name of a CSS style. |
styleValue | string |
String-ified CSS style value. |
prefixValues | boolean |
Whether to prefix the values as well. |
Remove unknown properties from a given object (DESTRUCTIVE).
Param | Type | Description |
---|---|---|
allowedProps | Array.<string> |
Array of allowed property keys. |
subject | Object |
Object to be processed. |
Example
var o = {foo: 'bar', hello: 'world', sieze: 'today'};
allowProps(['foo', 'hello'], o); // o == {foo: 'bar', hello: 'world'}
Remove known properties from a given object (DESTRUCTIVE).
Param | Type | Description |
---|---|---|
deniedProps | Array.<string> |
Array of denied property keys. |
subject | Object |
Object to be processed. |
Example
var o = {foo: 'bar', hello: 'world', sieze: 'today'};
denyProps(['foo', 'hello'], o); // o == {sieze: 'today'}
Get the difference between one object and another recursively.
Param | Type | Default | Description |
---|---|---|---|
source | Object |
Object to get differences from. | |
compareTo | Object |
Object to compare values to. | |
[depth] | number |
-1 |
Max depth for recursion. Negative value -> no limit. |
Copy properties from one object to another recursively.
Param | Type | Default | Description |
---|---|---|---|
target | Object |
Target object. | |
extensions | Object |
Object with properties to copy. | |
[depth] | number |
-1 |
Max depth for recursion. Negative value -> no limit. |
Verify that an object has all of the supplied properties.
Param | Type | Description |
---|---|---|
proplist | Array.<string> |
List of property keys to check. |
subject | Object |
Object to check. |
Verify that an object has at least one of the supplied properties.
Param | Type | Description |
---|---|---|
proplist | Array.<string> |
List of property keys to check. |
subject | Object |
Object to check. |
Check a property of 2 objects to see if the values match.
Param | Type | Description |
---|---|---|
prop | string |
The property by which to evaluate. |
subjectA | Object |
An object to evaluate. |
subjectB | Object |
Another object to evaluate. |
Snapshot the properties of an object.
Param | Type |
---|---|
obj | Object |
Camel case a string.
Param | Type |
---|---|
str | string |
Example
camelCase("This is my sample"); // => "thisIsMySample"
Copy a string to the users clipboard.
Param | Type | Description |
---|---|---|
str | string |
String to copy to clipboard. |
Get a formatted string representation of time in seconds.
Returns: string
- Formatted time string.
Param | Type | Default | Description |
---|---|---|---|
seconds | number |
Time in seconds. | |
[forceHours] | boolean |
false |
Whether to include hours in the output when time is less than 1 hour. |
Example
formatSeconds(27); // => "0:27"
formatSeconds(3822); // => "1:03:42"
Get a unique id string.
Kebab case a string.
Param | Type |
---|---|
str | string |
Example
kebabCase("This is my sample"); // => "this-is-my-sample"
Add left padding to a string.
Add left padding to a string. Only validation is converting non-zero falsey
values for char
to a single space.
Param | Type | Description |
---|---|---|
str | string |
String to pad, value is cast to string. |
length | number |
Desired minimum string length. |
[char] | string |
Padding character, default single space. |
Example
leftPad("hello", 8); // => " hello"
leftPad(24, 4, 0); // => "0024"
Lower case the first letter of a string.
Param | Type |
---|---|
str | string |
Lower case the first letter of each word in a string.
Param | Type |
---|---|
str | string |
Pascal case a string.
Param | Type |
---|---|
str | string |
Example
pascalCase("this is my sample"); // => "ThisIsMySample"
Join path segments.
Param | Type | Description |
---|---|---|
...segments | string , Array.<string> |
Path segments. Arrays and nested arrays will be flattened. |
Turn a fractional number into a percentage string.
Param | Type |
---|---|
fraction | number |
Example
percentage(0.725); // "72.5%"
Sentence case a string.
Param | Type |
---|---|
str | string |
Example
sentenceCase("this is my sample"); // => "This is my sample"
Snake case a string.
Param | Type |
---|---|
str | string |
Example
snakeCase("This is my sample"); // => "this_is_my_sample"
Strip the case of a string.
Strip the case of a string: no capitals, words separated by a single space.
Param | Type |
---|---|
str | string |
Strip substrings from the end of a string.
Param | Type | Description |
---|---|---|
match | string , RegExp |
Substring or regex to match. |
str | string |
Strip substrings from the start of a string.
Param | Type | Description |
---|---|---|
match | string , RegExp |
Substring or regex to match. |
str | string |
Title case a string.
Param | Type |
---|---|
str | string |
Example
titleCase("this is my sample"); // => "This Is My Sample"
Title snake case a string (aka PHP class case).
Param | Type |
---|---|
str | string |
Example
upperSnakeCase("This is my sample"); // => "This_Is_My_Sample"
Upper case the first letter of a string.
Param | Type |
---|---|
str | string |
Upper case the first letter of each word in a string.
Param | Type |
---|---|
str | string |
Upper snake case a string (aka constant case).
Param | Type |
---|---|
str | string |
Example
upperSnakeCase("This is my sample"); // => "THIS_IS_MY_SAMPLE"
Check whether any number of values are of the same type.
Check whether any number of values are of the same type.
- checks typeof and object/function constructors.
Param | Type | Description |
---|---|---|
value | * |
All other values are tested agains this value. |
...values | * |
Check if value is an Array
Param | Type |
---|---|
value | * |
Determine whether a value is a callable function
Param | Type |
---|---|
fn | * |
Check if a value is a DOM object, a.k.a. Node
Param | Type |
---|---|
value | * |
Reliable method of determining if int
Param | Type |
---|---|
value | * |
Check if value is a number
Param | Type |
---|---|
value | * |
Check if value is numeric
Param | Type |
---|---|
value | * |
Determine whether a value is an Object
Param | Type |
---|---|
value | * |
Determine whether a value is a Plain Old Javascript Object (POJO)
Param | Type |
---|---|
value | * |
Check if a value is a string
Param | Type |
---|---|
value | * |
Parse for boolean.
Parse for boolean. Checks for numeric strings, and "true", else casting to boolean.
Param | Type |
---|---|
value | string |