A grouped list of functions based on their origin/usage:
- closest
- escapeHtml
- htmlToElement
- preventDefault
- preventingDefault
- trapFocus
- triggerEvent
- unescapeHtml
All functions with usage examples:
Generic function for traversing a DOM, returning the first element matching the predicate function.
const findParentFoo = closest(el => el.hasAttribute(`data-foo`));
Composer of functions. Will accept 0 or more functions. Execution order is right to left, as is traditional.
const join = xs => xs.join(' ');
const split = xs => xs.split(' ');
const heads = xs => xs.map(x => x[0]);
const initials = compose(join, heads, split);
initials('Miles Davis'); //=> 'M D';
Curry a function. Will keep returning functions until the originally required arity has been reached.
const multiply = (a, b) => a * b;
const curriedMultiply = curry(multiply);
const double = curriedMultiply(2);
double(4); //=> 8
Creates a debounced function that delays invokation of the function until a specified time has elapsed since the last time the debounced function was invoked.
Returns a promise that resolves to the value returned by the debounced function.
const resizeHandler = e => { /* ... */ }; // invoked 300ms after last `resize`
window.addEventListener('resize', debounce(resizeHandler, 300));
// or
const getWindowDimensions = debounce(() => { /* ... */ }, 300);
const resizeListener = async e => {
const windowDimensions = await getWindowDimensions();
// invoked 300ms after last `resize`
};
window.addEventListener('resize', resizeListener);
Simple deep-copy function for cloning objects.
const original = {
foo: 'foo',
config: {
enabled: true,
},
};
const copy = deepCopy(original);
copy.config.enabled = false; // => will not update `original.config.enabled`
Check if the argument is defined.
let foo;
const bar = [];
defined(foo); //=> false
defined(bar); //=> true
Escapes HTML. Useful for sanitizing user input to prevent XSS attacks.
See also unescapeHtml.
const html = `"><img src=/ onerror="alert('XSS')"></img>`;
escapeHtml(html) //=> "><img src=/ onerror="alert('XSS')"></img>
Grab the head of a collection.
head([2, 4, 8]); //=> 2
head('baz'); //=> 'b'
Convert an HTML string to DOM element.
const button = htmlToElement(`
<button class="foo" aria-hidden="true", aria-controls="bar"></button>
`);
Grab the last item of a collection.
last([2, 4, 8]); //=> 8
last('baz'); //=> 'z'
Curried map implementation.
const double = n => n * 2;
const doubleAll = map(double);
doubleAll([1, 2, 3, 4]); //=> [2, 4, 6, 8]
Store results of function calls and return the cache when input arguments are the same.
const foo = (x, y) => { /* heavy calculation */ };
const memoizedFoo = memoize(foo);
memoizedFoo(1, 2); // calculated
memoizedFoo(1, 2); // from memory
memoizedFoo(1, 2); // from memory
memoizedFoo(3, 4); // calculated
memoizedFoo(1, 2); // from memory
Creates a new function, reversing the outcome of the original given function.
const notAnArray = not(Array.isArray);
notAnArray(42); //=> true
notAnArray([]); //=> false
Return a partial copy of an object omitting the keys specified.
omit(['a', 'c'], { a: 1, b: 2, c: 3, d: 4 }); //=> { b: 2, d: 4 }
Parse JSON in a safe way.
Will output a warning when console
is defined and incorrect JSON is encountered.
parseJson(`{"a":"foo","b":"bar"}`); //=> { a: 'foo', 'b': 'bar' }
parseJson(`{a:"foo",b:"bar"}`); //=> undefined
Return a partial copy of an object containing only the keys specified.
pick(['a', 'c'], { a: 1, b: 2, c: 3, d: 4 }); //=> { a: 1, c: 3 }
Call preventDefault on an event object. Might be combined with tap
to create a chainable utility.
See also preventingDefault.
preventDefault(e);
Function decorator to create event listeners from common functions.
Avoids having to specify e.preventDefault()
in functions, thus allowing the author to use them outside an event listener context.
const submit = () => { /* ... */ };
form.addEventListener('submit', preventingDefault(submit));
Getter of object properties.
prop('a', { a: 1, b: 2 }); //=> 1
Return a reversed array of a collection.
reverse([2, 4, 8]); //=> [8, 4, 2]
reverse('baz'); //=> ['z', 'a', 'b']
Grab a random item from a collection.
sample([{ id: 1 }, { id: 2 }, { id: 3 }]); //=> { id: 3 }
sample(['foo', 'bar', 'baz']); //=> 'bar'
sample('foo bar'); //=> 'o'
Grab the tail (rest) of a collection.
tail(['foo', 'bar', 'baz']); //=> ['bar', 'baz']
tail('foo bar'); //=> ['o', 'o', ' ', 'b', 'a', 'r']
Grab the first n items of a collection.
take(2, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']
take(2, 'foo bar'); //=> ['f', 'o']
Grab the last n items of a collection.
takeLast(2, ['foo', 'bar', 'baz']); //=> ['bar', 'baz']
takeLast(2, 'foo bar'); //=> ['a', 'r']
Function for doing side-effects. The generated function returns whatever argument it receives, and executes the side-effect function in the middle.
Handy for chaining logs.
foo().then(tap(x => console.log(x))).then(x => { /* ... */ });
Throttle functions so they're invoked according to the given threshold. It is both a leading and trailing edge throttle, meaning that it will invoke the function immediately and will postpone calls to the 'next throttle invokation' unless a newer call is made.
Returns a promise that resolves to the value returned by the throttled function.
const scrollHandler = e => { /* ... */ }; // invoked every 300ms during `scroll`
window.addEventListener('scroll', throttle(scrollHandler, 300));
// or
const getBackgroundColor = debounce(() => { /* ... */ }, 300);
const scrollListener = async e => {
const backgroundColor = await getBackgroundColor();
// invoked every 300ms during `scroll`
};
window.addEventListener('scroll', scrollListener);
Trap focus in a specific DOM node. It accepts a second argument to specify the root node, which defaults to document
.
Handy when building accessible modals/dialogs, overlays or navigation.
const focusTrap = trapFocus(modal); // traps focus
focusTrap.release(); // releases focus
focusTrap.retrap(); // retraps focus again (initial nodes only)
Create and trigger a synthetic event (new Event combined with dispatchEvent).
Useful when updating the value of HTML inputs, while maintaining existing addEventListener
callback behaviour. Defaults to a bubbling and cancelable event, but allows optional Event properties object as third argument.
input.addEventListener('input', foo);
input.value = 25;
triggerEvent(input, 'input'); //=> `foo` is called
// with another type of event and `Event` constructor arguments
triggerEvent(input, 'blur', {
composed: false,
});
Unescapes HTML.
See also escapeHtml.
const html = `<button id="button">Click me</button>`;
unescapeHtml(html) //=> <button id="button">Click me</button>
Generate RFC4122 v4 compliant UUID.
Handy for generating dynamic ids for accessible components used multiple times on a page.
uuid() //=> 367a0966-8f48-470c-a15f-b09069ca568e