Hello!
@@ -3415,9 +3308,8 @@ console.log(el.className); // 'container'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### createEventHub 
@@ -3444,12 +3336,12 @@ const createEventHub = () => ({
if (i > -1) this.hub[event].splice(i, 1);
}
});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const handler = data => console.log(data);
const hub = createEventHub();
let increment = 0;
@@ -3469,9 +3361,8 @@ hub.off('message', handler);
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### currentURL
@@ -3481,19 +3372,18 @@ Use `window.location.href` to get current URL.
```js
const currentURL = () => window.location.href;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
currentURL(); // 'https://google.com'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### detectDeviceType
@@ -3506,19 +3396,18 @@ const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
detectDeviceType(); // "Mobile" or "Desktop"
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### elementContains
@@ -3528,20 +3417,19 @@ Check that `parent` is not the same element as `child`, use `parent.contains(chi
```js
const elementContains = (parent, child) => parent !== child && parent.contains(child);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
elementContains(document.querySelector('head'), document.querySelector('title')); // true
elementContains(document.querySelector('body'), document.querySelector('body')); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### elementIsVisibleInViewport 
@@ -3561,21 +3449,20 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
elementIsVisibleInViewport(el); // false - (not fully visible)
elementIsVisibleInViewport(el, true); // true - (partially visible)
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### getScrollPosition
@@ -3589,19 +3476,18 @@ const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
getScrollPosition(); // {x: 0, y: 200}
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### getStyle
@@ -3611,19 +3497,18 @@ Use `Window.getComputedStyle()` to get the value of the CSS rule for the specifi
```js
const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
getStyle(document.querySelector('p'), 'font-size'); // '16px'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### hasClass
@@ -3633,19 +3518,18 @@ Use `element.classList.contains()` to check if the element has the specified cla
```js
const hasClass = (el, className) => el.classList.contains(className);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
hasClass(document.querySelector('p.special'), 'special'); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### hashBrowser 
@@ -3662,19 +3546,18 @@ const hashBrowser = val =>
hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
return hexes.join('');
});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
hashBrowser(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### hide
@@ -3684,19 +3567,18 @@ Use `NodeList.prototype.forEach()` to apply `display: none` to each element spec
```js
const hide = els => els.forEach(e => (e.style.display = 'none'));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
hide(document.querySelectorAll('img')); // Hides all
elements on the page
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### httpsRedirect
@@ -3708,19 +3590,18 @@ Use `location.protocol` to get the protocol currently being used. If it's not HT
const httpsRedirect = () => {
if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### insertAfter
@@ -3730,19 +3611,18 @@ Use `el.insertAdjacentHTML()` with a position of `'afterend'` to parse `htmlStri
```js
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
insertAfter(document.getElementById('myId'), 'after
'); // ...
after
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### insertBefore
@@ -3752,19 +3632,18 @@ Use `el.insertAdjacentHTML()` with a position of `'beforebegin'` to parse `htmlS
```js
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
insertBefore(document.getElementById('myId'), 'before
'); // before
...
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isBrowserTabFocused
@@ -3774,19 +3653,18 @@ Use the `Document.hidden` property, introduced by the Page Visibility API to che
```js
const isBrowserTabFocused = () => !document.hidden;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isBrowserTabFocused(); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### nodeListToArray
@@ -3796,19 +3674,18 @@ Use spread operator inside new array to convert a `NodeList` to an array.
```js
const nodeListToArray = nodeList => [...nodeList];
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
nodeListToArray(document.childNodes); // [ , html ]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### observeMutations 
@@ -3837,20 +3714,19 @@ const observeMutations = (element, callback, options) => {
);
return observer;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const obs = observeMutations(document, console.log); // Logs all mutations that happen on the page
obs.disconnect(); // Disconnects the observer and stops logging mutations on the page
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### off
@@ -3861,21 +3737,20 @@ Omit the fourth argument `opts` to use `false` or specify it based on the option
```js
const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const fn = () => console.log('!');
document.body.addEventListener('click', fn);
off(document.body, 'click', fn); // no longer logs '!' upon clicking on the page
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### on
@@ -3891,12 +3766,12 @@ const on = (el, evt, fn, opts = {}) => {
el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);
if (opts.target) return delegatorFn;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const fn = () => console.log('!');
on(document.body, 'click', fn); // logs '!' upon clicking the body
on(document.body, 'click', fn, { target: 'p' }); // logs '!' upon clicking a `p` element child of the body
@@ -3904,9 +3779,8 @@ on(document.body, 'click', fn, { options: true }); // use capturing instead of b
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### onUserInputChange 
@@ -3931,21 +3805,20 @@ const onUserInputChange = callback => {
(type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler);
});
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
onUserInputChange(type => {
console.log('The user is now using', type, 'as an input method.');
});
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### prefix
@@ -3963,19 +3836,18 @@ const prefix = prop => {
);
return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
prefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### recordAnimationFrames
@@ -4007,12 +3879,12 @@ const recordAnimationFrames = (callback, autoStart = true) => {
if (autoStart) start();
return { start, stop };
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const cb = () => console.log('Animation frame fired');
const recorder = recordAnimationFrames(cb); // logs 'Animation frame fired' on each animation frame
recorder.stop(); // stops logging
@@ -4021,9 +3893,8 @@ const recorder2 = recordAnimationFrames(cb, false); // `start` needs to be expli
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### redirect
@@ -4035,19 +3906,18 @@ Pass a second argument to simulate a link click (`true` - default) or an HTTP re
```js
const redirect = (url, asLink = true) =>
asLink ? (window.location.href = url) : window.location.replace(url);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
redirect('https://google.com');
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### runAsync 
@@ -4073,12 +3943,12 @@ const runAsync = fn => {
};
});
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const longRunningFunction = () => {
let result = 0;
for (let i = 0; i < 1000; i++) {
@@ -4102,9 +3972,8 @@ runAsync(() => typeof outsideVariable).then(console.log); // 'undefined'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### scrollToTop
@@ -4121,19 +3990,18 @@ const scrollToTop = () => {
window.scrollTo(0, c - c / 8);
}
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
scrollToTop();
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### setStyle
@@ -4143,19 +4011,18 @@ Use `element.style` to set the value of the CSS rule for the specified element t
```js
const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
setStyle(document.querySelector('p'), 'font-size', '20px'); // The first element on the page will have a font-size of 20px
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### show
@@ -4165,19 +4032,18 @@ Use the spread operator (`...`) and `Array.forEach()` to clear the `display` pro
```js
const show = (...el) => [...el].forEach(e => (e.style.display = ''));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
show(...document.querySelectorAll('img')); // Shows all
elements on the page
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### smoothScroll
@@ -4191,20 +4057,19 @@ const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar
smoothScroll('.fooBar'); // scrolls smoothly to the first element with a class of fooBar
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### toggleClass
@@ -4214,19 +4079,18 @@ Use `element.classList.toggle()` to toggle the specified class for the element.
```js
const toggleClass = (el, className) => el.classList.toggle(className);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### triggerEvent
@@ -4239,20 +4103,19 @@ Omit the third argument, `detail`, if you do not want to pass custom data to the
```js
const triggerEvent = (el, eventType, detail = undefined) =>
el.dispatchEvent(new CustomEvent(eventType, { detail: detail }));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
triggerEvent(document.getElementById('myId'), 'click');
triggerEvent(document.getElementById('myId'), 'click', { username: 'bob' });
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### UUIDGeneratorBrowser
@@ -4265,23 +4128,22 @@ const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
```
+
+[β¬ Back to top](#table-of-contents)
-
[β¬ Back to top](#table-of-contents)
-
----
- ## β±οΈ Date
-
-### formatDuration
+
+---
+## β±οΈ Date### formatDuration
Returns the human readable format of the given number of milliseconds.
@@ -4305,20 +4167,19 @@ const formatDuration = ms => {
.map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
.join(', ');
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### getColonTimeFromDate
@@ -4328,19 +4189,18 @@ Use `Date.toString()` and `String.slice()` to get the `HH:MM:SS` part of a given
```js
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
getColonTimeFromDate(new Date()); // "08:38:00"
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### getDaysDiffBetweenDates
@@ -4351,19 +4211,18 @@ Calculate the difference (in days) between two `Date` objects.
```js
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 3600 * 24);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### getMeridiemSuffixOfInteger
@@ -4380,12 +4239,12 @@ const getMeridiemSuffixOfInteger = num =>
: num < 12
? (num % 12) + 'am'
: (num % 12) + 'pm';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
getMeridiemSuffixOfInteger(0); // "12am"
getMeridiemSuffixOfInteger(11); // "11am"
getMeridiemSuffixOfInteger(13); // "1pm"
@@ -4393,9 +4252,8 @@ getMeridiemSuffixOfInteger(25); // "1pm"
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### tomorrow
@@ -4411,24 +4269,23 @@ const tomorrow = (long = false) => {
).padStart(2, '0')}`;
return !long ? ret : `${ret}T00:00:00`;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
tomorrow(); // 2017-12-27 (if current date is 2017-12-26)
tomorrow(true); // 2017-12-27T00:00:00 (if current date is 2017-12-26)
```
+
+[β¬ Back to top](#table-of-contents)
-
[β¬ Back to top](#table-of-contents)
-
----
- ## ποΈ Function
-
-### attempt
+
+---
+## ποΈ Function### attempt
Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
@@ -4442,12 +4299,12 @@ const attempt = (fn, ...args) => {
return e instanceof Error ? e : new Error(e);
}
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
@@ -4455,9 +4312,8 @@ if (elements instanceof Error) elements = []; // elements = []
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### bind
@@ -4468,12 +4324,12 @@ Use `Array.concat()` to prepend any additional supplied parameters to the argume
```js
const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
function greet(greeting, punctuation) {
return greeting + ' ' + this.user + punctuation;
}
@@ -4483,9 +4339,8 @@ console.log(freddyBound('hi', '!')); // 'hi fred!'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### bindKey
@@ -4497,12 +4352,12 @@ Use the spread operator (`...`) to prepend any additional supplied parameters to
```js
const bindKey = (context, fn, ...boundArgs) => (...args) =>
context[fn].apply(context, [...boundArgs, ...args]);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const freddy = {
user: 'fred',
greet: function(greeting, punctuation) {
@@ -4514,9 +4369,8 @@ console.log(freddyBound('hi', '!')); // 'hi fred!'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### chainAsync
@@ -4530,12 +4384,12 @@ const chainAsync = fns => {
const next = () => fns[curr++](next);
next();
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
chainAsync([
next => {
console.log('0 seconds');
@@ -4548,9 +4402,8 @@ chainAsync([
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### compose
@@ -4561,12 +4414,12 @@ The last (rightmost) function can accept one or more arguments; the remaining fu
```js
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const add5 = x => x + 5;
const multiply = (x, y) => x * y;
const multiplyAndAdd5 = compose(
@@ -4577,9 +4430,8 @@ multiplyAndAdd5(5, 2); // 15
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### composeRight
@@ -4590,12 +4442,12 @@ The first (leftmost) function can accept one or more arguments; the remaining fu
```js
const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const add = (x, y) => x + y;
const square = x => x * x;
const addAndSquare = composeRight(add, square);
@@ -4603,9 +4455,8 @@ addAndSquare(1, 2); // 9
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### converge
@@ -4616,12 +4467,12 @@ Use the spread operator (`...`) to call `coverger` with the results of all other
```js
const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args)));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const average = converge((a, b) => a / b, [
arr => arr.reduce((a, v) => a + v, 0),
arr => arr.length
@@ -4630,9 +4481,8 @@ average([1, 2, 3, 4, 5, 6, 7]); // 4
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### curry
@@ -4646,20 +4496,19 @@ If you want to curry a function that accepts a variable number of arguments (a v
```js
const curry = (fn, arity = fn.length, ...args) =>
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
curry(Math.pow)(2)(10); // 1024
curry(Math.min, 3)(10)(50)(2); // 2
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### debounce
@@ -4676,12 +4525,12 @@ const debounce = (fn, ms = 0) => {
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
window.addEventListener(
'resize',
debounce(() => {
@@ -4692,9 +4541,8 @@ window.addEventListener(
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### defer
@@ -4704,12 +4552,12 @@ Use `setTimeout()` with a timeout of 1ms to add a new event to the browser event
```js
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
// Example A:
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
@@ -4720,9 +4568,8 @@ defer(longRunningFunction); // Browser will update the HTML then run the functio
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### delay
@@ -4733,12 +4580,12 @@ Use the spread (`...`) operator to supply the function with an arbitrary number
```js
const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
delay(
function(text) {
console.log(text);
@@ -4749,9 +4596,8 @@ delay(
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### functionName
@@ -4761,19 +4607,18 @@ Use `console.debug()` and the `name` property of the passed method to log the me
```js
const functionName = fn => (console.debug(fn.name), fn);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
functionName(Math.max); // max (logged in debug channel of console)
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### hz
@@ -4790,12 +4635,12 @@ const hz = (fn, iterations = 100) => {
for (let i = 0; i < iterations; i++) fn();
return (1000 * iterations) / (performance.now() - before);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
// 10,000 element array
const numbers = Array(10000)
.fill()
@@ -4815,9 +4660,8 @@ Math.round(hz(sumForLoop)); // 4784
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### memoize 
@@ -4836,12 +4680,12 @@ const memoize = fn => {
cached.cache = cache;
return cached;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
// See the `anagrams` snippet.
const anagramsCached = memoize(anagrams);
anagramsCached('javascript'); // takes a long time
@@ -4850,9 +4694,8 @@ console.log(anagramsCached.cache); // The cached anagrams map
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### negate
@@ -4862,19 +4705,18 @@ Take a predicate function and apply the not operator (`!`) to it with its argume
```js
const negate = func => (...args) => !func(...args);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
[1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### once
@@ -4892,12 +4734,12 @@ const once = fn => {
return fn.apply(this, args);
};
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const startApp = function(event) {
console.log(this, event); // document.body, MouseEvent
};
@@ -4905,9 +4747,8 @@ document.body.addEventListener('click', once(startApp)); // only runs `startApp`
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### partial
@@ -4917,21 +4758,20 @@ Use the spread operator (`...`) to prepend `partials` to the list of arguments o
```js
const partial = (fn, ...partials) => (...args) => fn(...partials, ...args);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const greet = (greeting, name) => greeting + ' ' + name + '!';
const greetHello = partial(greet, 'Hello');
greetHello('John'); // 'Hello John!'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### partialRight
@@ -4941,21 +4781,20 @@ Use the spread operator (`...`) to append `partials` to the list of arguments of
```js
const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const greet = (greeting, name) => greeting + ' ' + name + '!';
const greetJohn = partialRight(greet, 'John');
greetJohn('Hello'); // 'Hello John!'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### runPromisesInSeries
@@ -4965,20 +4804,19 @@ Use `Array.reduce()` to create a promise chain, where each promise returns the n
```js
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const delay = d => new Promise(r => setTimeout(r, d));
runPromisesInSeries([() => delay(1000), () => delay(2000)]); // Executes each promise sequentially, taking a total of 3 seconds to complete
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### sleep
@@ -4988,12 +4826,12 @@ Delay executing part of an `async` function, by putting it to sleep, returning a
```js
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
async function sleepyWork() {
console.log("I'm going to sleep for 1 second.");
await sleep(1000);
@@ -5002,9 +4840,8 @@ async function sleepyWork() {
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### throttle 
@@ -5036,12 +4873,12 @@ const throttle = (fn, wait) => {
}
};
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
window.addEventListener(
'resize',
throttle(function(evt) {
@@ -5052,9 +4889,8 @@ window.addEventListener(
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### times
@@ -5068,21 +4904,20 @@ const times = (n, fn, context = undefined) => {
let i = 0;
while (fn.call(context, i) !== false && ++i < n) {}
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
var output = '';
times(5, i => (output += i));
console.log(output); // 01234
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### uncurry
@@ -5100,21 +4935,20 @@ const uncurry = (fn, n = 1) => (...args) => {
if (n > args.length) throw new RangeError('Arguments too few!');
return next(fn)(args.slice(0, n));
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const add = x => y => z => x + y + z;
const uncurriedAdd = uncurry(add, 3);
uncurriedAdd(1, 2, 3); // 6
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### unfold
@@ -5130,20 +4964,19 @@ const unfold = (fn, seed) => {
while ((val = fn(val[1]))) result.push(val[0]);
return result;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
var f = n => (n > 50 ? false : [-n, n + 10]);
unfold(f, 10); // [-10, -20, -30, -40, -50]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### when
@@ -5153,25 +4986,24 @@ Return a function expecting a single value, `x`, that returns the appropriate va
```js
const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const doubleEvenNumbers = when(x => x % 2 === 0, x => x * 2);
doubleEvenNumbers(2); // 4
doubleEvenNumbers(1); // 1
```
+
+[β¬ Back to top](#table-of-contents)
-
[β¬ Back to top](#table-of-contents)
-
----
- ## β Math
-
-### approximatelyEqual
+
+---
+## β Math### approximatelyEqual
Checks if two numbers are approximately equal to each other.
@@ -5180,19 +5012,18 @@ Omit the third parameter, `epsilon`, to use a default value of `0.001`.
```js
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### average
@@ -5202,20 +5033,19 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val
```js
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### averageBy
@@ -5227,20 +5057,19 @@ Use `Array.map()` to map each element to the value returned by `fn`, `Array.redu
const averageBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
arr.length;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### binomialCoefficient
@@ -5263,19 +5092,18 @@ const binomialCoefficient = (n, k) => {
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
binomialCoefficient(8, 2); // 28
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### clampNumber
@@ -5286,20 +5114,19 @@ Otherwise, return the nearest number in the range.
```js
const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
clampNumber(2, 3, 5); // 3
clampNumber(1, -1, -5); // -1
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### degreesToRads
@@ -5309,19 +5136,18 @@ Use `Math.PI` and the degree to radian formula to convert the angle from degrees
```js
const degreesToRads = deg => (deg * Math.PI) / 180.0;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
degreesToRads(90.0); // ~1.5708
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### digitize
@@ -5332,19 +5158,18 @@ Use `Array.map()` and `parseInt()` to transform each value to an integer.
```js
const digitize = n => [...`${n}`].map(i => parseInt(i));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
digitize(123); // [1, 2, 3]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### distance
@@ -5354,19 +5179,18 @@ Use `Math.hypot()` to calculate the Euclidean distance between two points.
```js
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
distance(1, 1, 2, 3); // 2.23606797749979
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### elo 
@@ -5397,12 +5221,12 @@ const elo = ([...ratings], kFactor = 32, selfRating) => {
}
return ratings;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
// Standard 1v1s
elo([1200, 1200]); // [1216, 1184]
elo([1200, 1200], 64); // [1232, 1168]
@@ -5416,9 +5240,8 @@ own individual rating by supplying it as the third argument.
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### factorial
@@ -5438,19 +5261,18 @@ const factorial = n =>
: n <= 1
? 1
: n * factorial(n - 1);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
factorial(6); // 720
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### fibonacci
@@ -5465,19 +5287,18 @@ const fibonacci = n =>
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
fibonacci(6); // [0, 1, 1, 2, 3, 5]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### gcd
@@ -5492,20 +5313,19 @@ const gcd = (...arr) => {
const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
return [...arr].reduce((a, b) => _gcd(a, b));
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
gcd(8, 36); // 4
gcd(...[12, 8, 32]); // 4
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### geometricProgression
@@ -5521,21 +5341,20 @@ const geometricProgression = (end, start = 1, step = 2) =>
Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(
(v, i) => start * step ** i
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
geometricProgression(256, 3); // [3, 6, 12, 24, 48, 96, 192]
geometricProgression(256, 1, 4); // [1, 4, 16, 64, 256]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### hammingDistance
@@ -5546,19 +5365,18 @@ Count and return the number of `1`s in the string, using `match(/1/g)`.
```js
const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
hammingDistance(2, 3); // 1
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### inRange
@@ -5572,12 +5390,12 @@ const inRange = (n, start, end = null) => {
if (end && start > end) [end, start] = [start, end];
return end == null ? n >= 0 && n < start : n >= start && n < end;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
inRange(3, 2, 5); // true
inRange(3, 4); // true
inRange(2, 3, 5); // false
@@ -5585,9 +5403,8 @@ inRange(3, 2); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isDivisible
@@ -5597,19 +5414,18 @@ Use the modulo operator (`%`) to check if the remainder is equal to `0`.
```js
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isDivisible(6, 3); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isEven
@@ -5620,19 +5436,18 @@ Returns `true` if the number is even, `false` if the number is odd.
```js
const isEven = num => num % 2 === 0;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isEven(3); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isPrime
@@ -5647,19 +5462,18 @@ const isPrime = num => {
for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
return num >= 2;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isPrime(11); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### lcm
@@ -5674,20 +5488,19 @@ const lcm = (...arr) => {
const _lcm = (x, y) => (x * y) / gcd(x, y);
return [...arr].reduce((a, b) => _lcm(a, b));
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
lcm(12, 7); // 84
lcm(...[1, 3, 4, 5]); // 60
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### luhnCheck 
@@ -5710,21 +5523,20 @@ const luhnCheck = num => {
sum += lastDigit;
return sum % 10 === 0;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
luhnCheck('4485275742308327'); // true
luhnCheck(6011329933655299); // false
luhnCheck(123456789); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### maxBy
@@ -5734,20 +5546,19 @@ Use `Array.map()` to map each element to the value returned by `fn`, `Math.max()
```js
const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8
maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### median
@@ -5762,19 +5573,18 @@ const median = arr => {
nums = [...arr].sort((a, b) => a - b);
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
median([5, 6, 50, 1, -5]); // 5
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### minBy
@@ -5784,20 +5594,19 @@ Use `Array.map()` to map each element to the value returned by `fn`, `Math.min()
```js
const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 2
minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 2
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### percentile
@@ -5808,19 +5617,18 @@ Use `Array.reduce()` to calculate how many numbers are below the value and how m
```js
const percentile = (arr, val) =>
(100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### powerset
@@ -5830,19 +5638,18 @@ Use `Array.reduce()` combined with `Array.map()` to iterate over elements and co
```js
const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
powerset([1, 2]); // [[], [1], [2], [2,1]]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### primes
@@ -5858,19 +5665,18 @@ const primes = num => {
numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x)));
return arr;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
primes(10); // [2,3,5,7]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### radsToDegrees
@@ -5880,19 +5686,18 @@ Use `Math.PI` and the radian to degree formula to convert the angle from radians
```js
const radsToDegrees = rad => (rad * 180.0) / Math.PI;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
radsToDegrees(Math.PI / 2); // 90
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### randomIntArrayInRange
@@ -5903,19 +5708,18 @@ Use `Array.from()` to create an empty array of the specific length, `Math.random
```js
const randomIntArrayInRange = (min, max, n = 1) =>
Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### randomIntegerInRange
@@ -5925,19 +5729,18 @@ Use `Math.random()` to generate a random number and map it to the desired range,
```js
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
randomIntegerInRange(0, 5); // 2
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### randomNumberInRange
@@ -5947,19 +5750,18 @@ Use `Math.random()` to generate a random value, map it to the desired range usin
```js
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
randomNumberInRange(2, 10); // 6.0211363285087005
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### round
@@ -5970,19 +5772,18 @@ Omit the second argument, `decimals` to round to an integer.
```js
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
round(1.005, 2); // 1.01
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### sdbm
@@ -5999,19 +5800,18 @@ const sdbm = str => {
0
);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
sdbm('name'); // -3521204949
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### standardDeviation
@@ -6029,20 +5829,19 @@ const standardDeviation = (arr, usePopulation = false) => {
(arr.length - (usePopulation ? 0 : 1))
);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample)
standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population)
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### sum
@@ -6052,19 +5851,18 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val
```js
const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
sum(...[1, 2, 3, 4]); // 10
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### sumBy
@@ -6075,20 +5873,19 @@ Use `Array.map()` to map each element to the value returned by `fn`, `Array.redu
```js
const sumBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20
sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### sumPower
@@ -6104,21 +5901,20 @@ const sumPower = (end, power = 2, start = 1) =>
.fill(0)
.map((x, i) => (i + start) ** power)
.reduce((a, b) => a + b, 0);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
sumPower(10); // 385
sumPower(10, 3); //3025
sumPower(10, 3, 5); //2925
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### toSafeInteger
@@ -6130,24 +5926,23 @@ Use `Math.round()` to convert to an integer.
```js
const toSafeInteger = num =>
Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
toSafeInteger('3.2'); // 3
toSafeInteger(Infinity); // 9007199254740991
```
+
+[β¬ Back to top](#table-of-contents)
-
[β¬ Back to top](#table-of-contents)
-
----
- ## π¦ Node
-
-### atob
+
+---
+## π¦ Node### atob
Decodes a string of data which has been encoded using base-64 encoding.
@@ -6155,19 +5950,18 @@ Create a `Buffer` for the given string with base-64 encoding and use `Buffer.toS
```js
const atob = str => new Buffer(str, 'base64').toString('binary');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
atob('Zm9vYmFy'); // 'foobar'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### btoa
@@ -6177,19 +5971,18 @@ Create a `Buffer` for the given string with binary encoding and use `Buffer.toSt
```js
const btoa = str => new Buffer(str, 'binary').toString('base64');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
btoa('foobar'); // 'Zm9vYmFy'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### colorize
@@ -6217,21 +6010,20 @@ const colorize = (...args) => ({
bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`,
bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m`
});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
console.log(colorize('foo').red); // 'foo' (red letters)
console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background)
console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite); // 'foo bar' (first word in yellow letters, second word in green letters, white background for both)
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### hasFlags
@@ -6243,12 +6035,12 @@ Use a regular expression to test if the specified flags are prefixed with `-` or
```js
const hasFlags = (...flags) =>
flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
// node myScript.js -s --test --cool=true
hasFlags('-s'); // true
hasFlags('--test', 'cool=true', '-s'); // true
@@ -6256,9 +6048,8 @@ hasFlags('special'); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### hashNode
@@ -6281,19 +6072,18 @@ const hashNode = val =>
0
)
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isTravisCI
@@ -6303,19 +6093,18 @@ Checks if the current environment has the `TRAVIS` and `CI` environment variable
```js
const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isTravisCI(); // true (if code is running on Travis CI)
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### JSONToFile
@@ -6327,19 +6116,18 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json`
const fs = require('fs');
const JSONToFile = (obj, filename) =>
fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### readFileLines
@@ -6356,12 +6144,12 @@ const readFileLines = filename =>
.readFileSync(filename)
.toString('UTF8')
.split('\n');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
/*
contents of test.txt :
line1
@@ -6375,9 +6163,8 @@ console.log(arr); // ['line1', 'line2', 'line3']
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### untildify
@@ -6387,19 +6174,18 @@ Use `String.replace()` with a regular expression and `OS.homedir()` to replace t
```js
const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
untildify('~/node'); // '/Users/aUser/node'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### UUIDGeneratorNode
@@ -6413,23 +6199,22 @@ const UUIDGeneratorNode = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'
```
+
+[β¬ Back to top](#table-of-contents)
-
[β¬ Back to top](#table-of-contents)
-
----
- ## ποΈ Object
-
-### bindAll
+
+---
+## ποΈ Object### bindAll
Binds methods of an object to the object itself, overwriting the existing method.
@@ -6445,12 +6230,12 @@ const bindAll = (obj, ...fns) =>
})
)
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
var view = {
label: 'docs',
click: function() {
@@ -6462,9 +6247,8 @@ jQuery(element).on('click', view.click); // Logs 'clicked docs' when clicked.
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### deepClone
@@ -6482,20 +6266,19 @@ const deepClone = obj => {
);
return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a); // a !== b, a.obj !== b.obj
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### deepFreeze
@@ -6509,12 +6292,12 @@ const deepFreeze = obj =>
prop =>
!obj[prop] instanceof Object || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
) || Object.freeze(obj);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
'use strict';
const o = deepFreeze([1, [2, 3]]);
@@ -6524,9 +6307,8 @@ o[1][0] = 4; // not allowed as well
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### defaults
@@ -6536,19 +6318,18 @@ Use `Object.assign()` to create a new empty object and copy the original one to
```js
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### dig
@@ -6565,12 +6346,12 @@ const dig = (obj, target) =>
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const data = {
level1: {
level2: {
@@ -6583,9 +6364,8 @@ dig(data, 'level4'); // undefined
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### equals 
@@ -6606,19 +6386,18 @@ const equals = (a, b) => {
if (keys.length !== Object.keys(b).length) return false;
return keys.every(k => equals(a[k], b[k]));
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### findKey
@@ -6628,12 +6407,12 @@ Use `Object.keys(obj)` to get all the properties of the object, `Array.find()` t
```js
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
findKey(
{
barney: { age: 36, active: true },
@@ -6645,9 +6424,8 @@ findKey(
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### findLastKey
@@ -6660,12 +6438,12 @@ const findLastKey = (obj, fn) =>
Object.keys(obj)
.reverse()
.find(key => fn(obj[key], key, obj));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
findLastKey(
{
barney: { age: 36, active: true },
@@ -6677,9 +6455,8 @@ findLastKey(
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### flattenObject
@@ -6699,19 +6476,18 @@ const flattenObject = (obj, prefix = '') =>
else acc[pre + k] = obj[k];
return acc;
}, {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### forOwn
@@ -6721,19 +6497,18 @@ Use `Object.keys(obj)` to get all the properties of the object, `Array.forEach()
```js
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### forOwnRight
@@ -6746,19 +6521,18 @@ const forOwnRight = (obj, fn) =>
Object.keys(obj)
.reverse()
.forEach(key => fn(obj[key], key, obj));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
forOwnRight({ foo: 'bar', a: 1 }, v => console.log(v)); // 1, 'bar'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### functions
@@ -6775,12 +6549,12 @@ const functions = (obj, inherited = false) =>
? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))]
: Object.keys(obj)
).filter(key => typeof obj[key] === 'function');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
function Foo() {
this.a = () => 1;
this.b = () => 2;
@@ -6791,9 +6565,8 @@ functions(new Foo(), true); // ['a', 'b', 'c']
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### get
@@ -6810,20 +6583,19 @@ const get = (from, ...selectors) =>
.filter(t => t !== '')
.reduce((prev, cur) => prev && prev[cur], from)
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### invertKeyValues
@@ -6840,20 +6612,19 @@ const invertKeyValues = (obj, fn) =>
acc[val].push(key);
return acc;
}, {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] }
invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value); // { group1: [ 'a', 'c' ], group2: [ 'b' ] }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### lowercaseKeys
@@ -6868,20 +6639,19 @@ const lowercaseKeys = obj =>
acc[key.toLowerCase()] = obj[key];
return acc;
}, {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const myObj = { Name: 'Adam', sUrnAME: 'Smith' };
const myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'};
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### mapKeys
@@ -6896,19 +6666,18 @@ const mapKeys = (obj, fn) =>
acc[fn(obj[k], k, obj)] = obj[k];
return acc;
}, {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### mapValues
@@ -6923,12 +6692,12 @@ const mapValues = (obj, fn) =>
acc[k] = fn(obj[k], k, obj);
return acc;
}, {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const users = {
fred: { user: 'fred', age: 40 },
pebbles: { user: 'pebbles', age: 1 }
@@ -6937,9 +6706,8 @@ mapValues(users, u => u.age); // { fred: 40, pebbles: 1 }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### matches
@@ -6950,20 +6718,19 @@ Use `Object.keys(source)` to get all the keys of the second object, then `Array.
```js
const matches = (obj, source) =>
Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true
matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### matchesWith
@@ -6980,12 +6747,12 @@ const matchesWith = (obj, source, fn) =>
? fn(obj[key], source[key], key, obj, source)
: obj[key] == source[key]
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const isGreeting = val => /^h(?:i|ello)$/.test(val);
matchesWith(
{ greeting: 'hello' },
@@ -6995,9 +6762,8 @@ matchesWith(
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### merge
@@ -7016,12 +6782,12 @@ const merge = (...objs) =>
}, {}),
{}
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const object = {
a: [{ x: 2 }, { y: 4 }],
b: 1
@@ -7035,9 +6801,8 @@ merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ],
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### nest
@@ -7054,12 +6819,12 @@ const nest = (items, id = null, link = 'parent_id') =>
items
.filter(item => item[link] === id)
.map(item => ({ ...item, children: nest(items, item.id) }));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
// One top level comment
const comments = [
{ id: 1, parent_id: null },
@@ -7073,9 +6838,8 @@ const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### objectFromPairs
@@ -7085,19 +6849,18 @@ Use `Array.reduce()` to create and combine key-value pairs.
```js
const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### objectToPairs
@@ -7107,19 +6870,18 @@ Use `Object.keys()` and `Array.map()` to iterate over the object's keys and prod
```js
const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### omit
@@ -7133,19 +6895,18 @@ const omit = (obj, arr) =>
Object.keys(obj)
.filter(k => !arr.includes(k))
.reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
omit({ a: 1, b: '2', c: 3 }, ['b']); // { 'a': 1, 'c': 3 }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### omitBy
@@ -7159,19 +6920,18 @@ const omitBy = (obj, fn) =>
Object.keys(obj)
.filter(k => !fn(obj[k], k))
.reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
omitBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { b: '2' }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### orderBy
@@ -7191,21 +6951,20 @@ const orderBy = (arr, props, orders) =>
return acc;
}, 0)
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const users = [{ name: 'fred', age: 48 }, { name: 'barney', age: 36 }, { name: 'fred', age: 40 }];
orderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
orderBy(users, ['name', 'age']); // [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### pick
@@ -7216,19 +6975,18 @@ Use `Array.reduce()` to convert the filtered/picked keys back to an object with
```js
const pick = (obj, arr) =>
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### pickBy
@@ -7242,19 +7000,18 @@ const pickBy = (obj, fn) =>
Object.keys(obj)
.filter(k => fn(obj[k], k))
.reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### renameKeys
@@ -7271,20 +7028,19 @@ const renameKeys = (keysMap, obj) =>
}),
{}
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### shallowClone
@@ -7294,20 +7050,19 @@ Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of th
```js
const shallowClone = obj => Object.assign({}, obj);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const a = { x: true, y: 1 };
const b = shallowClone(a); // a !== b
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### size
@@ -7329,21 +7084,20 @@ const size = val =>
: typeof val === 'string'
? new Blob([val]).size
: 0;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
size([1, 2, 3, 4, 5]); // 5
size('size'); // 4
size({ one: 1, two: 2, three: 3 }); // 3
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### transform
@@ -7353,12 +7107,12 @@ Use `Object.keys(obj)` to iterate over each key in the object, `Array.reduce()`
```js
const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
transform(
{ a: 1, b: 2, c: 1 },
(r, v, k) => {
@@ -7370,9 +7124,8 @@ transform(
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### truthCheckCollection
@@ -7382,19 +7135,18 @@ Use `Array.every()` to check if each passed object has the specified property an
```js
const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### unflattenObject 
@@ -7421,23 +7173,22 @@ const unflattenObject = obj =>
} else acc[k] = obj[k];
return acc;
}, {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
```
+
+[β¬ Back to top](#table-of-contents)
-
[β¬ Back to top](#table-of-contents)
-
----
- ## π String
-
-### byteSize
+
+---
+## π String### byteSize
Returns the length of a string in bytes.
@@ -7445,20 +7196,19 @@ Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/
```js
const byteSize = str => new Blob([str]).size;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
byteSize('π'); // 4
byteSize('Hello World'); // 11
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### capitalize
@@ -7470,20 +7220,19 @@ Omit the `lowerRest` parameter to keep the rest of the string intact, or set it
```js
const capitalize = ([first, ...rest], lowerRest = false) =>
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### capitalizeEveryWord
@@ -7493,19 +7242,18 @@ Use `String.replace()` to match the first character of each word and `String.toU
```js
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
capitalizeEveryWord('hello world!'); // 'Hello World!'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### CSVToArray
@@ -7522,21 +7270,20 @@ const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
.split('\n')
.map(v => v.split(delimiter));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
CSVToArray('a,b\nc,d'); // [['a','b'],['c','d']];
CSVToArray('a;b\nc;d', ';'); // [['a','b'],['c','d']];
CSVToArray('col1,col2\na,b\nc,d', ',', true); // [['a','b'],['c','d']];
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### CSVToJSON 
@@ -7559,20 +7306,19 @@ const CSVToJSON = (data, delimiter = ',') => {
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
});
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
CSVToJSON('col1,col2\na,b\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
CSVToJSON('col1;col2\na;b\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### decapitalize
@@ -7584,20 +7330,19 @@ Omit the `upperRest` parameter to keep the rest of the string intact, or set it
```js
const decapitalize = ([first, ...rest], upperRest = false) =>
first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar', true); // 'fOOBAR'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### escapeHTML
@@ -7618,19 +7363,18 @@ const escapeHTML = str =>
'"': '"'
}[tag] || tag)
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
escapeHTML('Me & you'); // '<a href="#">Me & you</a>'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### escapeRegExp
@@ -7640,19 +7384,18 @@ Use `String.replace()` to escape special characters.
```js
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
escapeRegExp('(test)'); // \\(test\\)
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### fromCamelCase
@@ -7667,21 +7410,20 @@ const fromCamelCase = (str, separator = '_') =>
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
.toLowerCase();
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'
fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isAbsoluteURL
@@ -7691,21 +7433,20 @@ Use a regular expression to test if the string is an absolute URL.
```js
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isAnagram
@@ -7724,19 +7465,18 @@ const isAnagram = (str1, str2) => {
.join('');
return normalize(str1) === normalize(str2);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isAnagram('iceman', 'cinema'); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isLowerCase
@@ -7746,21 +7486,20 @@ Convert the given string to lower case, using `String.toLowerCase()` and compare
```js
const isLowerCase = str => str === str.toLowerCase();
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isLowerCase('abc'); // true
isLowerCase('a3@$'); // true
isLowerCase('Ab4'); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isUpperCase
@@ -7771,21 +7510,20 @@ Convert the given string to upper case, using `String.toUpperCase()` and compare
```js
const isUpperCase = str => str === str.toUpperCase();
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isUpperCase('ABC'); // true
isLowerCase('A3@$'); // true
isLowerCase('aB4'); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### mapString
@@ -7801,19 +7539,18 @@ const mapString = (str, fn) =>
.split('')
.map((c, i) => fn(c, i, str))
.join('');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
mapString('lorem ipsum', c => c.toUpperCase()); // 'LOREM IPSUM'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### mask
@@ -7827,21 +7564,20 @@ Omit the third argument, `mask`, to use a default character of `'*'` for the mas
```js
const mask = (cc, num = 4, mask = '*') =>
('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
mask(1234567890, -4, '$'); // '$$$$567890'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### pad
@@ -7853,21 +7589,20 @@ Omit the third argument, `char`, to use the whitespace character as the default
```js
const pad = (str, length, char = ' ') =>
str.padStart((str.length + length) / 2, char).padEnd(length, char);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
pad('cat', 8); // ' cat '
pad(String(42), 6, '0'); // '004200'
pad('foobar', 3); // 'foobar'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### palindrome
@@ -7881,19 +7616,18 @@ const palindrome = str => {
const s = str.toLowerCase().replace(/[\W_]/g, '');
return s === [...s].reverse().join('');
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
palindrome('taco cat'); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### pluralize
@@ -7908,12 +7642,12 @@ const pluralize = (val, word, plural = word + 's') => {
if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]);
return _pluralize(val, word, plural);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
pluralize(0, 'apple'); // 'apples'
pluralize(1, 'apple'); // 'apple'
pluralize(2, 'apple'); // 'apples'
@@ -7928,9 +7662,8 @@ autoPluralize(2, 'person'); // 'people'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### removeNonASCII
@@ -7940,19 +7673,18 @@ Use a regular expression to remove non-printable ASCII characters.
```js
const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
removeNonASCII('Γ€ΓΓ§ΓΓ©ΓΓͺlorem-ipsumΓΆΓΓΓΎΓΊΓ'); // 'lorem-ipsum'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### reverseString
@@ -7963,19 +7695,18 @@ Combine characters to get a string using `String.join('')`.
```js
const reverseString = str => [...str].reverse().join('');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
reverseString('foobar'); // 'raboof'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### sortCharactersInString
@@ -7985,19 +7716,18 @@ Use the spread operator (`...`), `Array.sort()` and `String.localeCompare()` to
```js
const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
sortCharactersInString('cabbage'); // 'aabbceg'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### splitLines
@@ -8007,19 +7737,18 @@ Use `String.split()` and a regular expression to match line breaks and create an
```js
const splitLines = str => str.split(/\r?\n/);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### stringPermutations 
@@ -8043,19 +7772,18 @@ const stringPermutations = str => {
[]
);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba']
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### stripHTMLTags
@@ -8065,19 +7793,18 @@ Use a regular expression to remove HTML/XML tags from a string.
```js
const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
stripHTMLTags('lorem ipsum
'); // 'lorem ipsum'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### toCamelCase
@@ -8095,12 +7822,12 @@ const toCamelCase = str => {
.join('');
return s.slice(0, 1).toLowerCase() + s.slice(1);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
toCamelCase('some_database_field_name'); // 'someDatabaseFieldName'
toCamelCase('Some label that needs to be camelized'); // 'someLabelThatNeedsToBeCamelized'
toCamelCase('some-javascript-property'); // 'someJavascriptProperty'
@@ -8108,9 +7835,8 @@ toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMi
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### toKebabCase
@@ -8125,12 +7851,12 @@ const toKebabCase = str =>
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('-');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
toKebabCase('camelCase'); // 'camel-case'
toKebabCase('some text'); // 'some-text'
toKebabCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some-mixed-string-with-spaces-underscores-and-hyphens'
@@ -8139,9 +7865,8 @@ toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSo
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### toSnakeCase
@@ -8156,12 +7881,12 @@ const toSnakeCase = str =>
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('_');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
toSnakeCase('camelCase'); // 'camel_case'
toSnakeCase('some text'); // 'some_text'
toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens'
@@ -8170,9 +7895,8 @@ toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSo
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### truncateString
@@ -8184,19 +7908,18 @@ Return the string truncated to the desired length, with `'...'` appended to the
```js
const truncateString = (str, num) =>
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
truncateString('boomerang', 7); // 'boom...'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### unescapeHTML
@@ -8217,19 +7940,18 @@ const unescapeHTML = str =>
'"': '"'
}[tag] || tag)
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
unescapeHTML('<a href="#">Me & you</a>'); // 'Me & you'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### URLJoin 
@@ -8247,19 +7969,18 @@ const URLJoin = (...args) =>
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### words
@@ -8270,24 +7991,23 @@ Omit the second argument to use the default regexp.
```js
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
words('I love javaScript!!'); // ["I", "love", "javaScript"]
words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]
```
+
+[β¬ Back to top](#table-of-contents)
-
[β¬ Back to top](#table-of-contents)
-
----
- ## π Type
-
-### getType
+
+---
+## π Type### getType
Returns the native type of a value.
@@ -8296,19 +8016,18 @@ Returns lowercased constructor name of value, `"undefined"` or `"null"` if value
```js
const getType = v =>
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
getType(new Set([1, 2, 3])); // 'set'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### is
@@ -8318,12 +8037,12 @@ Ensure the value is not `undefined` or `null` using `Array.includes()`, and comp
```js
const is = (type, val) => ![, null].includes(val) && val.constructor === type;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
is(Array, [1]); // true
is(ArrayBuffer, new ArrayBuffer()); // true
is(Map, new Map()); // true
@@ -8340,9 +8059,8 @@ is(Boolean, new Boolean(true)); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isArrayLike
@@ -8352,21 +8070,20 @@ Check if the provided argument is not `null` and that its `Symbol.iterator` prop
```js
const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isArrayLike(document.querySelectorAll('.className')); // true
isArrayLike('abc'); // true
isArrayLike(null); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isBoolean
@@ -8376,20 +8093,19 @@ Use `typeof` to check if a value is classified as a boolean primitive.
```js
const isBoolean = val => typeof val === 'boolean';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isBoolean(null); // false
isBoolean(false); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isEmpty
@@ -8399,12 +8115,12 @@ Check if the provided value is `null` or if its `length` is equal to `0`.
```js
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isEmpty(new Map()); // true
isEmpty(new Set()); // true
isEmpty([]); // true
@@ -8418,9 +8134,8 @@ isEmpty(true); // true - type is not considered a collection
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isFunction
@@ -8430,20 +8145,19 @@ Use `typeof` to check if a value is classified as a function primitive.
```js
const isFunction = val => typeof val === 'function';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isFunction('x'); // false
isFunction(x => x); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isNil
@@ -8453,20 +8167,19 @@ Use the strict equality operator to check if the value and of `val` are equal to
```js
const isNil = val => val === undefined || val === null;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isNil(null); // true
isNil(undefined); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isNull
@@ -8476,19 +8189,18 @@ Use the strict equality operator to check if the value and of `val` are equal to
```js
const isNull = val => val === null;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isNull(null); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isNumber
@@ -8498,20 +8210,19 @@ Use `typeof` to check if a value is classified as a number primitive.
```js
const isNumber = val => typeof val === 'number';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isNumber('1'); // false
isNumber(1); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isObject
@@ -8522,12 +8233,12 @@ If the value is `null` or `undefined`, create and return an empty object. Ξther
```js
const isObject = obj => obj === Object(obj);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isObject([1, 2, 3, 4]); // true
isObject([]); // true
isObject(['Hello!']); // true
@@ -8537,9 +8248,8 @@ isObject(true); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isObjectLike
@@ -8549,12 +8259,12 @@ Check if the provided value is not `null` and its `typeof` is equal to `'object'
```js
const isObjectLike = val => val !== null && typeof val === 'object';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isObjectLike({}); // true
isObjectLike([1, 2, 3]); // true
isObjectLike(x => x); // false
@@ -8562,9 +8272,8 @@ isObjectLike(null); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isPlainObject
@@ -8574,20 +8283,19 @@ Check if the provided value is truthy, use `typeof` to check if it is an object
```js
const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isPlainObject({ a: 1 }); // true
isPlainObject(new Map()); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isPrimitive
@@ -8599,12 +8307,12 @@ Since `typeof null` evaluates to `'object'`, it needs to be directly compared.
```js
const isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isPrimitive(null); // true
isPrimitive(50); // true
isPrimitive('Hello!'); // true
@@ -8614,9 +8322,8 @@ isPrimitive([]); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isPromiseLike
@@ -8629,12 +8336,12 @@ const isPromiseLike = obj =>
obj !== null &&
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.then === 'function';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isPromiseLike({
then: function() {
return '';
@@ -8645,9 +8352,8 @@ isPromiseLike({}); // false
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isString
@@ -8657,19 +8363,18 @@ Use `typeof` to check if a value is classified as a string primitive.
```js
const isString = val => typeof val === 'string';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isString('10'); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isSymbol
@@ -8679,19 +8384,18 @@ Use `typeof` to check if a value is classified as a symbol primitive.
```js
const isSymbol = val => typeof val === 'symbol';
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isSymbol(Symbol('x')); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isUndefined
@@ -8701,19 +8405,18 @@ Use the strict equality operator to check if the value and of `val` are equal to
```js
const isUndefined = val => val === undefined;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isUndefined(undefined); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isValidJSON
@@ -8730,25 +8433,24 @@ const isValidJSON = obj => {
return false;
}
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isValidJSON('{"name":"Adam","age":20}'); // true
isValidJSON('{"name":"Adam",age:"20"}'); // false
isValidJSON(null); // true
```
+
+[β¬ Back to top](#table-of-contents)
-
[β¬ Back to top](#table-of-contents)
-
----
- ## π§ Utility
-
-### castArray
+
+---
+## π§ Utility### castArray
Casts the provided value as an array if it's not one.
@@ -8756,20 +8458,19 @@ Use `Array.isArray()` to determine if `val` is an array and return it as-is or e
```js
const castArray = val => (Array.isArray(val) ? val : [val]);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
castArray('foo'); // ['foo']
castArray([1]); // [1]
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### cloneRegExp
@@ -8779,20 +8480,19 @@ Use `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regula
```js
const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const regExp = /lorem ipsum/gi;
const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### coalesce
@@ -8802,19 +8502,18 @@ Use `Array.find()` to return the first non `null`/`undefined` argument.
```js
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
coalesce(null, undefined, '', NaN, 'Waldo'); // ""
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### coalesceFactory
@@ -8824,20 +8523,19 @@ Use `Array.find()` to return the first argument that returns `true` from the pro
```js
const coalesceFactory = valid => (...args) => args.find(valid);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));
customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo"
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### extendHex
@@ -8854,20 +8552,19 @@ const extendHex = shortHex =>
.split('')
.map(x => x + x)
.join('');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
extendHex('#03f'); // '#0033ff'
extendHex('05a'); // '#0055aa'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### getURLParameters
@@ -8882,20 +8579,19 @@ const getURLParameters = url =>
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{}
);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
getURLParameters('google.com'); // {}
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### hexToRGB 
@@ -8923,21 +8619,20 @@ const hexToRGB = hex => {
')'
);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
hexToRGB('#27ae60ff'); // 'rgba(39, 174, 96, 255)'
hexToRGB('27ae60'); // 'rgb(39, 174, 96)'
hexToRGB('#fff'); // 'rgb(255, 255, 255)'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### httpGet
@@ -8956,12 +8651,12 @@ const httpGet = (url, callback, err = console.error) => {
request.onerror = () => err(request);
request.send();
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
httpGet(
'https://jsonplaceholder.typicode.com/posts/1',
console.log
@@ -8976,9 +8671,8 @@ Logs: {
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### httpPost
@@ -9000,12 +8694,12 @@ const httpPost = (url, data, callback, err = console.error) => {
request.onerror = () => err(request);
request.send(data);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const newPost = {
userId: 1,
id: 1337,
@@ -9037,9 +8731,8 @@ Logs: {
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### isBrowser
@@ -9051,20 +8744,19 @@ If both of them are not `undefined`, then the current environment is assumed to
```js
const isBrowser = () => ![typeof window, typeof document].includes('undefined');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
isBrowser(); // true (browser)
isBrowser(); // false (Node)
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### mostPerformant
@@ -9083,12 +8775,12 @@ const mostPerformant = (fns, iterations = 10000) => {
});
return times.indexOf(Math.min(...times));
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
mostPerformant([
() => {
// Loops through the entire array before returning `false`
@@ -9102,9 +8794,8 @@ mostPerformant([
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### nthArg
@@ -9114,12 +8805,12 @@ Use `Array.slice()` to get the desired argument at index `n`.
```js
const nthArg = n => (...args) => args.slice(n)[0];
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
const third = nthArg(2);
third(1, 2, 3); // 3
third(1, 2); // undefined
@@ -9128,9 +8819,8 @@ last(1, 2, 3, 4, 5); // 5
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### parseCookie
@@ -9149,19 +8839,18 @@ const parseCookie = str =>
acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
return acc;
}, {});
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' }
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### prettyBytes 
@@ -9181,21 +8870,20 @@ const prettyBytes = (num, precision = 3, addSpace = true) => {
const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));
return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
prettyBytes(1000); // "1 KB"
prettyBytes(-27145424323.5821, 5); // "-27.145 GB"
prettyBytes(123456789, 3, false); // "123MB"
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### randomHexColorCode
@@ -9208,19 +8896,18 @@ const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
randomHexColorCode(); // "#e34155"
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### RGBToHex
@@ -9230,19 +8917,18 @@ Convert given RGB parameters to hexadecimal string using bitwise left-shift oper
```js
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
RGBToHex(255, 165, 1); // 'ffa501'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### serializeCookie
@@ -9252,19 +8938,18 @@ Use template literals and `encodeURIComponent()` to create the appropriate strin
```js
const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
serializeCookie('foo', 'bar'); // 'foo=bar'
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### timeTaken
@@ -9279,19 +8964,18 @@ const timeTaken = callback => {
console.timeEnd('timeTaken');
return r;
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### toCurrency
@@ -9302,12 +8986,12 @@ Use `Intl.NumberFormat` to enable country / currency sensitive formatting.
```js
const toCurrency = (n, curr, LanguageFormat = undefined) =>
Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
toCurrency(123456.789, 'EUR'); // β¬123,456.79 | currency: Euro | currencyLangFormat: Local
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79 | currency: US Dollar | currencyLangFormat: English (United States)
toCurrency(123456.789, 'USD', 'fa'); // Ϋ±Ϋ²Ϋ³Ω¬Ϋ΄Ϋ΅ΫΆΩ«Ϋ·ΫΉ Ψ$ | currency: US Dollar | currencyLangFormat: Farsi
@@ -9316,9 +9000,8 @@ toCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 Β₯ | currency: Ja
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### toDecimalMark
@@ -9326,19 +9009,18 @@ Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark]
```js
const toDecimalMark = num => num.toLocaleString('en-US');
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
toDecimalMark(12305030388.9087); // "12,305,030,388.909"
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### toOrdinalSuffix
@@ -9359,19 +9041,18 @@ const toOrdinalSuffix = num => {
? int + ordinals[digits[0] - 1]
: int + ordinals[3];
};
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
toOrdinalSuffix('123'); // "123rd"
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### validateNumber
@@ -9383,19 +9064,18 @@ Use `Number()` to check if the coercion holds.
```js
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
validateNumber('10'); // true
```
-
-
[β¬ Back to top](#table-of-contents)
-
+
+[β¬ Back to top](#table-of-contents)
### yesNo
@@ -9407,12 +9087,12 @@ Omit the second argument, `def` to set the default answer as `no`.
```js
const yesNo = (val, def = false) =>
/^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;
-```
+```
-Examples
-
-```js
+ Examples
+
+ ```js
yesNo('Y'); // true
yesNo('yes'); // true
yesNo('No'); // false
@@ -9420,8 +9100,8 @@ yesNo('Foo', true); // true
```
-
-
[β¬ Back to top](#table-of-contents)
+
+[β¬ Back to top](#table-of-contents)
## Collaborators
diff --git a/package-lock.json b/package-lock.json
index cde2cebe0..a1a8dbdde 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -5696,9 +5696,9 @@
}
},
"markdown-builder": {
- "version": "0.8.1",
- "resolved": "https://registry.npmjs.org/markdown-builder/-/markdown-builder-0.8.1.tgz",
- "integrity": "sha512-zqOAYg8jqUM6gB4WkcJ/K5HkqPUL33VAqNrebHSxlkXcEcjDTeKMNqUC8/bND4tKRu72lRFrTmmGYRtlevvXZQ==",
+ "version": "0.8.3-dev",
+ "resolved": "https://registry.npmjs.org/markdown-builder/-/markdown-builder-0.8.3-dev.tgz",
+ "integrity": "sha512-NJp9MW/odYYP8z1lEEwDW3k+iVnzW1xaJqwWbjlzsAAA1kZohi6Cf3bQkWKZsxPJTZACgYd/aKpmunLSD1u2Bw==",
"requires": {
"husky": "1.0.0-rc.14"
}
diff --git a/package.json b/package.json
index 2952c6c1f..92d5c0451 100644
--- a/package.json
+++ b/package.json
@@ -52,7 +52,7 @@
},
"homepage": "https://github.com/Chalarangelo/30-seconds-of-code#readme",
"dependencies": {
- "markdown-builder": "^0.8.1"
+ "markdown-builder": "^0.8.3-dev"
},
"jest": {
"reporters": [
diff --git a/snippets_archive/README.md b/snippets_archive/README.md
index abc633d5c..51ace3c7e 100644
--- a/snippets_archive/README.md
+++ b/snippets_archive/README.md
@@ -1,4 +1,4 @@
-
+
# Snippets Archive
These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.
## Table of Contents
@@ -38,13 +38,12 @@ const JSONToDate = arr => {
Examples
-```js
+ ```js
JSONToDate(/Date(1489525200000)/); // "14/3/2017"
```
-
[β¬ Back to top](#table-of-contents)
### speechSynthesis
@@ -67,13 +66,12 @@ const speechSynthesis = message => {
Examples
-```js
+ ```js
speechSynthesis('Hello, World'); // // plays the message
```
-
[β¬ Back to top](#table-of-contents)
### binarySearch
@@ -99,14 +97,13 @@ const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
Examples
-```js
+ ```js
binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2
binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1
```
-
[β¬ Back to top](#table-of-contents)
### cleanObj
@@ -132,14 +129,13 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => {
Examples
-```js
+ ```js
const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };
cleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}
```
-
[β¬ Back to top](#table-of-contents)
### collatz
@@ -155,13 +151,12 @@ const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
Examples
-```js
+ ```js
collatz(8); // 4
```
-
[β¬ Back to top](#table-of-contents)
### countVowels
@@ -177,14 +172,13 @@ const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
Examples
-```js
+ ```js
countVowels('foobar'); // 3
countVowels('gym'); // 0
```
-
[β¬ Back to top](#table-of-contents)
### factors
@@ -226,7 +220,7 @@ const factors = (num, primes = false) => {
Examples
-```js
+ ```js
factors(12); // [2,3,4,6,12]
factors(12, true); // [2,3]
factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]
@@ -235,7 +229,6 @@ factors(-12, true); // [2,3]
-
[β¬ Back to top](#table-of-contents)
### fibonacciCountUntilNum
@@ -252,13 +245,12 @@ const fibonacciCountUntilNum = num =>
Examples
-```js
+ ```js
fibonacciCountUntilNum(10); // 7
```
-
[β¬ Back to top](#table-of-contents)
### fibonacciUntilNum
@@ -282,13 +274,12 @@ const fibonacciUntilNum = num => {
Examples
-```js
+ ```js
fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
```
-
[β¬ Back to top](#table-of-contents)
### httpDelete
@@ -313,7 +304,7 @@ const httpDelete = (url, callback, err = console.error) => {
Examples
-```js
+ ```js
httpDelete('https://website.com/users/123', request => {
console.log(request.responseText);
}); // 'Deletes a user from the database'
@@ -321,7 +312,6 @@ httpDelete('https://website.com/users/123', request => {
-
[β¬ Back to top](#table-of-contents)
### httpPut
@@ -348,7 +338,7 @@ const httpPut = (url, data, callback, err = console.error) => {
Examples
-```js
+ ```js
const password = "fooBaz";
const data = JSON.stringify(password);
httpPut('https://website.com/users/123', data, request => {
@@ -358,7 +348,6 @@ httpPut('https://website.com/users/123', data, request => {
-
[β¬ Back to top](#table-of-contents)
### isArmstrongNumber
@@ -377,14 +366,13 @@ const isArmstrongNumber = digits =>
Examples
-```js
+ ```js
isArmstrongNumber(1634); // true
isArmstrongNumber(56); // false
```
-
[β¬ Back to top](#table-of-contents)
### isSimilar
@@ -404,14 +392,13 @@ const isSimilar = (pattern, str) =>
Examples
-```js
+ ```js
isSimilar('rt','Rohit'); // true
isSimilar('tr','Rohit'); // false
```
-
[β¬ Back to top](#table-of-contents)
### levenshteinDistance
@@ -444,7 +431,7 @@ const levenshteinDistance = (string1, string2) => {
Examples
-```js
+ ```js
levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7
const compareStrings = (string1,string2) => (100 - levenshteinDistance(string1,string2) / Math.max(string1.length,string2.length));
compareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)
@@ -452,7 +439,6 @@ compareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)
-
[β¬ Back to top](#table-of-contents)
### quickSort
@@ -477,14 +463,13 @@ const quickSort = ([n, ...nums], desc) =>
Examples
-```js
+ ```js
quickSort([4, 1, 3, 2]); // [1,2,3,4]
quickSort([4, 1, 3, 2], true); // [4,3,2,1]
```
-
[β¬ Back to top](#table-of-contents)
### removeVowels
@@ -501,14 +486,13 @@ const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl);
Examples
-```js
+ ```js
removeVowels("foobAr"); // "fbr"
removeVowels("foobAr","*"); // "f**b*r"
```
-
[β¬ Back to top](#table-of-contents)
### solveRPN
@@ -555,14 +539,13 @@ const solveRPN = rpn => {
Examples
-```js
+ ```js
solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
solveRPN('2 3 ^'); // 8
```
-
[β¬ Back to top](#table-of-contents)
### howManyTimes
@@ -591,7 +574,7 @@ const howManyTimes = (num, divisor) => {
Examples
-```js
+ ```js
howManyTimes(100, 2); // 2
howManyTimes(100, 2.5); // 2
howManyTimes(100, 0); // 0
@@ -600,6 +583,5 @@ howManyTimes(100, -1); // Infinity
-
[β¬ Back to top](#table-of-contents)