toosoon-utils
Version:
Utility functions & classes
96 lines (95 loc) • 2.56 kB
JavaScript
/**
* No-op function
*/
export const noop = () => { };
/**
* Promise wrapped setTimeout
*
* @param {number} [delay=0] Time to wait (in milliseconds)
* @returns {Promise}
*/
export function wait(delay = 0) {
return new Promise((resolve) => setTimeout(resolve, delay));
}
/**
* Create a debounced function that delays the execution of `callback` until a specified `delay` time has passed since the last call
*
* @param {Function} callback Function to debounce
* @param {number} delay Delay (in milliseconds)
* @returns {Function} Debounced function
*/
export function debounce(callback, delay) {
let timeout = null;
return (...args) => {
if (timeout)
clearTimeout(timeout);
timeout = setTimeout(() => callback(...args), delay);
};
}
/**
* Check if a value is defined
*
* @param {any} value Value to check
* @returns {boolean}
*/
export function isDefined(value) {
if (typeof value === 'undefined' || value === null)
return false;
return true;
}
/**
* Create a throttled function that limits the execution of `callback` to once every `limit` time
*
* @param {Function} callback Function to throttle
* @param {number} limit Minimum interval between two calls (in milliseconds)
* @returns {Function} Throttled function
*/
export function throttle(callback, limit) {
let lastTime = 0;
return (...args) => {
const time = now();
if (time - lastTime >= limit) {
lastTime = time;
callback(...args);
}
};
}
/**
* Deferred promise implementation
*
* @returns {Deferred}
*/
export function defer() {
let resolve;
let reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return { promise, resolve, reject };
}
/**
* Polyfill for `now()` functions
*/
export let now;
// In node.js, use `process.hrtime`
if (typeof process !== 'undefined' && process.hrtime) {
now = function () {
// Convert [seconds, nanoseconds] to milliseconds
const time = process.hrtime();
return time[0] * 1000 + time[1] / 1000000;
};
}
// In a browser use `performance` or `Date`
else if (typeof performance !== 'undefined') {
// This must be bound, because directly assigning this function leads to an invocation exception in Chrome
now = performance.now.bind(performance);
}
else if (typeof Date.now !== 'undefined') {
now = Date.now;
}
else {
now = function () {
return new Date().getTime();
};
}