1227 lines
159 KiB
HTML
1227 lines
159 KiB
HTML
<!DOCTYPE html><html lang="en"><head><link rel="stylesheet" href="./mini.css"><link href="https://fonts.googleapis.com/css?family=Inconsolata:400,700|Poppins:400,400i,500,700,700i&subset=latin-ext" rel="stylesheet"><title>30 seconds of code</title><meta charset="utf-8"><meta name="description" content="Curated collection of useful Javascript snippets that you can understand in 30 seconds or less."><meta name="keywords" content="javascript, snippets, code, programming"><meta name="author" content="Angelos Chalaris (chalarangelo@gmail.com)"><meta name="viewport" content="width=device-width,initial-scale=1"><meta property="og:title" content="30 seconds of code"><meta property="og:description" content="Curated collection of useful Javascript snippets that you can understand in 30 seconds or less."/><meta property="og:type" content="website"/><meta property="og:image" content="favicon.png"><link rel="icon" type="image/png" href="favicon.png"><link rel="stylesheet" href="prism.css"></head><script>const search = (node) => {
|
|
// Hide non-query-matching snippets
|
|
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => {
|
|
x.style.display = x.getAttribute("href").toUpperCase().indexOf(node.value.toUpperCase()) + 1 ? '' : 'none'
|
|
});
|
|
Array.from( node.parentElement.parentElement.children )
|
|
// Filter out the hidden links
|
|
.filter( x => !( x.tagName == 'A' && x.style.display == 'none' ) )
|
|
// set the display for each element based on if it's a H3
|
|
// If it's the last element and an H3, hide it
|
|
// Otherwise if it's and H3 and the next element is an H3, hide it
|
|
// Otherwise display it
|
|
.forEach( ( element, index, source) => {
|
|
element.style.display = (element.tagName == 'H3' && index + 1 == source.length ? 'none' : element.tagName == 'H3' && source[index + 1].tagName == 'H3' ? 'none' : '')
|
|
})
|
|
}
|
|
function loader() {
|
|
clipboard();
|
|
exampleMaker();
|
|
}
|
|
function clipboard() {
|
|
const snippets = document.querySelectorAll(":not(pre) + pre");
|
|
snippets.forEach(element => {
|
|
const button = document.createElement("button");
|
|
button.className = 'primary clipboard-copy';
|
|
button.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-clipboard"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect></svg> Copy to clipboard';
|
|
element.parentElement.appendChild(button);
|
|
|
|
button.addEventListener ("click", function() {
|
|
//The following regex removes all the comments from the snippet
|
|
const text = element.textContent;
|
|
// Apparently you can't copy a variable to clipboard so you need to create text input element,
|
|
// give it a value, copy it and then remove it from DOM.
|
|
const textArea = document.createElement("textarea");
|
|
textArea.value = text.trim();
|
|
document.body.appendChild(textArea);
|
|
console.log(textArea.innerText);
|
|
textArea.select();
|
|
document.execCommand("Copy");
|
|
document.body.removeChild(textArea);
|
|
});
|
|
});
|
|
};
|
|
function exampleMaker() {
|
|
const examples = document.querySelectorAll("pre + pre");
|
|
examples.forEach(el => {
|
|
let wrapper = document.createElement('div');
|
|
wrapper.className = 'collapse';
|
|
let toggle = document.createElement('input');
|
|
toggle.type = 'checkbox';
|
|
toggle.id = el.parentElement.parentElement.querySelector('h3').id+'-examples';
|
|
let label = document.createElement('label');
|
|
label.htmlFor = el.parentElement.parentElement.querySelector('h3').id+'-examples';
|
|
label.innerHTML = 'Show examples';
|
|
let box = document.createElement('div');
|
|
el.parentNode.insertBefore(wrapper, el);
|
|
wrapper.appendChild(toggle);
|
|
wrapper.appendChild(label);
|
|
wrapper.appendChild(box);
|
|
box.appendChild(el);
|
|
});
|
|
}</script><body onload="loader()"><a href="https://github.com/Chalarangelo/30-seconds-of-code/fork" class="github-corner" aria-label="View source on Github"><svg width="90" height="90" viewBox="0 0 250 250" style="fill:#151513;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style><header style="height:5.5rem"><h1 class="logo" href="https://github.com/Chalarangelo/30-seconds-of-code"><img src="favicon.png" style="height:4rem"/><span id="title"> 30 seconds of code</span> <small>Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.</small></h1><label for="doc-drawer-checkbox" class="button drawer-toggle" id="menu-toggle"></label></header><div class="row" style="height:calc(100vh - 5.875rem);overflow:hidden"><input id="doc-drawer-checkbox" class="drawer" value="on" type="checkbox"><nav class="col-md-4 col-lg-3" style="border-top:0"><div class="group"><input class="search" type="text" id="searchInput" onkeyup="search(this)"><label id="search-label">Search for snippet...</label></div><label for="doc-drawer-checkbox" class="button drawer-close"></label><h3>Adapter</h3><a class="sublink-1" href="#call">call</a> <a class="sublink-1" href="#collectinto">collectInto</a> <a class="sublink-1" href="#flip">flip</a> <a class="sublink-1" href="#pipefunctions">pipeFunctions</a> <a class="sublink-1" href="#promisify">promisify</a> <a class="sublink-1" href="#spreadover">spreadOver</a><h3>Array</h3><a class="sublink-1" href="#chunk">chunk</a> <a class="sublink-1" href="#compact">compact</a> <a class="sublink-1" href="#countoccurrences">countOccurrences</a> <a class="sublink-1" href="#deepflatten">deepFlatten</a> <a class="sublink-1" href="#difference">difference</a> <a class="sublink-1" href="#differencewith">differenceWith</a> <a class="sublink-1" href="#distinctvaluesofarray">distinctValuesOfArray</a> <a class="sublink-1" href="#dropelements">dropElements</a> <a class="sublink-1" href="#dropright">dropRight</a> <a class="sublink-1" href="#everynth">everyNth</a> <a class="sublink-1" href="#filternonunique">filterNonUnique</a> <a class="sublink-1" href="#flatten">flatten</a> <a class="sublink-1" href="#flattendepth">flattenDepth</a> <a class="sublink-1" href="#groupby">groupBy</a> <a class="sublink-1" href="#head">head</a> <a class="sublink-1" href="#initial">initial</a> <a class="sublink-1" href="#initialize2darray">initialize2DArray</a> <a class="sublink-1" href="#initializearraywithrange">initializeArrayWithRange</a> <a class="sublink-1" href="#initializearraywithvalues">initializeArrayWithValues</a> <a class="sublink-1" href="#intersection">intersection</a> <a class="sublink-1" href="#issorted">isSorted</a> <a class="sublink-1" href="#join">join</a> <a class="sublink-1" href="#last">last</a> <a class="sublink-1" href="#mapobject">mapObject</a> <a class="sublink-1" href="#maxn">maxN</a> <a class="sublink-1" href="#minn">minN</a> <a class="sublink-1" href="#nthelement">nthElement</a> <a class="sublink-1" href="#pick">pick</a> <a class="sublink-1" href="#pull">pull</a> <a class="sublink-1" href="#pullatindex">pullAtIndex</a> <a class="sublink-1" href="#pullatvalue">pullAtValue</a> <a class="sublink-1" href="#quicksort">quickSort</a> <a class="sublink-1" href="#reducedfilter">reducedFilter</a> <a class="sublink-1" href="#remove">remove</a> <a class="sublink-1" href="#sample">sample</a> <a class="sublink-1" href="#samplesize">sampleSize</a> <a class="sublink-1" href="#shuffle">shuffle</a> <a class="sublink-1" href="#similarity">similarity</a> <a class="sublink-1" href="#sortedindex">sortedIndex</a> <a class="sublink-1" href="#symmetricdifference">symmetricDifference</a> <a class="sublink-1" href="#tail">tail</a> <a class="sublink-1" href="#take">take</a> <a class="sublink-1" href="#takeright">takeRight</a> <a class="sublink-1" href="#union">union</a> <a class="sublink-1" href="#without">without</a> <a class="sublink-1" href="#zip">zip</a> <a class="sublink-1" href="#zipobject">zipObject</a><h3>Browser</h3><a class="sublink-1" href="#arraytohtmllist">arrayToHtmlList</a> <a class="sublink-1" href="#bottomvisible">bottomVisible</a> <a class="sublink-1" href="#copytoclipboard">copyToClipboard</a> <a class="sublink-1" href="#currenturl">currentURL</a> <a class="sublink-1" href="#detectdevicetype">detectDeviceType</a> <a class="sublink-1" href="#elementisvisibleinviewport">elementIsVisibleInViewport</a> <a class="sublink-1" href="#getscrollposition">getScrollPosition</a> <a class="sublink-1" href="#getstyle">getStyle</a> <a class="sublink-1" href="#hasclass">hasClass</a> <a class="sublink-1" href="#hide">hide</a> <a class="sublink-1" href="#httpsredirect">httpsRedirect</a> <a class="sublink-1" href="#onuserinputchange">onUserInputChange</a> <a class="sublink-1" href="#redirect">redirect</a> <a class="sublink-1" href="#runasync">runAsync</a> <a class="sublink-1" href="#scrolltotop">scrollToTop</a> <a class="sublink-1" href="#setstyle">setStyle</a> <a class="sublink-1" href="#show">show</a> <a class="sublink-1" href="#speechsynthesis">speechSynthesis</a> <a class="sublink-1" href="#toggleclass">toggleClass</a> <a class="sublink-1" href="#uuidgeneratorbrowser">UUIDGeneratorBrowser</a><h3>Date</h3><a class="sublink-1" href="#getdaysdiffbetweendates">getDaysDiffBetweenDates</a> <a class="sublink-1" href="#jsontodate">JSONToDate</a> <a class="sublink-1" href="#toenglishdate">toEnglishDate</a> <a class="sublink-1" href="#tomorrow">tomorrow</a><h3>Function</h3><a class="sublink-1" href="#chainasync">chainAsync</a> <a class="sublink-1" href="#compose">compose</a> <a class="sublink-1" href="#curry">curry</a> <a class="sublink-1" href="#defer">defer</a> <a class="sublink-1" href="#functionname">functionName</a> <a class="sublink-1" href="#memoize">memoize</a> <a class="sublink-1" href="#once">once</a> <a class="sublink-1" href="#runpromisesinseries">runPromisesInSeries</a> <a class="sublink-1" href="#sleep">sleep</a><h3>Logic</h3><a class="sublink-1" href="#negate">negate</a><h3>Math</h3><a class="sublink-1" href="#average">average</a> <a class="sublink-1" href="#clampnumber">clampNumber</a> <a class="sublink-1" href="#collatz">collatz</a> <a class="sublink-1" href="#digitize">digitize</a> <a class="sublink-1" href="#distance">distance</a> <a class="sublink-1" href="#elo">elo</a> <a class="sublink-1" href="#factorial">factorial</a> <a class="sublink-1" href="#factors">factors</a> <a class="sublink-1" href="#fibonacci">fibonacci</a> <a class="sublink-1" href="#fibonaccicountuntilnum">fibonacciCountUntilNum</a> <a class="sublink-1" href="#fibonacciuntilnum">fibonacciUntilNum</a> <a class="sublink-1" href="#gcd">gcd</a> <a class="sublink-1" href="#geometricprogression">geometricProgression</a> <a class="sublink-1" href="#hammingdistance">hammingDistance</a> <a class="sublink-1" href="#howmanytimes">howManyTimes</a> <a class="sublink-1" href="#inrange">inRange</a> <a class="sublink-1" href="#isarmstrongnumber">isArmstrongNumber</a> <a class="sublink-1" href="#isdivisible">isDivisible</a> <a class="sublink-1" href="#iseven">isEven</a> <a class="sublink-1" href="#isprime">isPrime</a> <a class="sublink-1" href="#lcm">lcm</a> <a class="sublink-1" href="#median">median</a> <a class="sublink-1" href="#percentile">percentile</a> <a class="sublink-1" href="#powerset">powerset</a> <a class="sublink-1" href="#primes">primes</a> <a class="sublink-1" href="#randomintegerinrange">randomIntegerInRange</a> <a class="sublink-1" href="#randomnumberinrange">randomNumberInRange</a> <a class="sublink-1" href="#round">round</a> <a class="sublink-1" href="#solverpn">solveRPN</a> <a class="sublink-1" href="#standarddeviation">standardDeviation</a> <a class="sublink-1" href="#sum">sum</a> <a class="sublink-1" href="#sumpower">sumPower</a><h3>Node</h3><a class="sublink-1" href="#hasflags">hasFlags</a> <a class="sublink-1" href="#istravisci">isTravisCI</a> <a class="sublink-1" href="#jsontofile">JSONToFile</a> <a class="sublink-1" href="#readfilelines">readFileLines</a> <a class="sublink-1" href="#untildify">untildify</a> <a class="sublink-1" href="#uuidgeneratornode">UUIDGeneratorNode</a><h3>Object</h3><a class="sublink-1" href="#cleanobj">cleanObj</a> <a class="sublink-1" href="#invertkeyvalues">invertKeyValues</a> <a class="sublink-1" href="#lowercasekeys">lowercaseKeys</a> <a class="sublink-1" href="#objectfrompairs">objectFromPairs</a> <a class="sublink-1" href="#objecttopairs">objectToPairs</a> <a class="sublink-1" href="#orderby">orderBy</a> <a class="sublink-1" href="#select">select</a> <a class="sublink-1" href="#shallowclone">shallowClone</a> <a class="sublink-1" href="#size">size</a> <a class="sublink-1" href="#truthcheckcollection">truthCheckCollection</a><h3>String</h3><a class="sublink-1" href="#anagrams">anagrams</a> <a class="sublink-1" href="#bytesize">byteSize</a> <a class="sublink-1" href="#capitalize">capitalize</a> <a class="sublink-1" href="#capitalizeeveryword">capitalizeEveryWord</a> <a class="sublink-1" href="#countvowels">countVowels</a> <a class="sublink-1" href="#escapehtml">escapeHTML</a> <a class="sublink-1" href="#escaperegexp">escapeRegExp</a> <a class="sublink-1" href="#fromcamelcase">fromCamelCase</a> <a class="sublink-1" href="#isabsoluteurl">isAbsoluteURL</a> <a class="sublink-1" href="#mask">mask</a> <a class="sublink-1" href="#palindrome">palindrome</a> <a class="sublink-1" href="#pluralize">pluralize</a> <a class="sublink-1" href="#repeatstring">repeatString</a> <a class="sublink-1" href="#reversestring">reverseString</a> <a class="sublink-1" href="#sortcharactersinstring">sortCharactersInString</a> <a class="sublink-1" href="#splitlines">splitLines</a> <a class="sublink-1" href="#tocamelcase">toCamelCase</a> <a class="sublink-1" href="#tokebabcase">toKebabCase</a> <a class="sublink-1" href="#tosnakecase">toSnakeCase</a> <a class="sublink-1" href="#truncatestring">truncateString</a> <a class="sublink-1" href="#unescapehtml">unescapeHTML</a> <a class="sublink-1" href="#words">words</a><h3>Utility</h3><a class="sublink-1" href="#cloneregexp">cloneRegExp</a> <a class="sublink-1" href="#coalesce">coalesce</a> <a class="sublink-1" href="#coalescefactory">coalesceFactory</a> <a class="sublink-1" href="#extendhex">extendHex</a> <a class="sublink-1" href="#gettype">getType</a> <a class="sublink-1" href="#geturlparameters">getURLParameters</a> <a class="sublink-1" href="#hextorgb">hexToRGB</a> <a class="sublink-1" href="#isarray">isArray</a> <a class="sublink-1" href="#isarraylike">isArrayLike</a> <a class="sublink-1" href="#isboolean">isBoolean</a> <a class="sublink-1" href="#isfunction">isFunction</a> <a class="sublink-1" href="#isnull">isNull</a> <a class="sublink-1" href="#isnumber">isNumber</a> <a class="sublink-1" href="#isprimitive">isPrimitive</a> <a class="sublink-1" href="#ispromiselike">isPromiseLike</a> <a class="sublink-1" href="#isstring">isString</a> <a class="sublink-1" href="#issymbol">isSymbol</a> <a class="sublink-1" href="#isvalidjson">isValidJSON</a> <a class="sublink-1" href="#prettybytes">prettyBytes</a> <a class="sublink-1" href="#randomhexcolorcode">randomHexColorCode</a> <a class="sublink-1" href="#rgbtohex">RGBToHex</a> <a class="sublink-1" href="#sdbm">sdbm</a> <a class="sublink-1" href="#timetaken">timeTaken</a> <a class="sublink-1" href="#todecimalmark">toDecimalMark</a> <a class="sublink-1" href="#toordinalsuffix">toOrdinalSuffix</a> <a class="sublink-1" href="#validatenumber">validateNumber</a> <a class="sublink-1" href="#yesno">yesNo</a></nav><main class="col-sm-12 col-md-8 col-lg-9" style="height:100%;overflow-y:auto;background:#eceef2;padding:0"><a id="top"> </a><h2 style="text-align:center">Adapter</h2><div class="card fluid"><div class="section double-padded"><h3 id="call">call</h3></div><div class="section double-padded"><p>Given a key and a set of arguments, call them when given a context. Primarily useful in composition.</p><p>Use a closure to call a stored key with stored arguments.</p><pre><code class="language-js">const call = (key, ...args) => context => context[key](...args);
|
|
</code></pre><pre><code class="language-js">Promise.resolve([1, 2, 3])
|
|
.then(call('map', x => 2 * x))
|
|
.then(console.log); //[ 2, 4, 6 ]
|
|
const map = call.bind(null, 'map');
|
|
Promise.resolve([1, 2, 3])
|
|
.then(map(x => 2 * x))
|
|
.then(console.log); //[ 2, 4, 6 ]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="collectinto">collectInto</h3></div><div class="section double-padded"><p>Changes a function that accepts an array into a variadic function.</p><p>Given a function, return a closure that collects all inputs into an array-accepting function.</p><pre><code class="language-js">const collectInto = fn => (...args) => fn(args);
|
|
</code></pre><pre><code class="language-js">const Pall = collectInto(Promise.all.bind(Promise));
|
|
let p1 = Promise.resolve(1);
|
|
let p2 = Promise.resolve(2);
|
|
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
|
|
Pall(p1, p2, p3).then(console.log);
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flip">flip</h3></div><div class="section double-padded"><p>Flip takes a function as an argument, then makes the first argument the last</p><p>Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.</p><pre><code class="language-js">const flip = fn => (...args) => fn(args.pop(), ...args);
|
|
</code></pre><pre><code class="language-js">let a = { name: 'John Smith' };
|
|
let b = {};
|
|
const mergeFrom = flip(Object.assign);
|
|
let mergePerson = mergeFrom.bind(null, a);
|
|
mergePerson(b); // == b
|
|
b = {};
|
|
Object.assign(b, a); // == b
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="pipefunctions">pipeFunctions</h3></div><div class="section double-padded"><p>Performs left-to-right function composition.</p><p>Use <code>Array.reduce()</code> with the spread operator (<code>...</code>) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.</p><pre><code class="language-js">const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
|
|
</code></pre><pre><code class="language-js">const add5 = x => x + 5;
|
|
const multiply = (x, y) => x * y;
|
|
const multiplyAndAdd5 = pipeFunctions(multiply, add5);
|
|
multiplyAndAdd5(5, 2); // 15
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="promisify">promisify</h3></div><div class="section double-padded"><p>Converts an asynchronous function to return a promise.</p><p>Use currying to return a function returning a <code>Promise</code> that calls the original function. Use the <code>...rest</code> operator to pass in all the parameters.</p><p><em>In Node 8+, you can use <a href="https://nodejs.org/api/util.html#util_util_promisify_original"><code>util.promisify</code></a></em></p><pre><code class="language-js">const promisify = func => (...args) =>
|
|
new Promise((resolve, reject) =>
|
|
func(...args, (err, result) => (err ? reject(err) : resolve(result)))
|
|
);
|
|
</code></pre><pre><code class="language-js">const delay = promisify((d, cb) => setTimeout(cb, d));
|
|
delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="spreadover">spreadOver</h3></div><div class="section double-padded"><p>Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.</p><p>Use closures and the spread operator (<code>...</code>) to map the array of arguments to the inputs of the function.</p><pre><code class="language-js">const spreadOver = fn => argsArr => fn(...argsArr);
|
|
</code></pre><pre><code class="language-js">const arrayMax = spreadOver(Math.max);
|
|
arrayMax([1, 2, 3]); // 3
|
|
arrayMax([1, 2, 4]); // 4
|
|
</code></pre></div></div><br/><h2 style="text-align:center">Array</h2><div class="card fluid"><div class="section double-padded"><h3 id="chunk">chunk</h3></div><div class="section double-padded"><p>Chunks an array into smaller arrays of a specified size.</p><p>Use <code>Array.from()</code> to create a new array, that fits the number of chunks that will be produced. Use <code>Array.slice()</code> to map each element of the new array to a chunk the length of <code>size</code>. If the original array can't be split evenly, the final chunk will contain the remaining elements.</p><pre><code class="language-js">const chunk = (arr, size) =>
|
|
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
|
|
arr.slice(i * size, i * size + size)
|
|
);
|
|
</code></pre><pre><code class="language-js">chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="compact">compact</h3></div><div class="section double-padded"><p>Removes falsey values from an array.</p><p>Use <code>Array.filter()</code> to filter out falsey values (<code>false</code>, <code>null</code>, <code>0</code>, <code>""</code>, <code>undefined</code>, and <code>NaN</code>).</p><pre><code class="language-js">const compact = arr => arr.filter(Boolean);
|
|
</code></pre><pre><code class="language-js">compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="countoccurrences">countOccurrences</h3></div><div class="section double-padded"><p>Counts the occurrences of a value in an array.</p><p>Use <code>Array.reduce()</code> to increment a counter each time you encounter the specific value inside the array.</p><pre><code class="language-js">const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);
|
|
</code></pre><pre><code class="language-js">countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="deepflatten">deepFlatten</h3></div><div class="section double-padded"><p>Deep flattens an array.</p><p>Use recursion. Use <code>Array.concat()</code> with an empty array (<code>[]</code>) and the spread operator (<code>...</code>) to flatten an array. Recursively flatten each element that is an array.</p><pre><code class="language-js">const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
|
|
</code></pre><pre><code class="language-js">deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="difference">difference</h3></div><div class="section double-padded"><p>Returns the difference between two arrays.</p><p>Create a <code>Set</code> from <code>b</code>, then use <code>Array.filter()</code> on <code>a</code> to only keep values not contained in <code>b</code>.</p><pre><code class="language-js">const difference = (a, b) => {
|
|
const s = new Set(b);
|
|
return a.filter(x => !s.has(x));
|
|
};
|
|
</code></pre><pre><code class="language-js">difference([1, 2, 3], [1, 2, 4]); // [3]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="differencewith">differenceWith</h3></div><div class="section double-padded"><p>Filters out all values from an array for which the comparator function does not return <code>true</code>.</p><p>Use <code>Array.filter()</code> and <code>Array.find()</code> to find the appropriate values.</p><pre><code class="language-js">const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)));
|
|
</code></pre><pre><code class="language-js">differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a, b) => Math.round(a) == Math.round(b)); // [1, 1.2]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="distinctvaluesofarray">distinctValuesOfArray</h3></div><div class="section double-padded"><p>Returns all the distinct values of an array.</p><p>Use ES6 <code>Set</code> and the <code>...rest</code> operator to discard all duplicated values.</p><pre><code class="language-js">const distinctValuesOfArray = arr => [...new Set(arr)];
|
|
</code></pre><pre><code class="language-js">distinctValuesOfArray([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="dropelements">dropElements</h3></div><div class="section double-padded"><p>Removes elements in an array until the passed function returns <code>true</code>. Returns the remaining elements in the array.</p><p>Loop through the array, using <code>Array.slice()</code> to drop the first element of the array until the returned value from the function is <code>true</code>. Returns the remaining elements.</p><pre><code class="language-js">const dropElements = (arr, func) => {
|
|
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
|
|
return arr;
|
|
};
|
|
</code></pre><pre><code class="language-js">dropElements([1, 2, 3, 4], n => n >= 3); // [3,4]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="dropright">dropRight</h3></div><div class="section double-padded"><p>Returns a new array with <code>n</code> elements removed from the right.</p><p>Use <code>Array.slice()</code> to slice the remove the specified number of elements from the right.</p><pre><code class="language-js">const dropRight = (arr, n = 1) => arr.slice(0, -n);
|
|
</code></pre><pre><code class="language-js">dropRight([1, 2, 3]); // [1,2]
|
|
dropRight([1, 2, 3], 2); // [1]
|
|
dropRight([1, 2, 3], 42); // []
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="everynth">everyNth</h3></div><div class="section double-padded"><p>Returns every nth element in an array.</p><p>Use <code>Array.filter()</code> to create a new array that contains every nth element of a given array.</p><pre><code class="language-js">const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
|
|
</code></pre><pre><code class="language-js">everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="filternonunique">filterNonUnique</h3></div><div class="section double-padded"><p>Filters out the non-unique values in an array.</p><p>Use <code>Array.filter()</code> for an array containing only the unique values.</p><pre><code class="language-js">const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
|
|
</code></pre><pre><code class="language-js">filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flatten">flatten</h3></div><div class="section double-padded"><p>Flattens an array.</p><p>Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.</p><pre><code class="language-js">const flatten = arr => [].concat(...arr);
|
|
</code></pre><pre><code class="language-js">flatten([1, [2], 3, 4]); // [1,2,3,4]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flattendepth">flattenDepth</h3></div><div class="section double-padded"><p>Flattens an array up to the specified depth.</p><p>Use recursion, decrementing <code>depth</code> by 1 for each level of depth. Use <code>Array.reduce()</code> and <code>Array.concat()</code> to merge elements or arrays. Base case, for <code>depth</code> equal to <code>1</code> stops recursion. Omit the second element, <code>depth</code> to flatten only to a depth of <code>1</code> (single flatten).</p><pre><code class="language-js">const flattenDepth = (arr, depth = 1) =>
|
|
depth != 1
|
|
? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), [])
|
|
: arr.reduce((a, v) => a.concat(v), []);
|
|
</code></pre><pre><code class="language-js">flattenDepth([1, [2], 3, 4]); // [1,2,3,4]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="groupby">groupBy</h3></div><div class="section double-padded"><p>Groups the elements of an array based on the given function.</p><p>Use <code>Array.map()</code> to map the values of an array to a function or property name. Use <code>Array.reduce()</code> to create an object, where the keys are produced from the mapped results.</p><pre><code class="language-js">const groupBy = (arr, func) =>
|
|
arr.map(typeof func === 'function' ? func : val => val[func]).reduce((acc, val, i) => {
|
|
acc[val] = (acc[val] || []).concat(arr[i]);
|
|
return acc;
|
|
}, {});
|
|
</code></pre><pre><code class="language-js">groupBy([6.1, 4.2, 6.3], Math.floor); // {4: [4.2], 6: [6.1, 6.3]}
|
|
groupBy(['one', 'two', 'three'], 'length'); // {3: ['one', 'two'], 5: ['three']}
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="head">head</h3></div><div class="section double-padded"><p>Returns the head of a list.</p><p>Use <code>arr[0]</code> to return the first element of the passed array.</p><pre><code class="language-js">const head = arr => arr[0];
|
|
</code></pre><pre><code class="language-js">head([1, 2, 3]); // 1
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="initial">initial</h3></div><div class="section double-padded"><p>Returns all the elements of an array except the last one.</p><p>Use <code>arr.slice(0,-1)</code> to return all but the last element of the array.</p><pre><code class="language-js">const initial = arr => arr.slice(0, -1);
|
|
</code></pre><pre><code class="language-js">initial([1, 2, 3]); // [1,2]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="initialize2darray">initialize2DArray</h3></div><div class="section double-padded"><p>Initializes a 2D array of given width and height and value.</p><p>Use <code>Array.map()</code> to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to <code>null</code>.</p><pre><code class="language-js">const initialize2DArray = (w, h, val = null) =>
|
|
Array(h)
|
|
.fill()
|
|
.map(() => Array(w).fill(val));
|
|
</code></pre><pre><code class="language-js">initialize2DArray(2, 2, 0); // [[0,0], [0,0]]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="initializearraywithrange">initializeArrayWithRange</h3></div><div class="section double-padded"><p>Initializes an array containing the numbers in the specified range where <code>start</code> and <code>end</code> are inclusive with there common difference <code>step</code>.</p><p>Use <code>Array(Math.ceil((end+1-start)/step)</code> to create an array of the desired length(the amounts of elements is equal to <code>(end-start)/step</code> or <code>(end+1-start)/step</code> for inclusive end), <code>Array.map()</code> to fill with the desired values in a range. You can omit <code>start</code> to use a default value of <code>0</code>. You can omit <code>step</code> to use a default value of <code>1</code>.</p><pre><code class="language-js">const initializeArrayWithRange = (end, start = 0, step = 1) =>
|
|
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start);
|
|
</code></pre><pre><code class="language-js">initializeArrayWithRange(5); // [0,1,2,3,4,5]
|
|
initializeArrayWithRange(7, 3); // [3,4,5,6,7]
|
|
initializeArrayWithRange(9, 0, 2); //[0,2,4,6,8]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="initializearraywithvalues">initializeArrayWithValues</h3></div><div class="section double-padded"><p>Initializes and fills an array with the specified values.</p><p>Use <code>Array(n)</code> to create an array of the desired length, <code>fill(v)</code> to fill it with the desired values. You can omit <code>value</code> to use a default value of <code>0</code>.</p><pre><code class="language-js">const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
|
|
</code></pre><pre><code class="language-js">initializeArrayWithValues(5, 2); // [2,2,2,2,2]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="intersection">intersection</h3></div><div class="section double-padded"><p>Returns a list of elements that exist in both arrays.</p><p>Create a <code>Set</code> from <code>b</code>, then use <code>Array.filter()</code> on <code>a</code> to only keep values contained in <code>b</code>.</p><pre><code class="language-js">const intersection = (a, b) => {
|
|
const s = new Set(b);
|
|
return a.filter(x => s.has(x));
|
|
};
|
|
</code></pre><pre><code class="language-js">intersection([1, 2, 3], [4, 3, 2]); // [2,3]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="issorted">isSorted</h3></div><div class="section double-padded"><p>Returns <code>1</code> if the array is sorted in ascending order, <code>-1</code> if it is sorted in descending order or <code>0</code> if it is not sorted.</p><p>Calculate the ordering <code>direction</code> for the first two elements. Use <code>Object.entries()</code> to loop over array objects and compare them in pairs. Return <code>0</code> if the <code>direction</code> changes or the <code>direction</code> if the last element is reached.</p><pre><code class="language-js">const isSorted = arr => {
|
|
const direction = arr[0] > arr[1] ? -1 : 1;
|
|
for (let [i, val] of arr.entries())
|
|
if (i === arr.length - 1) return direction;
|
|
else if ((val - arr[i + 1]) * direction > 0) return 0;
|
|
};
|
|
</code></pre><pre><code class="language-js">isSorted([0, 1, 2, 3]); // 1
|
|
isSorted([0, 1, 2, 2]); // 1
|
|
isSorted([4, 3, 2]); // -1
|
|
isSorted([4, 3, 5]); // 0
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="join">join</h3></div><div class="section double-padded"><p>Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.</p><p>Use <code>Array.reduce()</code> to combine elements into a string. Omit the second argument, <code>separator</code>, to use a default separator of <code>','</code>. Omit the third argument, <code>end</code>, to use the same value as <code>separator</code> by default.</p><pre><code class="language-js">const join = (arr, separator = ',', end = separator) =>
|
|
arr.reduce(
|
|
(acc, val, i) =>
|
|
i == arr.length - 2
|
|
? acc + val + end
|
|
: i == arr.length - 1 ? acc + val : acc + val + separator,
|
|
''
|
|
);
|
|
</code></pre><pre><code class="language-js">join(); // ''
|
|
join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); //"pen,pineapple,apple&pen"
|
|
join(['pen', 'pineapple', 'apple', 'pen'], ','); //"pen,pineapple,apple,pen"
|
|
join(['pen', 'pineapple', 'apple', 'pen']); //"pen,pineapple,apple,pen"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="last">last</h3></div><div class="section double-padded"><p>Returns the last element in an array.</p><p>Use <code>arr.length - 1</code> to compute the index of the last element of the given array and returning it.</p><pre><code class="language-js">const last = arr => arr[arr.length - 1];
|
|
</code></pre><pre><code class="language-js">last([1, 2, 3]); // 3
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="mapobject">mapObject</h3></div><div class="section double-padded"><p>Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.</p><p>Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new <code>Array</code> to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).</p><pre><code class="language-js">const mapObject = (arr, fn) =>
|
|
(a => (
|
|
(a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
|
|
))();
|
|
</code></pre><pre><code class="language-js">const squareIt = arr => mapObject(arr, a => a * a);
|
|
squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="maxn">maxN</h3></div><div class="section double-padded"><p>Returns the <code>n</code> maximum elements from the provided array. If <code>n</code> is greater than or equal to the provided array's length, then return the original array(sorted in descending order).</p><p>Use <code>Array.sort()</code> combined with the spread operator (<code>...</code>) to create a shallow clone of the array and sort it in descending order. Use <code>Array.slice()</code> to get the specified number of elements. Omit the second argument, <code>n</code>, to get a one-element array.</p><pre><code class="language-js">const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
|
|
</code></pre><pre><code class="language-js">maxN([1, 2, 3]); // [3]
|
|
maxN([1, 2, 3], 2); // [3,2]
|
|
maxN([1, 2, 3], 4); // [3,2,1]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="minn">minN</h3></div><div class="section double-padded"><p>Returns the <code>n</code> minimum elements from the provided array. If <code>n</code> is greater than or equal to the provided array's length, then return the original array(sorted in ascending order).</p><p>Use <code>Array.sort()</code> combined with the spread operator (<code>...</code>) to create a shallow clone of the array and sort it in ascending order. Use <code>Array.slice()</code> to get the specified number of elements. Omit the second argument, <code>n</code>, to get a one-element array.</p><pre><code class="language-js">const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
|
|
</code></pre><pre><code class="language-js">minN([1, 2, 3]); // [1]
|
|
minN([1, 2, 3], 2); // [1,2]
|
|
minN([1, 2, 3], 4); // [1,2,3]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="nthelement">nthElement</h3></div><div class="section double-padded"><p>Returns the nth element of an array.</p><p>Use <code>Array.slice()</code> to get an array containing the nth element at the first place. If the index is out of bounds, return <code>[]</code>. Omit the second argument, <code>n</code>, to get the first element of the array.</p><pre><code class="language-js">const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
|
|
</code></pre><pre><code class="language-js">nthElement(['a', 'b', 'c'], 1); // 'b'
|
|
nthElement(['a', 'b', 'b'], -3); // 'a'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="pick">pick</h3></div><div class="section double-padded"><p>Picks the key-value pairs corresponding to the given keys from an object.</p><p>Use <code>Array.reduce()</code> to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.</p><pre><code class="language-js">const pick = (obj, arr) =>
|
|
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
|
|
</code></pre><pre><code class="language-js">pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="pull">pull</h3></div><div class="section double-padded"><p>Mutates the original array to filter out the values specified.</p><p>Use <code>Array.filter()</code> and <code>Array.includes()</code> to pull out the values that are not needed. Use <code>Array.length = 0</code> to mutate the passed in an array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values.</p><p><em>(For a snippet that does not mutate the original array see <a href="#without"><code>without</code></a>)</em></p><pre><code class="language-js">const pull = (arr, ...args) => {
|
|
let argState = Array.isArray(args[0]) ? args[0] : args;
|
|
let pulled = arr.filter((v, i) => !argState.includes(v));
|
|
arr.length = 0;
|
|
pulled.forEach(v => arr.push(v));
|
|
};
|
|
</code></pre><pre><code class="language-js">let myArray1 = ['a', 'b', 'c', 'a', 'b', 'c'];
|
|
pull(myArray1, 'a', 'c');
|
|
console.log(myArray1); // [ 'b', 'b' ]
|
|
|
|
let myArray2 = ['a', 'b', 'c', 'a', 'b', 'c'];
|
|
pull(myArray2, ['a', 'c']);
|
|
console.log(myArray2); // [ 'b', 'b' ]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="pullatindex">pullAtIndex</h3></div><div class="section double-padded"><p>Mutates the original array to filter out the values at the specified indexes.</p><p>Use <code>Array.filter()</code> and <code>Array.includes()</code> to pull out the values that are not needed. Use <code>Array.length = 0</code> to mutate the passed in an array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values. Use <code>Array.push()</code> to keep track of pulled values</p><pre><code class="language-js">const pullAtIndex = (arr, pullArr) => {
|
|
let removed = [];
|
|
let pulled = arr
|
|
.map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))
|
|
.filter((v, i) => !pullArr.includes(i));
|
|
arr.length = 0;
|
|
pulled.forEach(v => arr.push(v));
|
|
return removed;
|
|
};
|
|
</code></pre><pre><code class="language-js">let myArray = ['a', 'b', 'c', 'd'];
|
|
let pulled = pullAtIndex(myArray, [1, 3]);
|
|
|
|
console.log(myArray); // [ 'a', 'c' ]
|
|
console.log(pulled); // [ 'b', 'd' ]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="pullatvalue">pullAtValue</h3></div><div class="section double-padded"><p>Mutates the original array to filter out the values specified. Returns the removed elements.</p><p>Use <code>Array.filter()</code> and <code>Array.includes()</code> to pull out the values that are not needed. Use <code>Array.length = 0</code> to mutate the passed in an array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values. Use <code>Array.push()</code> to keep track of pulled values</p><pre><code class="language-js">const pullAtValue = (arr, pullArr) => {
|
|
let removed = [],
|
|
pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)),
|
|
mutateTo = arr.filter((v, i) => !pullArr.includes(v));
|
|
arr.length = 0;
|
|
mutateTo.forEach(v => arr.push(v));
|
|
return removed;
|
|
};
|
|
</code></pre><pre><code class="language-js">let myArray = ['a', 'b', 'c', 'd'];
|
|
let pulled = pullAtValue(myArray, ['b', 'd']);
|
|
console.log(myArray); // [ 'a', 'c' ]
|
|
console.log(pulled); // [ 'b', 'd' ]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="quicksort">quickSort</h3></div><div class="section double-padded"><p>QuickSort an Array (ascending sort by default).</p><p>Use recursion. Use <code>Array.filter</code> and spread operator (<code>...</code>) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. If the parameter <code>desc</code> is truthy, return array sorts in descending order.</p><pre><code class="language-js">const quickSort = ([n, ...nums], desc) =>
|
|
isNaN(n)
|
|
? []
|
|
: [
|
|
...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),
|
|
n,
|
|
...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
|
|
];
|
|
</code></pre><pre><code class="language-js">quickSort([4, 1, 3, 2]); // [1,2,3,4]
|
|
quickSort([4, 1, 3, 2], true); // [4,3,2,1]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="reducedfilter">reducedFilter</h3></div><div class="section double-padded"><p>Filter an array of objects based on a condition while also filtering out unspecified keys.</p><p>Use <code>Array.filter()</code> to filter the array based on the predicate <code>fn</code> so that it returns the objects for which the condition returned a truthy value. On the filtered array, use <code>Array.map()</code> to return the new object using <code>Array.reduce()</code> to filter out the keys which were not supplied as the <code>keys</code> argument.</p><pre><code class="language-js">const reducedFilter = (data, keys, fn) =>
|
|
data.filter(fn).map(el =>
|
|
keys.reduce((acc, key) => {
|
|
acc[key] = el[key];
|
|
return acc;
|
|
}, {})
|
|
);
|
|
</code></pre><pre><code class="language-js">const data = [
|
|
{
|
|
id: 1,
|
|
name: 'john',
|
|
age: 24
|
|
},
|
|
{
|
|
id: 2,
|
|
name: 'mike',
|
|
age: 50
|
|
}
|
|
];
|
|
|
|
reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="remove">remove</h3></div><div class="section double-padded"><p>Removes elements from an array for which the given function returns <code>false</code>.</p><p>Use <code>Array.filter()</code> to find array elements that return truthy values and <code>Array.reduce()</code> to remove elements using <code>Array.splice()</code>. The <code>func</code> is invoked with three arguments (<code>value, index, array</code>).</p><pre><code class="language-js">const remove = (arr, func) =>
|
|
Array.isArray(arr)
|
|
? arr.filter(func).reduce((acc, val) => {
|
|
arr.splice(arr.indexOf(val), 1);
|
|
return acc.concat(val);
|
|
}, [])
|
|
: [];
|
|
</code></pre><pre><code class="language-js">remove([1, 2, 3, 4], n => n % 2 == 0); // [2, 4]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sample">sample</h3></div><div class="section double-padded"><p>Returns a random element from an array.</p><p>Use <code>Math.random()</code> to generate a random number, multiply it by <code>length</code> and round it of to the nearest whole number using <code>Math.floor()</code>. This method also works with strings.</p><pre><code class="language-js">const sample = arr => arr[Math.floor(Math.random() * arr.length)];
|
|
</code></pre><pre><code class="language-js">sample([3, 7, 9, 11]); // 9
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="samplesize">sampleSize</h3></div><div class="section double-padded"><p>Gets <code>n</code> random elements at unique keys from <code>array</code> up to the size of <code>array</code>.</p><p>Shuffle the array using the <a href="https://github.com/chalarangelo/30-seconds-of-code#shuffle">Fisher-Yates algorithm</a>. Use <code>Array.slice()</code> to get the first <code>n</code> elements. Omit the second argument, <code>n</code> to get only one element at random from the array.</p><pre><code class="language-js">const sampleSize = ([...arr], n = 1) => {
|
|
let m = arr.length;
|
|
while (m) {
|
|
const i = Math.floor(Math.random() * m--);
|
|
[arr[m], arr[i]] = [arr[i], arr[m]];
|
|
}
|
|
return arr.slice(0, n);
|
|
};
|
|
</code></pre><pre><code class="language-js">sampleSize([1, 2, 3], 2); // [3,1]
|
|
sampleSize([1, 2, 3], 4); // [2,3,1]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="shuffle">shuffle</h3></div><div class="section double-padded"><p>Randomizes the order of the values of an array, returning a new array.</p><p>Uses the Fisher-Yates algorithm to reorder the elements of the array, based on the <a href="https://github.com/lodash/lodash/blob/b2ea6b1cd251796dcb5f9700c4911a7b6223920b/shuffle.js">Lodash implementation</a>, but as a pure function.</p><pre><code class="language-js">const shuffle = ([...arr]) => {
|
|
let m = arr.length;
|
|
while (m) {
|
|
const i = Math.floor(Math.random() * m--);
|
|
[arr[m], arr[i]] = [arr[i], arr[m]];
|
|
}
|
|
return arr;
|
|
};
|
|
</code></pre><pre><code class="language-js">const foo = [1, 2, 3];
|
|
shuffle(foo); // [2,3,1]
|
|
console.log(foo); // [1,2,3]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="similarity">similarity</h3></div><div class="section double-padded"><p>Returns an array of elements that appear in both arrays.</p><p>Use <code>filter()</code> to remove values that are not part of <code>values</code>, determined using <code>includes()</code>.</p><pre><code class="language-js">const similarity = (arr, values) => arr.filter(v => values.includes(v));
|
|
</code></pre><pre><code class="language-js">similarity([1, 2, 3], [1, 2, 4]); // [1,2]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sortedindex">sortedIndex</h3></div><div class="section double-padded"><p>Returns the lowest index at which value should be inserted into array in order to maintain its sort order.</p><p>Check if the array is sorted in descending order (loosely). Use <code>Array.findIndex()</code> to find the appropriate index where the element should be inserted.</p><pre><code class="language-js">const sortedIndex = (arr, n) => {
|
|
const isDescending = arr[0] > arr[arr.length - 1];
|
|
const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
|
|
return index === -1 ? arr.length : index;
|
|
};
|
|
</code></pre><pre><code class="language-js">sortedIndex([5, 3, 2, 1], 4); // 1
|
|
sortedIndex([30, 50], 40); // 1
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="symmetricdifference">symmetricDifference</h3></div><div class="section double-padded"><p>Returns the symmetric difference between two arrays.</p><p>Create a <code>Set</code> from each array, then use <code>Array.filter()</code> on each of them to only keep values not contained in the other.</p><pre><code class="language-js">const symmetricDifference = (a, b) => {
|
|
const sA = new Set(a),
|
|
sB = new Set(b);
|
|
return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
|
|
};
|
|
</code></pre><pre><code class="language-js">symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tail">tail</h3></div><div class="section double-padded"><p>Returns all elements in an array except for the first one.</p><p>Return <code>arr.slice(1)</code> if the array's <code>length</code> is more than <code>1</code>, otherwise, return the whole array.</p><pre><code class="language-js">const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
|
|
</code></pre><pre><code class="language-js">tail([1, 2, 3]); // [2,3]
|
|
tail([1]); // [1]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="take">take</h3></div><div class="section double-padded"><p>Returns an array with n elements removed from the beginning.</p><p>Use <code>Array.slice()</code> to create a slice of the array with <code>n</code> elements taken from the beginning.</p><pre><code class="language-js">const take = (arr, n = 1) => arr.slice(0, n);
|
|
</code></pre><pre><code class="language-js">take([1, 2, 3], 5); // [1, 2, 3]
|
|
take([1, 2, 3], 0); // []
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="takeright">takeRight</h3></div><div class="section double-padded"><p>Returns an array with n elements removed from the end.</p><p>Use <code>Array.slice()</code> to create a slice of the array with <code>n</code> elements taken from the end.</p><pre><code class="language-js">const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
|
|
</code></pre><pre><code class="language-js">takeRight([1, 2, 3], 2); // [ 2, 3 ]
|
|
takeRight([1, 2, 3]); // [3]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="union">union</h3></div><div class="section double-padded"><p>Returns every element that exists in any of the two arrays once.</p><p>Create a <code>Set</code> with all values of <code>a</code> and <code>b</code> and convert to an array.</p><pre><code class="language-js">const union = (a, b) => Array.from(new Set([...a, ...b]));
|
|
</code></pre><pre><code class="language-js">union([1, 2, 3], [4, 3, 2]); // [1,2,3,4]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="without">without</h3></div><div class="section double-padded"><p>Filters out the elements of an array, that have one of the specified values.</p><p>Use <code>Array.filter()</code> to create an array excluding(using <code>!Array.includes()</code>) all given values.</p><p><em>(For a snippet that mutates the original array see <a href="#pull"><code>pull</code></a>)</em></p><pre><code class="language-js">const without = (arr, ...args) => arr.filter(v => !args.includes(v));
|
|
</code></pre><pre><code class="language-js">without([2, 1, 2, 3], 1, 2); // [3]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="zip">zip</h3></div><div class="section double-padded"><p>Creates an array of elements, grouped based on the position in the original arrays.</p><p>Use <code>Math.max.apply()</code> to get the longest array in the arguments. Creates an array with that length as return value and use <code>Array.from()</code> with a map-function to create an array of grouped elements. If lengths of the argument-arrays vary, <code>undefined</code> is used where no value could be found.</p><pre><code class="language-js">const zip = (...arrays) => {
|
|
const maxLength = Math.max(...arrays.map(x => x.length));
|
|
return Array.from({ length: maxLength }).map((_, i) => {
|
|
return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);
|
|
});
|
|
};
|
|
</code></pre><pre><code class="language-js">zip(['a', 'b'], [1, 2], [true, false]); // [['a', 1, true], ['b', 2, false]]
|
|
zip(['a'], [1, 2], [true, false]); // [['a', 1, true], [undefined, 2, false]]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="zipobject">zipObject</h3></div><div class="section double-padded"><p>Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.</p><p>Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using <code>Array.reduce()</code>.</p><pre><code class="language-js">const zipObject = (props, values) =>
|
|
props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});
|
|
</code></pre><pre><code class="language-js">zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined}
|
|
zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}
|
|
</code></pre></div></div><br/><h2 style="text-align:center">Browser</h2><div class="card fluid"><div class="section double-padded"><h3 id="arraytohtmllist">arrayToHtmlList</h3></div><div class="section double-padded"><p>Converts the given array elements into <code><li></code> tags and appends them to the list of the given id.</p><p>Use <code>Array.map()</code> and <code>document.querySelector()</code> to create a list of html tags.</p><pre><code class="language-js">const arrayToHtmlList = (arr, listID) =>
|
|
arr.map(item => (document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`));
|
|
</code></pre><pre><code class="language-js">arrayToHtmlList(['item 1', 'item 2'], 'myListID');
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="bottomvisible">bottomVisible</h3></div><div class="section double-padded"><p>Returns <code>true</code> if the bottom of the page is visible, <code>false</code> otherwise.</p><p>Use <code>scrollY</code>, <code>scrollHeight</code> and <code>clientHeight</code> to determine if the bottom of the page is visible.</p><pre><code class="language-js">const bottomVisible = () =>
|
|
document.documentElement.clientHeight + window.scrollY >=
|
|
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
|
|
</code></pre><pre><code class="language-js">bottomVisible(); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="copytoclipboard">copyToClipboard</h3></div><div class="section double-padded"><p>Copy a string to the clipboard. Only works as a result of user action (i.e. inside a <code>click</code> event listener).</p><p>Create a new <code><textarea></code> element, fill it with the supplied data and add it to the HTML document. Use <code>Selection.getRangeAt()</code>to store the selected range (if any). Use <code>document.execCommand('copy')</code> to copy to the clipboard. Remove the <code><textarea></code> element from the HTML document. Finally, use <code>Selection().addRange()</code> to recover the original selected range (if any).</p><pre><code class="language-js">const copyToClipboard = str => {
|
|
const el = document.createElement('textarea');
|
|
el.value = str;
|
|
el.setAttribute('readonly', '');
|
|
el.style.position = 'absolute';
|
|
el.style.left = '-9999px';
|
|
document.body.appendChild(el);
|
|
const selected =
|
|
document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
|
|
el.select();
|
|
document.execCommand('copy');
|
|
document.body.removeChild(el);
|
|
if (selected) {
|
|
document.getSelection().removeAllRanges();
|
|
document.getSelection().addRange(selected);
|
|
}
|
|
};
|
|
</code></pre><pre><code class="language-js">copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="currenturl">currentURL</h3></div><div class="section double-padded"><p>Returns the current URL.</p><p>Use <code>window.location.href</code> to get current URL.</p><pre><code class="language-js">const currentURL = () => window.location.href;
|
|
</code></pre><pre><code class="language-js">currentURL(); // 'https://google.com'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="detectdevicetype">detectDeviceType</h3></div><div class="section double-padded"><p>Detects wether the website is being opened in a mobile device or a desktop/laptop.</p><p>Use a regular expression to test the <code>navigator.userAgent</code> property to figure out if the device is a mobile device or a desktop/laptop.</p><pre><code class="language-js">const detectDeviceType = () =>
|
|
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
|
|
? 'Mobile'
|
|
: 'Desktop';
|
|
</code></pre><pre><code class="language-js">detectDeviceType(); // "Mobile"
|
|
detectDeviceType(); // "Desktop"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="elementisvisibleinviewport">elementIsVisibleInViewport</h3></div><div class="section double-padded"><p>Returns <code>true</code> if the element specified is visible in the viewport, <code>false</code> otherwise.</p><p>Use <code>Element.getBoundingClientRect()</code> and the <code>window.inner(Width|Height)</code> values to determine if a given element is visible in the viewport. Omit the second argument to determine if the element is entirely visible, or specify <code>true</code> to determine if it is partially visible.</p><pre><code class="language-js">const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
|
|
const { top, left, bottom, right } = el.getBoundingClientRect();
|
|
const { innerHeight, innerWidth } = window;
|
|
return partiallyVisible
|
|
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
|
|
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
|
|
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
|
|
};
|
|
</code></pre><pre><code class="language-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)
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="getscrollposition">getScrollPosition</h3></div><div class="section double-padded"><p>Returns the scroll position of the current page.</p><p>Use <code>pageXOffset</code> and <code>pageYOffset</code> if they are defined, otherwise <code>scrollLeft</code> and <code>scrollTop</code>. You can omit <code>el</code> to use a default value of <code>window</code>.</p><pre><code class="language-js">const getScrollPosition = (el = window) => ({
|
|
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
|
|
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
|
|
});
|
|
</code></pre><pre><code class="language-js">getScrollPosition(); // {x: 0, y: 200}
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="getstyle">getStyle</h3></div><div class="section double-padded"><p>Returns the value of a CSS rule for the specified element.</p><p>Use <code>Window.getComputedStyle()</code> to get the value of the CSS rule for the specified element.</p><pre><code class="language-js">const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
|
|
</code></pre><pre><code class="language-js">getStyle(document.querySelector('p'), 'font-size'); // '16px'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="hasclass">hasClass</h3></div><div class="section double-padded"><p>Returns <code>true</code> if the element has the specified class, <code>false</code> otherwise.</p><p>Use <code>element.classList.contains()</code> to check if the element has the specified class.</p><pre><code class="language-js">const hasClass = (el, className) => el.classList.contains(className);
|
|
</code></pre><pre><code class="language-js">hasClass(document.querySelector('p.special'), 'special'); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="hide">hide</h3></div><div class="section double-padded"><p>Hides all the elements specified.</p><p>Use the spread operator (<code>...</code>) and <code>Array.forEach()</code> to apply <code>display: none</code> to each element specified.</p><pre><code class="language-js">const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
|
|
</code></pre><pre><code class="language-js">hide(document.querySelectorAll('img')); // Hides all <img> elements on the page
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="httpsredirect">httpsRedirect</h3></div><div class="section double-padded"><p>Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.</p><p>Use <code>location.protocol</code> to get the protocol currently being used. If it's not HTTPS, use <code>location.replace()</code> to replace the existing page with the HTTPS version of the page. Use <code>location.href</code> to get the full address, split it with <code>String.split()</code> and remove the protocol part of the URL.</p><pre><code class="language-js">const httpsRedirect = () => {
|
|
if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
|
|
};
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="onuserinputchange">onUserInputChange</h3></div><div class="section double-padded"><p>Run the callback whenever the user input type changes (<code>mouse</code> or <code>touch</code>). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops).</p><p>Use two event listeners. Assume <code>mouse</code> input initially and bind a <code>touchstart</code> event listener to the document. On <code>touchstart</code>, add a <code>mousemove</code> event listener to listen for two consecutive <code>mousemove</code> events firing within 20ms, using <code>performance.now()</code>. Run the callback with the input type as an argument in either of these situations.</p><pre><code class="language-js">const onUserInputChange = callback => {
|
|
let type = 'mouse',
|
|
lastTime = 0;
|
|
const mousemoveHandler = () => {
|
|
const now = performance.now();
|
|
if (now - lastTime < 20)
|
|
(type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler);
|
|
lastTime = now;
|
|
};
|
|
document.addEventListener('touchstart', () => {
|
|
if (type === 'touch') return;
|
|
(type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler);
|
|
});
|
|
};
|
|
</code></pre><pre><code class="language-js">onUserInputChange(type => {
|
|
console.log('The user is now using', type, 'as an input method.');
|
|
});
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="redirect">redirect</h3></div><div class="section double-padded"><p>Redirects to a specified URL.</p><p>Use <code>window.location.href</code> or <code>window.location.replace()</code> to redirect to <code>url</code>. Pass a second argument to simulate a link click (<code>true</code> - default) or an HTTP redirect (<code>false</code>).</p><pre><code class="language-js">const redirect = (url, asLink = true) =>
|
|
asLink ? (window.location.href = url) : window.location.replace(url);
|
|
</code></pre><pre><code class="language-js">redirect('https://google.com');
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="runasync">runAsync</h3></div><div class="section double-padded"><p>Runs a function in a separate thread by using a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Web Worker</a>, allowing long running functions to not block the UI.</p><p>Create a new <code>Worker</code> using a <code>Blob</code> object URL, the contents of which should be the stringified version of the supplied function. Immediately post the return value of calling the function back. Return a promise, listening for <code>onmessage</code> and <code>onerror</code> events and resolving the data posted back from the worker, or throwing an error.</p><pre><code class="language-js">const runAsync = fn => {
|
|
const blob = `
|
|
var fn = ${fn.toString()};
|
|
this.postMessage(fn());
|
|
`;
|
|
const worker = new Worker(
|
|
URL.createObjectURL(new Blob([blob]), {
|
|
type: 'application/javascript; charset=utf-8'
|
|
})
|
|
);
|
|
return new Promise((res, rej) => {
|
|
worker.onmessage = ({ data }) => {
|
|
res(data), worker.terminate();
|
|
};
|
|
worker.onerror = err => {
|
|
rej(err), worker.terminate();
|
|
};
|
|
});
|
|
};
|
|
</code></pre><pre><code class="language-js">const longRunningFunction = () => {
|
|
let result = 0;
|
|
for (var i = 0; i < 1000; i++) {
|
|
for (var j = 0; j < 700; j++) {
|
|
for (var k = 0; k < 300; k++) {
|
|
result = result + i + j + k;
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
};
|
|
|
|
// NOTE: Since the function is running in a different context, closures are not supported.
|
|
// The function supplied to `runAsync` gets stringified, so everything becomes literal.
|
|
// All variables and functions must be defined inside.
|
|
runAsync(longRunningFunction).then(console.log); // 209685000000
|
|
runAsync(() => 10 ** 3).then(console.log); // 1000
|
|
let outsideVariable = 50;
|
|
runAsync(() => typeof outsideVariable).then(console.log); // 'undefined'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="scrolltotop">scrollToTop</h3></div><div class="section double-padded"><p>Smooth-scrolls to the top of the page.</p><p>Get distance from top using <code>document.documentElement.scrollTop</code> or <code>document.body.scrollTop</code>. Scroll by a fraction of the distance from the top. Use <code>window.requestAnimationFrame()</code> to animate the scrolling.</p><pre><code class="language-js">const scrollToTop = () => {
|
|
const c = document.documentElement.scrollTop || document.body.scrollTop;
|
|
if (c > 0) {
|
|
window.requestAnimationFrame(scrollToTop);
|
|
window.scrollTo(0, c - c / 8);
|
|
}
|
|
};
|
|
</code></pre><pre><code class="language-js">scrollToTop();
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="setstyle">setStyle</h3></div><div class="section double-padded"><p>Sets the value of a CSS rule for the specified element.</p><p>Use <code>element.style</code> to set the value of the CSS rule for the specified element to <code>value</code>.</p><pre><code class="language-js">const setStyle = (el, ruleName, value) => (el.style[ruleName] = value);
|
|
</code></pre><pre><code class="language-js">setStyle(document.querySelector('p'), 'font-size', '20px'); // The first <p> element on the page will have a font-size of 20px
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="show">show</h3></div><div class="section double-padded"><p>Shows all the elements specified.</p><p>Use the spread operator (<code>...</code>) and <code>Array.forEach()</code> to clear the <code>display</code> property for each element specified.</p><pre><code class="language-js">const show = (...el) => [...el].forEach(e => (e.style.display = ''));
|
|
</code></pre><pre><code class="language-js">show(document.querySelectorAll('img')); // Shows all <img> elements on the page
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="speechsynthesis">speechSynthesis</h3></div><div class="section double-padded"><p>Performs speech synthesis (experimental).</p><p>Use <code>SpeechSynthesisUtterance.voice</code> and <code>window.speechSynthesis.getVoices()</code> to convert a message to speech. Use <code>window.speechSynthesis.speak()</code> to play the message.</p><p>Learn more about the <a href="https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance">SpeechSynthesisUtterance interface of the Web Speech API</a>.</p><pre><code class="language-js">const speechSynthesis = message => {
|
|
const msg = new SpeechSynthesisUtterance(message);
|
|
msg.voice = window.speechSynthesis.getVoices()[0];
|
|
window.speechSynthesis.speak(msg);
|
|
};
|
|
</code></pre><pre><code class="language-js">speechSynthesis('Hello, World'); // // plays the message
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="toggleclass">toggleClass</h3></div><div class="section double-padded"><p>Toggle a class for an element.</p><p>Use <code>element.classList.toggle()</code> to toggle the specified class for the element.</p><pre><code class="language-js">const toggleClass = (el, className) => el.classList.toggle(className);
|
|
</code></pre><pre><code class="language-js">toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="uuidgeneratorbrowser">UUIDGeneratorBrowser</h3></div><div class="section double-padded"><p>Generates a UUID in a browser.</p><p>Use <code>crypto</code> API to generate a UUID, compliant with <a href="https://www.ietf.org/rfc/rfc4122.txt">RFC4122</a> version 4.</p><pre><code class="language-js">const UUIDGeneratorBrowser = () =>
|
|
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
|
|
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
|
|
);
|
|
</code></pre><pre><code class="language-js">UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
|
|
</code></pre></div></div><br/><h2 style="text-align:center">Date</h2><div class="card fluid"><div class="section double-padded"><h3 id="getdaysdiffbetweendates">getDaysDiffBetweenDates</h3></div><div class="section double-padded"><p>Returns the difference (in days) between two dates.</p><p>Calculate the difference (in days) between two <code>Date</code> objects.</p><pre><code class="language-js">const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
|
|
(dateFinal - dateInitial) / (1000 * 3600 * 24);
|
|
</code></pre><pre><code class="language-js">getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="jsontodate">JSONToDate</h3></div><div class="section double-padded"><p>Converts a JSON object to a date.</p><p>Use <code>Date()</code>, to convert dates in JSON format to readable format (<code>dd/mm/yyyy</code>).</p><pre><code class="language-js">const JSONToDate = arr => {
|
|
const dt = new Date(parseInt(arr.toString().substr(6)));
|
|
return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
|
|
};
|
|
</code></pre><pre><code class="language-js">JSONToDate(/Date(1489525200000)/); // "14/3/2017"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="toenglishdate">toEnglishDate</h3></div><div class="section double-padded"><p>Converts a date from American format to English format.</p><p>Use <code>Date.toISOString()</code>, <code>split('T')</code> and <code>replace()</code> to convert a date from American format to the English format. Throws an error if the passed time cannot be converted to a date.</p><pre><code class="language-js">const toEnglishDate = time => {
|
|
try {
|
|
return new Date(time)
|
|
.toISOString()
|
|
.split('T')[0]
|
|
.replace(/-/g, '/');
|
|
} catch (e) {}
|
|
};
|
|
</code></pre><pre><code class="language-js">toEnglishDate('09/21/2010'); // '21/09/2010'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tomorrow">tomorrow</h3></div><div class="section double-padded"><p>Results in a string representation of tomorrow's date. Use <code>new Date()</code> to get today's date, adding <code>86400000</code> of seconds to it(24 hours), using <code>toISOString</code> to convert Date object to string.</p><pre><code class="language-js">const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0];
|
|
</code></pre><pre><code class="language-js">tomorrow(); // 2017-12-27 (if current date is 2017-12-26)
|
|
</code></pre></div></div><br/><h2 style="text-align:center">Function</h2><div class="card fluid"><div class="section double-padded"><h3 id="chainasync">chainAsync</h3></div><div class="section double-padded"><p>Chains asynchronous functions.</p><p>Loop through an array of functions containing asynchronous events, calling <code>next</code> when each asynchronous event has completed.</p><pre><code class="language-js">const chainAsync = fns => {
|
|
let curr = 0;
|
|
const next = () => fns[curr++](next);
|
|
next();
|
|
};
|
|
</code></pre><pre><code class="language-js">chainAsync([
|
|
next => {
|
|
console.log('0 seconds');
|
|
setTimeout(next, 1000);
|
|
},
|
|
next => {
|
|
console.log('1 second');
|
|
setTimeout(next, 1000);
|
|
},
|
|
next => {
|
|
console.log('2 seconds');
|
|
}
|
|
]);
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="compose">compose</h3></div><div class="section double-padded"><p>Performs right-to-left function composition.</p><p>Use <code>Array.reduce()</code> to perform right-to-left function composition. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.</p><pre><code class="language-js">const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
|
|
</code></pre><pre><code class="language-js">const add5 = x => x + 5;
|
|
const multiply = (x, y) => x * y;
|
|
const multiplyAndAdd5 = compose(add5, multiply);
|
|
multiplyAndAdd5(5, 2); // 15
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="curry">curry</h3></div><div class="section double-padded"><p>Curries a function.</p><p>Use recursion. If the number of provided arguments (<code>args</code>) is sufficient, call the passed function <code>fn</code>. Otherwise, return a curried function <code>fn</code> that expects the rest of the arguments. If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. <code>Math.min()</code>), you can optionally pass the number of arguments to the second parameter <code>arity</code>.</p><pre><code class="language-js">const curry = (fn, arity = fn.length, ...args) =>
|
|
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
|
|
</code></pre><pre><code class="language-js">curry(Math.pow)(2)(10); // 1024
|
|
curry(Math.min, 3)(10)(50)(2); // 2
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="defer">defer</h3></div><div class="section double-padded"><p>Defers invoking a function until the current call stack has cleared.</p><p>Use <code>setTimeout()</code> with a timeout of 1ms to add a new event to the browser event queue and allow the rendering engine to complete its work. Use the spread (<code>...</code>) operator to supply the function with an arbitrary number of arguments.</p><pre><code class="language-js">const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
|
|
</code></pre><pre><code class="language-js">// Example A:
|
|
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
|
|
|
|
// Example B:
|
|
document.querySelector('#someElement').innerHTML = 'Hello';
|
|
longRunningFunction(); // the browser will not update the HTML until this has finished
|
|
defer(longRunningFunction); // the browser will update the HTML then run the function
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="functionname">functionName</h3></div><div class="section double-padded"><p>Logs the name of a function.</p><p>Use <code>console.debug()</code> and the <code>name</code> property of the passed method to log the method's name to the <code>debug</code> channel of the console.</p><pre><code class="language-js">const functionName = fn => (console.debug(fn.name), fn);
|
|
</code></pre><pre><code class="language-js">functionName(Math.max); // max (logged in debug channel of console)
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="memoize">memoize</h3></div><div class="section double-padded"><p>Returns the memoized (cached) function.</p><p>Create an empty cache by instantiating a new <code>Map</code> object. Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. The <code>function</code> keyword must be used in order to allow the memoized function to have its <code>this</code> context changed if necessary. Allow access to the <code>cache</code> by setting it as a property on the returned function.</p><pre><code class="language-js">const memoize = fn => {
|
|
const cache = new Map();
|
|
const cached = function(val) {
|
|
return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
|
|
};
|
|
cached.cache = cache;
|
|
return cached;
|
|
};
|
|
</code></pre><pre><code class="language-js">// See the `anagrams` snippet.
|
|
const anagramsCached = memoize(anagrams);
|
|
anagramsCached('javascript'); // takes a long time
|
|
anagramsCached('javascript'); // returns virtually instantly since it's now cached
|
|
console.log(anagramsCached.cache); // Map
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="once">once</h3></div><div class="section double-padded"><p>Ensures a function is called only once.</p><p>Utilizing a closure, use a flag, <code>called</code>, and set it to <code>true</code> once the function is called for the first time, preventing it from being called again. In order to allow the function to have its <code>this</code> context changed (such as in an event listener), the <code>function</code> keyword must be used, and the supplied function must have the context applied. Allow the function to be supplied with an arbitrary number of arguments using the rest/spread (<code>...</code>) operator.</p><pre><code class="language-js">const once = fn => {
|
|
let called = false;
|
|
return function(...args) {
|
|
if (called) return;
|
|
called = true;
|
|
return fn.apply(this, args);
|
|
};
|
|
};
|
|
</code></pre><pre><code class="language-js">const startApp = function(event) {
|
|
console.log(this, event); // document.body, MouseEvent
|
|
};
|
|
document.body.addEventListener('click', once(startApp)); // only runs `startApp` once upon click
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="runpromisesinseries">runPromisesInSeries</h3></div><div class="section double-padded"><p>Runs an array of promises in series.</p><p>Use <code>Array.reduce()</code> to create a promise chain, where each promise returns the next promise when resolved.</p><pre><code class="language-js">const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
|
</code></pre><pre><code class="language-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
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sleep">sleep</h3></div><div class="section double-padded"><p>Delays the execution of an asynchronous function.</p><p>Delay executing part of an <code>async</code> function, by putting it to sleep, returning a <code>Promise</code>.</p><pre><code class="language-js">const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
</code></pre><pre><code class="language-js">async function sleepyWork() {
|
|
console.log("I'm going to sleep for 1 second.");
|
|
await sleep(1000);
|
|
console.log('I woke up after 1 second.');
|
|
}
|
|
</code></pre></div></div><br/><h2 style="text-align:center">Logic</h2><div class="card fluid"><div class="section double-padded"><h3 id="negate">negate</h3></div><div class="section double-padded"><p>Negates a predicate function.</p><p>Take a predicate function and apply <code>not</code> to it with its arguments.</p><pre><code class="language-js">const negate = func => (...args) => !func(...args);
|
|
</code></pre><pre><code class="language-js">filter([1, 2, 3, 4, 5, 6], negate(isEven)); // [1, 3, 5]
|
|
negate(isOdd)(1); // false
|
|
</code></pre></div></div><br/><h2 style="text-align:center">Math</h2><div class="card fluid"><div class="section double-padded"><h3 id="average">average</h3></div><div class="section double-padded"><p>Returns the average of an of two or more numbers/arrays.</p><p>Use <code>Array.reduce()</code> to add each value to an accumulator, initialized with a value of <code>0</code>, divide by the <code>length</code> of the array.</p><pre><code class="language-js">const average = (...arr) => {
|
|
const nums = [].concat(...arr);
|
|
return nums.reduce((acc, val) => acc + val, 0) / nums.length;
|
|
};
|
|
</code></pre><pre><code class="language-js">average([1, 2, 3]); // 2
|
|
average(1, 2, 3); // 2
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="clampnumber">clampNumber</h3></div><div class="section double-padded"><p>Clamps <code>num</code> within the inclusive range specified by the boundary values <code>a</code> and <code>b</code>.</p><p>If <code>num</code> falls within the range, return <code>num</code>. Otherwise, return the nearest number in the range.</p><pre><code class="language-js">const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
|
|
</code></pre><pre><code class="language-js">clampNumber(2, 3, 5); // 3
|
|
clampNumber(1, -1, -5); // -1
|
|
clampNumber(3, 2, 4); // 3
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="collatz">collatz</h3></div><div class="section double-padded"><p>Applies the Collatz algorithm.</p><p>If <code>n</code> is even, return <code>n/2</code>. Otherwise, return <code>3n+1</code>.</p><pre><code class="language-js">const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1);
|
|
</code></pre><pre><code class="language-js">collatz(8); // 4
|
|
collatz(5); // 16
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="digitize">digitize</h3></div><div class="section double-padded"><p>Converts a number to an array of digits.</p><p>Convert the number to a string, using spread operators in ES6(<code>[...string]</code>) build an array. Use <code>Array.map()</code> and <code>parseInt()</code> to transform each value to an integer.</p><pre><code class="language-js">const digitize = n => [...('' + n)].map(i => parseInt(i));
|
|
</code></pre><pre><code class="language-js">digitize(123); // [1, 2, 3]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="distance">distance</h3></div><div class="section double-padded"><p>Returns the distance between two points.</p><p>Use <code>Math.hypot()</code> to calculate the Euclidean distance between two points.</p><pre><code class="language-js">const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
|
|
</code></pre><pre><code class="language-js">distance(1, 1, 2, 3); // 2.23606797749979
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="elo">elo</h3></div><div class="section double-padded"><p>Computes the new ratings between two opponents using the <a href="https://en.wikipedia.org/wiki/Elo_rating_system">Elo rating system</a>. It takes an array of two pre-ratings and returns an array containing two post-ratings. The winner's rating is the first element of the array.</p><p>Use the exponent <code>**</code> operator and math operators to compute the expected score (chance of winning) of each opponent and compute the new rating for each. Omit the second argument to use the default K-factor of 32, or supply a custom K-factor value.</p><pre><code class="language-js">const elo = ([a, b], kFactor = 32) => {
|
|
const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));
|
|
const newRating = (rating, i) => rating + kFactor * (i - expectedScore(i ? a : b, i ? b : a));
|
|
return [newRating(a, 1), newRating(b, 0)];
|
|
};
|
|
</code></pre><pre><code class="language-js">elo([1200, 1200]); // [1216, 1184]
|
|
elo([1000, 2000]); // [1031.8991261061358, 1968.1008738938642]
|
|
elo([1500, 1000]); // [1501.7036868864648, 998.2963131135352]
|
|
elo([1200, 1200], 64); // [1232, 1168]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="factorial">factorial</h3></div><div class="section double-padded"><p>Calculates the factorial of a number.</p><p>Use recursion. If <code>n</code> is less than or equal to <code>1</code>, return <code>1</code>. Otherwise, return the product of <code>n</code> and the factorial of <code>n - 1</code>. Throws an exception if <code>n</code> is a negative number.</p><pre><code class="language-js">const factorial = n =>
|
|
n < 0
|
|
? (() => {
|
|
throw new TypeError('Negative numbers are not allowed!');
|
|
})()
|
|
: n <= 1 ? 1 : n * factorial(n - 1);
|
|
</code></pre><pre><code class="language-js">factorial(6); // 720
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="factors">factors</h3></div><div class="section double-padded"><p>Returns the array of factors of the given <code>num</code>. If the second argument is set to <code>true</code> returns only the prime factors of <code>num</code>. If <code>num</code> is <code>1</code> or <code>0</code> returns an empty array. If <code>num</code> is less than <code>0</code> returns all the factors of <code>-int</code> together with their additive inverses.</p><p>Use <code>Array.from()</code>, <code>Array.map()</code> and <code>Array.filter()</code> to find all the factors of <code>num</code>. If given <code>num</code> is negative, use <code>Array.reduce()</code> to add the additive inverses to the array. Return all results if <code>primes</code> is <code>false</code>, else determine and return only the prime factors using <code>isPrime</code> and <code>Array.filter()</code>. Omit the second argument, <code>primes</code>, to return prime and non-prime factors by default.</p><p><strong>Note</strong>:- <em>Negative numbers are not considered prime.</em></p><pre><code class="language-js">const factors = (num, primes = false) => {
|
|
const isPrime = num => {
|
|
const boundary = Math.floor(Math.sqrt(num));
|
|
for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
|
|
return num >= 2;
|
|
};
|
|
const isNeg = num < 0;
|
|
num = isNeg ? -num : num;
|
|
let array = Array.from({ length: num - 1 })
|
|
.map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
|
|
.filter(val => val);
|
|
if (isNeg)
|
|
array = array.reduce((acc, val) => {
|
|
acc.push(val);
|
|
acc.push(-val);
|
|
return acc;
|
|
}, []);
|
|
return primes ? array.filter(isPrime) : array;
|
|
};
|
|
</code></pre><pre><code class="language-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]
|
|
factors(-12, true); // [2,3]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="fibonacci">fibonacci</h3></div><div class="section double-padded"><p>Generates an array, containing the Fibonacci sequence, up until the nth term.</p><p>Create an empty array of the specific length, initializing the first two values (<code>0</code> and <code>1</code>). Use <code>Array.reduce()</code> to add values into the array, using the sum of the last two values, except for the first two.</p><pre><code class="language-js">const fibonacci = n =>
|
|
Array.from({ length: n }).reduce(
|
|
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
|
|
[]
|
|
);
|
|
</code></pre><pre><code class="language-js">fibonacci(6); // [0, 1, 1, 2, 3, 5]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="fibonaccicountuntilnum">fibonacciCountUntilNum</h3></div><div class="section double-padded"><p>Returns the number of fibonnacci numbers up to <code>num</code>(<code>0</code> and <code>num</code> inclusive).</p><p>Use a mathematical formula to calculate the number of fibonacci numbers until <code>num</code>.</p><pre><code class="language-js">const fibonacciCountUntilNum = num =>
|
|
Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
|
</code></pre><pre><code class="language-js">fibonacciCountUntilNum(10); // 7
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="fibonacciuntilnum">fibonacciUntilNum</h3></div><div class="section double-padded"><p>Generates an array, containing the Fibonacci sequence, up until the nth term.</p><p>Create an empty array of the specific length, initializing the first two values (<code>0</code> and <code>1</code>). Use <code>Array.reduce()</code> to add values into the array, using the sum of the last two values, except for the first two. Uses a mathematical formula to calculate the length of the array required.</p><pre><code class="language-js">const fibonacciUntilNum = num => {
|
|
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
|
return Array.from({ length: n }).reduce(
|
|
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
|
|
[]
|
|
);
|
|
};
|
|
</code></pre><pre><code class="language-js">fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="gcd">gcd</h3></div><div class="section double-padded"><p>Calculates the greatest common divisor between two or more numbers/arrays.</p><p>The <code>helperGcd</code>function uses recursion. Base case is when <code>y</code> equals <code>0</code>. In this case, return <code>x</code>. Otherwise, return the GCD of <code>y</code> and the remainder of the division <code>x/y</code>.</p><pre><code class="language-js">const gcd = (...arr) => {
|
|
let data = [].concat(...arr);
|
|
const helperGcd = (x, y) => (!y ? x : gcd(y, x % y));
|
|
return data.reduce((a, b) => helperGcd(a, b));
|
|
};
|
|
</code></pre><pre><code class="language-js">gcd(8, 36); // 4
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="geometricprogression">geometricProgression</h3></div><div class="section double-padded"><p>Initializes an array containing the numbers in the specified range where <code>start</code> and <code>end</code> are inclusive and the ratio between two terms is <code>step</code>. Returns an error if <code>step</code> equals <code>1</code>.</p><p>Use <code>Array.from()</code>, <code>Math.log()</code> and <code>Math.floor()</code> to create an array of the desired length, <code>Array.map()</code> to fill with the desired values in a range. Omit the second argument, <code>start</code>, to use a default value of <code>1</code>. Omit the third argument, <code>step</code>, to use a default value of <code>2</code>.</p><pre><code class="language-js">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
|
|
);
|
|
</code></pre><pre><code class="language-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]
|
|
geometricProgression(256, 2, 1); //Gives error
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="hammingdistance">hammingDistance</h3></div><div class="section double-padded"><p>Calculates the Hamming distance between two values.</p><p>Use XOR operator (<code>^</code>) to find the bit difference between the two numbers, convert to a binary string using <code>toString(2)</code>. Count and return the number of <code>1</code>s in the string, using <code>match(/1/g)</code>.</p><pre><code class="language-js">const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
|
|
</code></pre><pre><code class="language-js">hammingDistance(2, 3); // 1
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="howmanytimes">howManyTimes</h3></div><div class="section double-padded"><p>Returns the number of times <code>num</code> can be divided by <code>divisor</code> (integer or fractional) without getting a fractional answer. Works for both negative and positive integers.</p><p>If <code>divisor</code> is <code>-1</code> or <code>1</code> return <code>Infinity</code>. If <code>divisor</code> is <code>-0</code> or <code>0</code> return <code>0</code>. Otherwise, keep dividing <code>num</code> with <code>divisor</code> and incrementing <code>i</code>, while the result is an integer. Return the number of times the loop was executed, <code>i</code>.</p><pre><code class="language-js">const howManyTimes = (num, divisor) => {
|
|
if (divisor === 1 || divisor === -1) return Infinity;
|
|
if (divisor === 0) return 0;
|
|
let i = 0;
|
|
while (Number.isInteger(num / divisor)) {
|
|
i++;
|
|
num = num / divisor;
|
|
}
|
|
return i;
|
|
};
|
|
</code></pre><pre><code class="language-js">howManyTimes(100, 2); //2
|
|
howManyTimes(100, -2); //2
|
|
howManyTimes(100, 2.5); //2
|
|
howManyTimes(100, 3); //0
|
|
howManyTimes(100, 0); //0
|
|
howManyTimes(100, 1); //Infinity
|
|
howManyTimes(100, -1); //Infinity
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="inrange">inRange</h3></div><div class="section double-padded"><p>Checks if the given number falls within the given range.</p><p>Use arithmetic comparison to check if the given number is in the specified range. If the second parameter, <code>end</code>, is not specified, the range is considered to be from <code>0</code> to <code>start</code>.</p><pre><code class="language-js">const inRange = (n, start, end = null) => {
|
|
if (end && start > end) end = [start, (start = end)][0];
|
|
return end == null ? n >= 0 && n < start : n >= start && n < end;
|
|
};
|
|
</code></pre><pre><code class="language-js">inRange(3, 2, 5); // true
|
|
inRange(3, 4); // true
|
|
inRange(2, 3, 5); // false
|
|
inrange(3, 2); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isarmstrongnumber">isArmstrongNumber</h3></div><div class="section double-padded"><p>Checks if the given number is an Armstrong number or not.</p><p>Convert the given number into an array of digits. Use the exponent operator (<code>**</code>) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return <code>true</code> otherwise <code>false</code>.</p><pre><code class="language-js">const isArmstrongNumber = digits =>
|
|
(arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
|
|
(digits + '').split('')
|
|
);
|
|
</code></pre><pre><code class="language-js">isArmstrongNumber(1634); // true
|
|
isArmstrongNumber(371); // true
|
|
isArmstrongNumber(56); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isdivisible">isDivisible</h3></div><div class="section double-padded"><p>Checks if the first numeric argument is divisible by the second one.</p><p>Use the modulo operator (<code>%</code>) to check if the remainder is equal to <code>0</code>.</p><pre><code class="language-js">const isDivisible = (dividend, divisor) => dividend % divisor === 0;
|
|
</code></pre><pre><code class="language-js">isDivisible(6, 3); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="iseven">isEven</h3></div><div class="section double-padded"><p>Returns <code>true</code> if the given number is even, <code>false</code> otherwise.</p><p>Checks whether a number is odd or even using the modulo (<code>%</code>) operator. Returns <code>true</code> if the number is even, <code>false</code> if the number is odd.</p><pre><code class="language-js">const isEven = num => num % 2 === 0;
|
|
</code></pre><pre><code class="language-js">isEven(3); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isprime">isPrime</h3></div><div class="section double-padded"><p>Checks if the provided integer is a prime number.</p><p>Check numbers from <code>2</code> to the square root of the given number. Return <code>false</code> if any of them divides the given number, else return <code>true</code>, unless the number is less than <code>2</code>.</p><pre><code class="language-js">const isPrime = num => {
|
|
const boundary = Math.floor(Math.sqrt(num));
|
|
for (var i = 2; i <= boundary; i++) if (num % i == 0) return false;
|
|
return num >= 2;
|
|
};
|
|
</code></pre><pre><code class="language-js">isPrime(11); // true
|
|
isPrime(12); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="lcm">lcm</h3></div><div class="section double-padded"><p>Returns the least common multiple of two or more numbers/arrays.</p><p>Use the greatest common divisor (GCD) formula and <code>Math.abs()</code> to determine the least common multiple. The GCD formula uses recursion.</p><pre><code class="language-js">const lcm = (...arr) => {
|
|
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
|
|
const _lcm = (x, y) => x * y / gcd(x, y);
|
|
return [].concat(...arr).reduce((a, b) => _lcm(a, b));
|
|
};
|
|
</code></pre><pre><code class="language-js">lcm(12, 7); // 84
|
|
lcm([1, 3, 4], 5); // 60
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="median">median</h3></div><div class="section double-padded"><p>Returns the median of an array of numbers.</p><p>Find the middle of the array, use <code>Array.sort()</code> to sort the values. Return the number at the midpoint if <code>length</code> is odd, otherwise the average of the two middle numbers.</p><pre><code class="language-js">const median = arr => {
|
|
const mid = Math.floor(arr.length / 2),
|
|
nums = [...arr].sort((a, b) => a - b);
|
|
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
|
|
};
|
|
</code></pre><pre><code class="language-js">median([5, 6, 50, 1, -5]); // 5
|
|
median([0, 10, -2, 7]); // 3.5
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="percentile">percentile</h3></div><div class="section double-padded"><p>Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.</p><p>Use <code>Array.reduce()</code> to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.</p><pre><code class="language-js">const percentile = (arr, val) =>
|
|
100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;
|
|
</code></pre><pre><code class="language-js">percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="powerset">powerset</h3></div><div class="section double-padded"><p>Returns the powerset of a given array of numbers.</p><p>Use <code>Array.reduce()</code> combined with <code>Array.map()</code> to iterate over elements and combine into an array containing all combinations.</p><pre><code class="language-js">const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
|
|
</code></pre><pre><code class="language-js">powerset([1, 2]); // [[], [1], [2], [2,1]]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="primes">primes</h3></div><div class="section double-padded"><p>Generates primes up to a given number, using the Sieve of Eratosthenes.</p><p>Generate an array from <code>2</code> to the given number. Use <code>Array.filter()</code> to filter out the values divisible by any number from <code>2</code> to the square root of the provided number.</p><pre><code class="language-js">const primes = num => {
|
|
let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2),
|
|
sqroot = Math.floor(Math.sqrt(num)),
|
|
numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2);
|
|
numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y == x)));
|
|
return arr;
|
|
};
|
|
</code></pre><pre><code class="language-js">primes(10); // [2,3,5,7]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="randomintegerinrange">randomIntegerInRange</h3></div><div class="section double-padded"><p>Returns a random integer in the specified range.</p><p>Use <code>Math.random()</code> to generate a random number and map it to the desired range, using <code>Math.floor()</code> to make it an integer.</p><pre><code class="language-js">const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
|
|
</code></pre><pre><code class="language-js">randomIntegerInRange(0, 5); // 2
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="randomnumberinrange">randomNumberInRange</h3></div><div class="section double-padded"><p>Returns a random number in the specified range.</p><p>Use <code>Math.random()</code> to generate a random value, map it to the desired range using multiplication.</p><pre><code class="language-js">const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
|
|
</code></pre><pre><code class="language-js">randomNumberInRange(2, 10); // 6.0211363285087005
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="round">round</h3></div><div class="section double-padded"><p>Rounds a number to a specified amount of digits.</p><p>Use <code>Math.round()</code> and template literals to round the number to the specified number of digits. Omit the second argument, <code>decimals</code> to round to an integer.</p><pre><code class="language-js">const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
|
|
</code></pre><pre><code class="language-js">round(1.005, 2); // 1.01
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="solverpn">solveRPN</h3></div><div class="section double-padded"><p>Solves the given mathematical expression in <a href="https://en.wikipedia.org/wiki/Reverse_Polish_notation">reverse polish notation</a>. Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- <code>+</code>,<code>-</code>,<code>*</code>,<code>/</code>,<code>^</code>,<code>**</code> (<code>^</code>&<code>**</code> are the exponential symbols and are same). This snippet does not supports any unary operators.</p><p>Use a dictionary, <code>OPERATORS</code> to specify each operator's matching mathematical operation. Use <code>String.replace()</code> with a regular expression to replace <code>^</code> with <code>**</code>, <code>String.split()</code> to tokenize the string and <code>Array.filter()</code> to remove empty tokens. Use <code>Array.forEach()</code> to parse each <code>symbol</code>, evaluate it as a numeric value or operator and solve the mathematical expression. Numeric values are converted to floating point numbers and pushed to a <code>stack</code>, while operators are evaluated using the <code>OPERATORS</code> dictionary and pop elements from the <code>stack</code> to apply operations.</p><pre><code class="language-js">const solveRPN = rpn => {
|
|
const OPERATORS = {
|
|
'*': (a, b) => a * b,
|
|
'+': (a, b) => a + b,
|
|
'-': (a, b) => a - b,
|
|
'/': (a, b) => a / b,
|
|
'**': (a, b) => a ** b
|
|
};
|
|
const [stack, solve] = [
|
|
[],
|
|
rpn
|
|
.replace(/\^/g, '**')
|
|
.split(/\s+/g)
|
|
.filter(el => !/\s+/.test(el) && el !== '')
|
|
];
|
|
solve.forEach(symbol => {
|
|
if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {
|
|
stack.push(symbol);
|
|
} else if (Object.keys(OPERATORS).includes(symbol)) {
|
|
const [a, b] = [stack.pop(), stack.pop()];
|
|
stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));
|
|
} else {
|
|
throw `${symbol} is not a recognized symbol`;
|
|
}
|
|
});
|
|
if (stack.length === 1) return stack.pop();
|
|
else throw `${rpn} is not a proper RPN. Please check it and try again`;
|
|
};
|
|
</code></pre><pre><code class="language-js">solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
|
|
solveRPN('3 5 6 + *'); //33
|
|
solveRPN('2 4 / 5 6 - *'); //-0.5
|
|
solveRPN('2 3 ^'); //8
|
|
solveRPN('2 3 ^'); //8
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="standarddeviation">standardDeviation</h3></div><div class="section double-padded"><p>Returns the standard deviation of an array of numbers.</p><p>Use <code>Array.reduce()</code> to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then determine the standard deviation. You can omit the second argument to get the sample standard deviation or set it to <code>true</code> to get the population standard deviation.</p><pre><code class="language-js">const standardDeviation = (arr, usePopulation = false) => {
|
|
const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
|
return Math.sqrt(
|
|
arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) /
|
|
(arr.length - (usePopulation ? 0 : 1))
|
|
);
|
|
};
|
|
</code></pre><pre><code class="language-js">standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample)
|
|
standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population)
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sum">sum</h3></div><div class="section double-padded"><p>Returns the sum of two or more numbers/arrays.</p><p>Use <code>Array.reduce()</code> to add each value to an accumulator, initialized with a value of <code>0</code>.</p><pre><code class="language-js">const sum = (...arr) => [].concat(...arr).reduce((acc, val) => acc + val, 0);
|
|
</code></pre><pre><code class="language-js">sum([1, 2, 3, 4]); // 10
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sumpower">sumPower</h3></div><div class="section double-padded"><p>Returns the sum of the powers of all the numbers from <code>start</code> to <code>end</code> (both inclusive).</p><p>Use <code>Array.fill()</code> to create an array of all the numbers in the target range, <code>Array.map()</code> and the exponent operator (<code>**</code>) to raise them to <code>power</code> and <code>Array.reduce()</code> to add them together. Omit the second argument, <code>power</code>, to use a default power of <code>2</code>. Omit the third argument, <code>start</code>, to use a default starting value of <code>1</code>.</p><pre><code class="language-js">const sumPower = (end, power = 2, start = 1) =>
|
|
Array(end + 1 - start)
|
|
.fill(0)
|
|
.map((x, i) => (i + start) ** power)
|
|
.reduce((a, b) => a + b, 0);
|
|
</code></pre><pre><code class="language-js">sumPower(10); // 385
|
|
sumPower(10, 3); //3025
|
|
sumPower(10, 3, 5); //2925
|
|
</code></pre></div></div><br/><h2 style="text-align:center">Node</h2><div class="card fluid"><div class="section double-padded"><h3 id="hasflags">hasFlags</h3></div><div class="section double-padded"><p>Check if the current process's arguments contain the specified flags.</p><p>Use <code>Array.every()</code> and <code>Array.includes()</code> to check if <code>process.argv</code> contains all the specified flags. Use a regular expression to test if the specified flags are prefixed with <code>-</code> or <code>--</code> and prefix them accordingly.</p><pre><code class="language-js">const hasFlags = (...flags) =>
|
|
flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
|
|
</code></pre><pre><code class="language-js">// node myScript.js -s --test --cool=true
|
|
hasFlags('-s'); // true
|
|
hasFlags('test', 'cool=true'); // true
|
|
hasFlags('--test', 'cool=true', '-s'); // true
|
|
hasFlags('special'); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="istravisci">isTravisCI</h3></div><div class="section double-padded"><p>Checks if the current environment is <a href="https://travis-ci.org/">Travis CI</a>.</p><p>Checks if the current environment has the <code>TRAVIS</code> and <code>CI</code> environment variables (<a href="https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables">reference</a>).</p><pre><code class="language-js">const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
|
|
</code></pre><pre><code class="language-js">isTravisCI(); // true (if code is running on Travis CI)
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="jsontofile">JSONToFile</h3></div><div class="section double-padded"><p>Writes a JSON object to a file.</p><p>Use <code>fs.writeFile()</code>, template literals and <code>JSON.stringify()</code> to write a <code>json</code> object to a <code>.json</code> file.</p><pre><code class="language-js">const fs = require('fs');
|
|
const JSONToFile = (obj, filename) =>
|
|
fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
|
|
</code></pre><pre><code class="language-js">JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="readfilelines">readFileLines</h3></div><div class="section double-padded"><p>Returns an array of lines from the specified file.</p><p>Use <code>readFileSync</code> function in <code>fs</code> node package to create a <code>Buffer</code> from a file. convert buffer to string using <code>toString(encoding)</code> function. creating an array from contents of file by <code>split</code>ing file content line by line (each <code>\n</code>).</p><pre><code class="language-js">const fs = require('fs');
|
|
const readFileLines = filename =>
|
|
fs
|
|
.readFileSync(filename)
|
|
.toString('UTF8')
|
|
.split('\n');
|
|
</code></pre><pre><code class="language-js">/*
|
|
contents of test.txt :
|
|
line1
|
|
line2
|
|
line3
|
|
___________________________
|
|
*/
|
|
let arr = readFileLines('test.txt');
|
|
console.log(arr); // ['line1', 'line2', 'line3']
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="untildify">untildify</h3></div><div class="section double-padded"><p>Converts a tilde path to an absolute path.</p><p>Use <code>String.replace()</code> with a regular expression and <code>OS.homedir()</code> to replace the <code>~</code> in the start of the path with the home directory.</p><pre><code class="language-js">const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
|
|
</code></pre><pre><code class="language-js">untildify('~/node'); // '/Users/aUser/node'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="uuidgeneratornode">UUIDGeneratorNode</h3></div><div class="section double-padded"><p>Generates a UUID in Node.JS.</p><p>Use <code>crypto</code> API to generate a UUID, compliant with <a href="https://www.ietf.org/rfc/rfc4122.txt">RFC4122</a> version 4.</p><pre><code class="language-js">const crypto = require('crypto');
|
|
const UUIDGeneratorNode = () =>
|
|
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
|
|
(c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
|
|
);
|
|
</code></pre><pre><code class="language-js">UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'
|
|
</code></pre></div></div><br/><h2 style="text-align:center">Object</h2><div class="card fluid"><div class="section double-padded"><h3 id="cleanobj">cleanObj</h3></div><div class="section double-padded"><p>Removes any properties except the ones specified from a JSON object.</p><p>Use <code>Object.keys()</code> method to loop over given JSON object and deleting keys that are not <code>include</code>d in given array. Also if you give it a special key (<code>childIndicator</code>) it will search deeply inside it to apply function to inner objects too.</p><pre><code class="language-js">const cleanObj = (obj, keysToKeep = [], childIndicator) => {
|
|
Object.keys(obj).forEach(key => {
|
|
if (key === childIndicator) {
|
|
cleanObj(obj[key], keysToKeep, childIndicator);
|
|
} else if (!keysToKeep.includes(key)) {
|
|
delete obj[key];
|
|
}
|
|
});
|
|
return obj;
|
|
};
|
|
</code></pre><pre><code class="language-js">const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };
|
|
cleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="invertkeyvalues">invertKeyValues</h3></div><div class="section double-padded"><p>Inverts the key-value pairs of an object, without mutating it.</p><p>Use <code>Object.keys()</code> and <code>Array.reduce()</code> to invert the key-value pairs of an object.</p><pre><code class="language-js">const invertKeyValues = obj =>
|
|
Object.keys(obj).reduce((acc, key) => {
|
|
acc[obj[key]] = key;
|
|
return acc;
|
|
}, {});
|
|
</code></pre><pre><code class="language-js">invertKeyValues({ name: 'John', age: 20 }); // { 20: 'age', John: 'name' }
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="lowercasekeys">lowercaseKeys</h3></div><div class="section double-padded"><p>Creates a new object from the specified object, where all the keys are in lowercase.</p><p>Use <code>Object.keys()</code> and <code>Array.reduce()</code> to create a new object from the specified object. Convert each key in the original object to lowercase, using <code>String.toLowerCase()</code>.</p><pre><code class="language-js">const lowercaseKeys = obj =>
|
|
Object.keys(obj).reduce((acc, key) => {
|
|
acc[key.toLowerCase()] = obj[key];
|
|
return acc;
|
|
}, {});
|
|
</code></pre><pre><code class="language-js">const myObj = { Name: 'Adam', sUrnAME: 'Smith' };
|
|
const myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'};
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="objectfrompairs">objectFromPairs</h3></div><div class="section double-padded"><p>Creates an object from the given key-value pairs.</p><p>Use <code>Array.reduce()</code> to create and combine key-value pairs.</p><pre><code class="language-js">const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {});
|
|
</code></pre><pre><code class="language-js">objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="objecttopairs">objectToPairs</h3></div><div class="section double-padded"><p>Creates an array of key-value pair arrays from an object.</p><p>Use <code>Object.keys()</code> and <code>Array.map()</code> to iterate over the object's keys and produce an array with key-value pairs.</p><pre><code class="language-js">const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
|
|
</code></pre><pre><code class="language-js">objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]])
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="orderby">orderBy</h3></div><div class="section double-padded"><p>Returns a sorted array of objects ordered by properties and orders.</p><p>Uses a custom implementation of sort, that reduces the props array argument with a default value of 0, it uses destructuring to swap the properties position depending on the order passed. If no orders array is passed it sort by 'asc' by default.</p><pre><code class="language-js">const orderBy = (arr, props, orders) =>
|
|
[...arr].sort((a, b) =>
|
|
props.reduce((acc, prop, i) => {
|
|
if (acc === 0) {
|
|
const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]];
|
|
acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
|
|
}
|
|
return acc;
|
|
}, 0)
|
|
);
|
|
</code></pre><pre><code class="language-js">const users = [
|
|
{ name: 'fred', age: 48 },
|
|
{ name: 'barney', age: 36 },
|
|
{ name: 'fred', age: 40 },
|
|
{ name: 'barney', age: 34 }
|
|
];
|
|
orderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, {name: 'barney', age: 34}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
|
|
orderBy(users, ['name', 'age']); // [{name: 'barney', age: 34}, {name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="select">select</h3></div><div class="section double-padded"><p>Retrieve a property that indicated by the selector from an object.</p><p>If the property does not exists returns <code>undefined</code>.</p><pre><code class="language-js">const select = (from, selector) =>
|
|
selector.split('.').reduce((prev, cur) => prev && prev[cur], from);
|
|
</code></pre><pre><code class="language-js">const obj = { selector: { to: { val: 'val to select' } } };
|
|
select(obj, 'selector.to.val'); // 'val to select'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="shallowclone">shallowClone</h3></div><div class="section double-padded"><p>Creates a shallow clone of an object.</p><p>Use <code>Object.assign()</code> and an empty object (<code>{}</code>) to create a shallow clone of the original.</p><pre><code class="language-js">const shallowClone = obj => Object.assign({}, obj);
|
|
</code></pre><pre><code class="language-js">const a = { x: true, y: 1 };
|
|
const b = shallowClone(a);
|
|
a === b; // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="size">size</h3></div><div class="section double-padded"><p>Get size of arrays, objects or strings.</p><p>Get type of <code>value</code> (<code>array</code>, <code>object</code> or <code>string</code>). Use <code>length</code> property for arrays. Use <code>length</code> or <code>size</code> value if available or number of keys for objects. Use <code>size</code> of a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob"><code>Blob</code> object</a> created from <code>value</code> for strings.</p><p>Split strings into array of characters with <code>split('')</code> and return its length.</p><pre><code class="language-js">const size = value =>
|
|
Array.isArray(value)
|
|
? value.length
|
|
: value && typeof value === 'object'
|
|
? value.size || value.length || Object.keys(value).length
|
|
: typeof value === 'string' ? new Blob([value]).size : 0;
|
|
</code></pre><pre><code class="language-js">size([1, 2, 3, 4, 5]); // 5
|
|
size('size'); // 4
|
|
size({ one: 1, two: 2, three: 3 }); // 3
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="truthcheckcollection">truthCheckCollection</h3></div><div class="section double-padded"><p>Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).</p><p>Use <code>Array.every()</code> to check if each passed object has the specified property and if it returns a truthy value.</p><pre><code class="language-js">const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
|
|
</code></pre><pre><code class="language-js">truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true
|
|
</code></pre></div></div><br/><h2 style="text-align:center">String</h2><div class="card fluid"><div class="section double-padded"><h3 id="anagrams">anagrams</h3></div><div class="section double-padded"><p>⚠️ <strong>WARNING</strong>: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.</p><p>Generates all anagrams of a string (contains duplicates).</p><p>Use recursion. For each letter in the given string, create all the partial anagrams for the rest of its letters. Use <code>Array.map()</code> to combine the letter with each partial anagram, then <code>Array.reduce()</code> to combine all anagrams in one array. Base cases are for string <code>length</code> equal to <code>2</code> or <code>1</code>.</p><pre><code class="language-js">const anagrams = str => {
|
|
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
|
|
return str
|
|
.split('')
|
|
.reduce(
|
|
(acc, letter, i) =>
|
|
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),
|
|
[]
|
|
);
|
|
};
|
|
</code></pre><pre><code class="language-js">anagrams('abc'); // ['abc','acb','bac','bca','cab','cba']
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="bytesize">byteSize</h3></div><div class="section double-padded"><p>Returns the length of string.</p><p>Convert a given string to a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob"><code>Blob</code> Object</a> and find its <code>size</code>.</p><pre><code class="language-js">const byteSize = str => new Blob([str]).size;
|
|
</code></pre><pre><code class="language-js">byteSize('😀'); // 4
|
|
byteSize('Hello World'); // 11
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="capitalize">capitalize</h3></div><div class="section double-padded"><p>Capitalizes the first letter of a string.</p><p>Use destructuring and <code>toUpperCase()</code> to capitalize first letter, <code>...rest</code> to get array of characters after first letter and then <code>Array.join('')</code> to make it a string again. Omit the <code>lowerRest</code> parameter to keep the rest of the string intact, or set it to <code>true</code> to convert to lowercase.</p><pre><code class="language-js">const capitalize = ([first, ...rest], lowerRest = false) =>
|
|
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
|
|
</code></pre><pre><code class="language-js">capitalize('fooBar'); // 'FooBar'
|
|
capitalize('fooBar', true); // 'Foobar'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="capitalizeeveryword">capitalizeEveryWord</h3></div><div class="section double-padded"><p>Capitalizes the first letter of every word in a string.</p><p>Use <code>replace()</code> to match the first character of each word and <code>toUpperCase()</code> to capitalize it.</p><pre><code class="language-js">const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
|
</code></pre><pre><code class="language-js">capitalizeEveryWord('hello world!'); // 'Hello World!'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="countvowels">countVowels</h3></div><div class="section double-padded"><p>Retuns <code>number</code> of vowels in provided string.</p><p>Use a regular expression to count the number of vowels <code>(A, E, I, O, U)</code> in a <code>string</code>.</p><pre><code class="language-js">const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
|
|
</code></pre><pre><code class="language-js">countVowels('foobar'); // 3
|
|
countVowels('gym'); // 0
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="escapehtml">escapeHTML</h3></div><div class="section double-padded"><p>Escapes a string for use in HTML.</p><p>Use <code>String.replace()</code> with a regex that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).</p><pre><code class="language-js">const escapeHTML = str =>
|
|
str.replace(
|
|
/[&<>'"]/g,
|
|
tag =>
|
|
({
|
|
'&': '&amp;',
|
|
'<': '&lt;',
|
|
'>': '&gt;',
|
|
"'": '&#39;',
|
|
'"': '&quot;'
|
|
}[tag] || tag)
|
|
);
|
|
</code></pre><pre><code class="language-js">escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="escaperegexp">escapeRegExp</h3></div><div class="section double-padded"><p>Escapes a string to use in a regular expression.</p><p>Use <code>replace()</code> to escape special characters.</p><pre><code class="language-js">const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
</code></pre><pre><code class="language-js">escapeRegExp('(test)'); // \\(test\\)
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="fromcamelcase">fromCamelCase</h3></div><div class="section double-padded"><p>Converts a string from camelcase.</p><p>Use <code>replace()</code> to remove underscores, hyphens, and spaces and convert words to camelcase. Omit the second argument to use a default separator of <code>_</code>.</p><pre><code class="language-js">const fromCamelCase = (str, separator = '_') =>
|
|
str
|
|
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
|
|
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
|
|
.toLowerCase();
|
|
</code></pre><pre><code class="language-js">fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
|
|
fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'
|
|
fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isabsoluteurl">isAbsoluteURL</h3></div><div class="section double-padded"><p>Returns <code>true</code> if the given string is an absolute URL, <code>false</code> otherwise.</p><p>Use a regular expression to test if the string is an absolute URL.</p><pre><code class="language-js">const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
|
|
</code></pre><pre><code class="language-js">isAbsoluteURL('https://google.com'); // true
|
|
isAbsoluteURL('ftp://www.myserver.net'); // true
|
|
isAbsoluteURL('/foo/bar'); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="mask">mask</h3></div><div class="section double-padded"><p>Replaces all but the last <code>num</code> of characters with the specified mask character.</p><p>Use <code>String.slice()</code> to grab the portion of the characters that need to be masked and use <code>String.replace()</code> with a regex to replace every character with the mask character. Concatenate the masked characters with the remaining unmasked portion of the string. Omit the second argument, <code>num</code>, to keep a default of <code>4</code> characters unmasked. If <code>num</code> is negative, the unmasked characters will be at the start of the string. Omit the third argument, <code>mask</code>, to use a default character of <code>'*'</code> for the mask.</p><pre><code class="language-js">const mask = (cc, num = 4, mask = '*') =>
|
|
('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num);
|
|
</code></pre><pre><code class="language-js">mask(1234567890); // '******7890'
|
|
mask(1234567890, 3); // '*******890'
|
|
mask(1234567890, 4, '$'); // '$$$$$$7890'
|
|
mask(1234567890, -4, '$'); // '1234$$$$$$'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="palindrome">palindrome</h3></div><div class="section double-padded"><p>Returns <code>true</code> if the given string is a palindrome, <code>false</code> otherwise.</p><p>Convert string <code>toLowerCase()</code> and use <code>replace()</code> to remove non-alphanumeric characters from it. Then, <code>split('')</code> into individual characters, <code>reverse()</code>, <code>join('')</code> and compare to the original, unreversed string, after converting it <code>tolowerCase()</code>.</p><pre><code class="language-js">const palindrome = str => {
|
|
const s = str.toLowerCase().replace(/[\W_]/g, '');
|
|
return (
|
|
s ===
|
|
s
|
|
.split('')
|
|
.reverse()
|
|
.join('')
|
|
);
|
|
};
|
|
</code></pre><pre><code class="language-js">palindrome('taco cat'); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h1>pluralize</h1><p>If <code>num</code> is greater than <code>1</code> returns the plural form of the given string, else return the singular form.</p><p>Check if <code>num</code> is greater than <code>0</code>. Throw an appropriate <code>Error</code> if not, return the appropriate string otherwise. Omit the third argument, <code>items</code>, to use a default plural form same as <code>item</code> suffixed with a single <code>'s'</code>.</p><pre><code class="language-js">const pluralize = (num, item, items = item + 's') =>
|
|
num <= 0
|
|
? (() => {
|
|
throw new Error(`'num' should be >= 1. Value povided was ${num}.`);
|
|
})()
|
|
: num === 1 ? item : items;
|
|
</code></pre><pre><code class="language-js">pluralize(1, 'apple', 'apples'); // 'apple'
|
|
pluralize(3, 'apple', 'apples'); // 'apples'
|
|
pluralize(2, 'apple'); // 'apples'
|
|
pluralize(0, 'apple', 'apples'); // Gives error
|
|
pluralize(-3, 'apple', 'apples'); // Gives error
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="repeatstring">repeatString</h3></div><div class="section double-padded"><p>Repeats a string n times using <code>String.repeat()</code></p><p>If no string is provided the default is <code>""</code> and the default number of times is 2.</p><pre><code class="language-js">const repeatString = (str = '', num = 2) => {
|
|
return num >= 0 ? str.repeat(num) : str;
|
|
};
|
|
</code></pre><pre><code class="language-js">repeatString('abc', 3); // 'abcabcabc'
|
|
repeatString('abc'); // 'abcabc'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="reversestring">reverseString</h3></div><div class="section double-padded"><p>Reverses a string.</p><p>Use <code>split('')</code> and <code>Array.reverse()</code> to reverse the order of the characters in the string. Combine characters to get a string using <code>join('')</code>.</p><pre><code class="language-js">const reverseString = str =>
|
|
str
|
|
.split('')
|
|
.reverse()
|
|
.join('');
|
|
</code></pre><pre><code class="language-js">reverseString('foobar'); // 'raboof'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sortcharactersinstring">sortCharactersInString</h3></div><div class="section double-padded"><p>Alphabetically sorts the characters in a string.</p><p>Split the string using <code>split('')</code>, <code>Array.sort()</code> utilizing <code>localeCompare()</code>, recombine using <code>join('')</code>.</p><pre><code class="language-js">const sortCharactersInString = str =>
|
|
str
|
|
.split('')
|
|
.sort((a, b) => a.localeCompare(b))
|
|
.join('');
|
|
</code></pre><pre><code class="language-js">sortCharactersInString('cabbage'); // 'aabbceg'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="splitlines">splitLines</h3></div><div class="section double-padded"><p>Splits a multiline string into an array of lines.</p><p>Use <code>String.split()</code> and a regular expression to match line breaks and create an array.</p><pre><code class="language-js">const splitLines = str => str.split(/\r?\n/);
|
|
</code></pre><pre><code class="language-js">splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string' , '']
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tocamelcase">toCamelCase</h3></div><div class="section double-padded"><p>Converts a string to camelcase.</p><p>Break the string into words and combine them capitalizing the first letter of each word. For more detailed explanation of this Regex, <a href="https://regex101.com/r/bMCgAB/1">visit this Site</a>.</p><pre><code class="language-js">const toCamelCase = str => {
|
|
let s =
|
|
str &&
|
|
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.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
|
|
.join('');
|
|
return s.slice(0, 1).toLowerCase() + s.slice(1);
|
|
};
|
|
</code></pre><pre><code class="language-js">toCamelCase('some_database_field_name'); // 'someDatabaseFieldName'
|
|
toCamelCase('Some label that needs to be camelized'); // 'someLabelThatNeedsToBeCamelized'
|
|
toCamelCase('some-javascript-property'); // 'someJavascriptProperty'
|
|
toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMixedStringWithSpacesUnderscoresAndHyphens'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tokebabcase">toKebabCase</h3></div><div class="section double-padded"><p>Converts a string to kebab case.</p><p>Break the string into words and combine them using <code>-</code> as a separator. For more detailed explanation of this Regex, <a href="https://regex101.com/r/bMCgAB/1">visit this Site</a>.</p><pre><code class="language-js">const toKebabCase = str =>
|
|
str &&
|
|
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('-');
|
|
</code></pre><pre><code class="language-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'
|
|
toKebabCase('AllThe-small Things'); // "all-the-small-things"
|
|
toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tosnakecase">toSnakeCase</h3></div><div class="section double-padded"><p>Converts a string to snake case.</p><p>Break the string into words and combine them using <code>_</code> as a separator. For more detailed explanation of this Regex, <a href="https://regex101.com/r/bMCgAB/1">visit this Site</a>.</p><pre><code class="language-js">const toSnakeCase = str =>
|
|
str &&
|
|
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('_');
|
|
</code></pre><pre><code class="language-js">toSnakeCase('camelCase'); // 'camel_case'
|
|
toSnakeCase('some text'); // 'some_text'
|
|
toSnakeCase('some-javascript-property'); // 'some_javascript_property'
|
|
toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens'
|
|
toSnakeCase('AllThe-small Things'); // "all_the_smal_things"
|
|
toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="truncatestring">truncateString</h3></div><div class="section double-padded"><p>Truncates a string up to a specified length.</p><p>Determine if the string's <code>length</code> is greater than <code>num</code>. Return the string truncated to the desired length, with <code>...</code> appended to the end or the original string.</p><pre><code class="language-js">const truncateString = (str, num) =>
|
|
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
|
|
</code></pre><pre><code class="language-js">truncateString('boomerang', 7); // 'boom...'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="unescapehtml">unescapeHTML</h3></div><div class="section double-padded"><p>Unescapes escaped HTML characters.</p><p>Use <code>String.replace()</code> with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).</p><pre><code class="language-js">const unescapeHTML = str =>
|
|
str.replace(
|
|
/&amp;|&lt;|&gt;|&#39;|&quot;/g,
|
|
tag =>
|
|
({
|
|
'&amp;': '&',
|
|
'&lt;': '<',
|
|
'&gt;': '>',
|
|
'&#39;': "'",
|
|
'&quot;': '"'
|
|
}[tag] || tag)
|
|
);
|
|
</code></pre><pre><code class="language-js">unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="words">words</h3></div><div class="section double-padded"><p>Converts a given string into an array of words.</p><p>Use <code>String.split()</code> with a supplied pattern (defaults to non-alpha as a regex) to convert to an array of strings. Use <code>Array.filter()</code> to remove any empty strings. Omit the second argument to use the default regex.</p><pre><code class="language-js">const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
|
|
</code></pre><pre><code class="language-js">words('I love javaScript!!'); // ["I", "love", "javaScript"]
|
|
words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]
|
|
</code></pre></div></div><br/><h2 style="text-align:center">Utility</h2><div class="card fluid"><div class="section double-padded"><h3 id="cloneregexp">cloneRegExp</h3></div><div class="section double-padded"><p>Clones a regular expression.</p><p>Use <code>new RegExp()</code>, <code>RegExp.source</code> and <code>RegExp.flags</code> to clone the given regular expression.</p><pre><code class="language-js">const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
|
|
</code></pre><pre><code class="language-js">const regExp = /lorem ipsum/gi;
|
|
const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="coalesce">coalesce</h3></div><div class="section double-padded"><p>Returns the first non-null/undefined argument.</p><p>Use <code>Array.find()</code> to return the first non <code>null</code>/<code>undefined</code> argument.</p><pre><code class="language-js">const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
|
|
</code></pre><pre><code class="language-js">coalesce(null, undefined, '', NaN, 'Waldo'); // ""
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="coalescefactory">coalesceFactory</h3></div><div class="section double-padded"><p>Returns a customized coalesce function that returns the first argument that returns <code>true</code> from the provided argument validation function.</p><p>Use <code>Array.find()</code> to return the first argument that returns <code>true</code> from the provided argument validation function.</p><pre><code class="language-js">const coalesceFactory = valid => (...args) => args.find(valid);
|
|
</code></pre><pre><code class="language-js">const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));
|
|
customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="extendhex">extendHex</h3></div><div class="section double-padded"><p>Extends a 3-digit color code to a 6-digit color code.</p><p>Use <code>Array.map()</code>, <code>split()</code> and <code>Array.join()</code> to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form. <code>String.slice()</code> is used to remove <code>#</code> from string start since it's added once.</p><pre><code class="language-js">const extendHex = shortHex =>
|
|
'#' +
|
|
shortHex
|
|
.slice(shortHex.startsWith('#') ? 1 : 0)
|
|
.split('')
|
|
.map(x => x + x)
|
|
.join('');
|
|
</code></pre><pre><code class="language-js">extendHex('#03f'); // '#0033ff'
|
|
extendHex('05a'); // '#0055aa'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="gettype">getType</h3></div><div class="section double-padded"><p>Returns the native type of a value.</p><p>Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null</p><pre><code class="language-js">const getType = v =>
|
|
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
|
|
</code></pre><pre><code class="language-js">getType(new Set([1, 2, 3])); // "set"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="geturlparameters">getURLParameters</h3></div><div class="section double-padded"><p>Returns an object containing the parameters of the current URL.</p><p>Use <code>match()</code> with an appropriate regular expression to get all key-value pairs, <code>Array.reduce()</code> to map and combine them into a single object. Pass <code>location.search</code> as the argument to apply to the current <code>url</code>.</p><pre><code class="language-js">const getURLParameters = url =>
|
|
url
|
|
.match(/([^?=&]+)(=([^&]*))/g)
|
|
.reduce((a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {});
|
|
</code></pre><pre><code class="language-js">getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="hextorgb">hexToRGB</h3></div><div class="section double-padded"><p>Converts a color code to a <code>rgb()</code> or <code>rgba()</code> string if alpha value is provided.</p><p>Use bitwise right-shift operator and mask bits with <code>&</code> (and) operator to convert a hexadecimal color code (with or without prefixed with <code>#</code>) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If an alpha value is provided alongside 6-digit hex, give <code>rgba()</code> string in return.</p><pre><code class="language-js">const hexToRGB = hex => {
|
|
let alpha = false,
|
|
h = hex.slice(hex.startsWith('#') ? 1 : 0);
|
|
if (h.length === 3) h = [...h].map(x => x + x).join('');
|
|
else if (h.length === 8) alpha = true;
|
|
h = parseInt(h, 16);
|
|
return (
|
|
'rgb' +
|
|
(alpha ? 'a' : '') +
|
|
'(' +
|
|
(h >>> (alpha ? 24 : 16)) +
|
|
', ' +
|
|
((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) +
|
|
', ' +
|
|
((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
|
|
(alpha ? `, ${h & 0x000000ff}` : '') +
|
|
')'
|
|
);
|
|
};
|
|
</code></pre><pre><code class="language-js">hexToRGB('#27ae60ff'); // 'rgba(39, 174, 96, 255)'
|
|
hexToRGB('27ae60'); // 'rgb(39, 174, 96)'
|
|
hexToRGB('#fff'); // 'rgb(255, 255, 255)'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isarray">isArray</h3></div><div class="section double-padded"><p>Checks if the given argument is an array.</p><p>Use <code>Array.isArray()</code> to check if a value is classified as an array.</p><pre><code class="language-js">const isArray = val => !!val && Array.isArray(val);
|
|
</code></pre><pre><code class="language-js">isArray(null); // false
|
|
isArray([1]); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isarraylike">isArrayLike</h3></div><div class="section double-padded"><p>Checks if the provided argument is array-like (i.e. is iterable).</p><p>Use the spread operator (<code>...</code>) to check if the provided argument is iterable inside a <code>try... catch</code> block and the comma operator (<code>,</code>) to return the appropriate value.</p><pre><code class="language-js">const isArrayLike = val => {
|
|
try {
|
|
return [...val], true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
};
|
|
</code></pre><pre><code class="language-js">isArrayLike(document.querySelectorAll('.className')); // true
|
|
isArrayLike('abc'); // true
|
|
isArrayLike(null); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isboolean">isBoolean</h3></div><div class="section double-padded"><p>Checks if the given argument is a native boolean element.</p><p>Use <code>typeof</code> to check if a value is classified as a boolean primitive.</p><pre><code class="language-js">const isBoolean = val => typeof val === 'boolean';
|
|
</code></pre><pre><code class="language-js">isBoolean(null); // false
|
|
isBoolean(false); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isfunction">isFunction</h3></div><div class="section double-padded"><p>Checks if the given argument is a function.</p><p>Use <code>typeof</code> to check if a value is classified as a function primitive.</p><pre><code class="language-js">const isFunction = val => val && typeof val === 'function';
|
|
</code></pre><pre><code class="language-js">isFunction('x'); // false
|
|
isFunction(x => x); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isnull">isNull</h3></div><div class="section double-padded"><p>Returns <code>true</code> if the specified value is <code>null</code>, <code>false</code> otherwise.</p><p>Use the strict equality operator to check if the value and of <code>val</code> are equal to <code>null</code>.</p><pre><code class="language-js">const isNull = val => val === null;
|
|
</code></pre><pre><code class="language-js">isNull(null); // true
|
|
isNull('null'); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isnumber">isNumber</h3></div><div class="section double-padded"><p>Checks if the given argument is a number.</p><p>Use <code>typeof</code> to check if a value is classified as a number primitive.</p><pre><code class="language-js">const isNumber = val => typeof val === 'number';
|
|
</code></pre><pre><code class="language-js">isNumber('1'); // false
|
|
isNumber(1); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isprimitive">isPrimitive</h3></div><div class="section double-padded"><p>Returns a boolean determining if the supplied value is primitive or not.</p><p>Use <code>Array.includes()</code> on an array of type strings which are not primitive, supplying the type using <code>typeof</code>. Since <code>typeof null</code> evaluates to <code>'object'</code>, it needs to be directly compared.</p><pre><code class="language-js">const isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null;
|
|
</code></pre><pre><code class="language-js">isPrimitive(window.someNonExistentProperty); // true
|
|
isPrimitive(null); // true
|
|
isPrimitive(50); // true
|
|
isPrimitive('Hello!'); // true
|
|
isPrimitive(false); // true
|
|
isPrimitive(Symbol()); // true
|
|
isPrimitive([]); // false
|
|
isPrimitive(new String('Hello!')); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="ispromiselike">isPromiseLike</h3></div><div class="section double-padded"><p>Returns <code>true</code> if an object looks like a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><code>Promise</code></a>, <code>false</code> otherwise.</p><p>Check if the object is not <code>null</code>, its <code>typeof</code> matches either <code>object</code> or <code>function</code> and if it has a <code>.then</code> property, which is also a <code>function</code>.</p><pre><code class="language-js">const isPromiseLike = obj =>
|
|
obj !== null &&
|
|
(typeof obj === 'object' || typeof obj === 'function') &&
|
|
typeof obj.then === 'function';
|
|
</code></pre><pre><code class="language-js">isPromiseLike({
|
|
then: function() {
|
|
return '';
|
|
}
|
|
}); // true
|
|
isPromiseLike(null); // false
|
|
isPromiseLike({}); // false
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isstring">isString</h3></div><div class="section double-padded"><p>Checks if the given argument is a string.</p><p>Use <code>typeof</code> to check if a value is classified as a string primitive.</p><pre><code class="language-js">const isString = val => typeof val === 'string';
|
|
</code></pre><pre><code class="language-js">isString(10); // false
|
|
isString('10'); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="issymbol">isSymbol</h3></div><div class="section double-padded"><p>Checks if the given argument is a symbol.</p><p>Use <code>typeof</code> to check if a value is classified as a symbol primitive.</p><pre><code class="language-js">const isSymbol = val => typeof val === 'symbol';
|
|
</code></pre><pre><code class="language-js">isSymbol('x'); // false
|
|
isSymbol(Symbol('x')); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isvalidjson">isValidJSON</h3></div><div class="section double-padded"><p>Checks if the provided argument is a valid JSON.</p><p>Use <code>JSON.parse()</code> and a <code>try... catch</code> block to check if the provided argument is a valid JSON.</p><pre><code class="language-js">const isValidJSON = obj => {
|
|
try {
|
|
JSON.parse(obj);
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
};
|
|
</code></pre><pre><code class="language-js">isValidJSON('{"name":"Adam","age":20}'); // true
|
|
isValidJSON('{"name":"Adam",age:"20"}'); // false
|
|
isValidJSON(null); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="prettybytes">prettyBytes</h3></div><div class="section double-padded"><p>Converts a number in bytes to a human-readable string.</p><p>Use an array dictionary of units to be accessed based on the exponent. Use <code>Number.toPrecision()</code> to truncate the number to a certain number of digits. Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not. Omit the second argument, <code>precision</code>, to use a default precision of <code>3</code> digits. Omit the third argument, <code>addSpace</code>, to add space between the number and unit by default.</p><pre><code class="language-js">const prettyBytes = (num, precision = 3, addSpace = true) => {
|
|
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
|
if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
|
|
const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);
|
|
const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));
|
|
return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
|
|
};
|
|
</code></pre><pre><code class="language-js">prettyBytes(1000); // 1 KB
|
|
prettyBytes(123456789); // 123 MB
|
|
prettyBytes(-50); // -50 B
|
|
prettyBytes(27145424323.5821); // 27.1 GB
|
|
prettyBytes(27145424323.5821, 5); // 27.145 GB
|
|
prettyBytes(5500, 3, false); // 5.5KB
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="randomhexcolorcode">randomHexColorCode</h3></div><div class="section double-padded"><p>Generates a random hexadecimal color code.</p><p>Use <code>Math.random</code> to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using <code>toString(16)</code>.</p><pre><code class="language-js">const randomHexColorCode = () => {
|
|
let n = ((Math.random() * 0xfffff) | 0).toString(16);
|
|
return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n);
|
|
};
|
|
</code></pre><pre><code class="language-js">randomHexColorCode(); // "#e34155"
|
|
randomHexColorCode(); // "#fd73a6"
|
|
randomHexColorCode(); // "#4144c6"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="rgbtohex">RGBToHex</h3></div><div class="section double-padded"><p>Converts the values of RGB components to a color code.</p><p>Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (<code><<</code>) and <code>toString(16)</code>, then <code>padStart(6,'0')</code> to get a 6-digit hexadecimal value.</p><pre><code class="language-js">const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
|
</code></pre><pre><code class="language-js">RGBToHex(255, 165, 1); // 'ffa501'
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sdbm">sbdm</h3></div><div class="section double-padded"><p>This algorithm is a simple hash-algorithm that hashes it input string <code>s</code> into a whole number.</p><p>Use <code>split('')</code> and <code>Array.reduce()</code> to create a hash of the input string, utilizing bit shifting.</p><pre><code class="language-js">const sdbm = str => {
|
|
let arr = str.split('');
|
|
return arr.reduce(
|
|
(hashCode, currentVal) =>
|
|
(hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode),
|
|
0
|
|
);
|
|
};
|
|
</code></pre><pre><code class="language-js">console.log(sdbm('name')); // -3521204949
|
|
console.log(sdbm('age')); // 808122783
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="timetaken">timeTaken</h3></div><div class="section double-padded"><p>Measures the time taken by a function to execute.</p><p>Use <code>console.time()</code> and <code>console.timeEnd()</code> to measure the difference between the start and end times to determine how long the callback took to execute.</p><pre><code class="language-js">const timeTaken = callback => {
|
|
console.time('timeTaken');
|
|
const r = callback();
|
|
console.timeEnd('timeTaken');
|
|
return r;
|
|
};
|
|
</code></pre><pre><code class="language-js">timeTaken(() => Math.pow(2, 10)); // 1024
|
|
// (logged): timeTaken: 0.02099609375ms
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="todecimalmark">toDecimalMark</h3></div><div class="section double-padded"><p>Use <code>toLocaleString()</code> to convert a float-point arithmetic to the <a href="https://en.wikipedia.org/wiki/Decimal_mark">Decimal mark</a> form. It makes a comma separated string from a number.</p><pre><code class="language-js">const toDecimalMark = num => num.toLocaleString('en-US');
|
|
</code></pre><pre><code class="language-js">toDecimalMark(12305030388.9087); // "12,305,030,388.9087"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="toordinalsuffix">toOrdinalSuffix</h3></div><div class="section double-padded"><p>Adds an ordinal suffix to a number.</p><p>Use the modulo operator (<code>%</code>) to find values of single and tens digits. Find which ordinal pattern digits match. If digit is found in teens pattern, use teens ordinal.</p><pre><code class="language-js">const toOrdinalSuffix = num => {
|
|
const int = parseInt(num),
|
|
digits = [int % 10, int % 100],
|
|
ordinals = ['st', 'nd', 'rd', 'th'],
|
|
oPattern = [1, 2, 3, 4],
|
|
tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
|
|
return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])
|
|
? int + ordinals[digits[0] - 1]
|
|
: int + ordinals[3];
|
|
};
|
|
</code></pre><pre><code class="language-js">toOrdinalSuffix('123'); // "123rd"
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="validatenumber">validateNumber</h3></div><div class="section double-padded"><p>Returns <code>true</code> if the given value is a number, <code>false</code> otherwise.</p><p>Use <code>!isNaN</code> in combination with <code>parseFloat()</code> to check if the argument is a number. Use <code>isFinite()</code> to check if the number is finite. Use <code>Number()</code> to check if the coercion holds.</p><pre><code class="language-js">const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
|
|
</code></pre><pre><code class="language-js">validateNumber('10'); // true
|
|
</code></pre></div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="yesno">yesNo</h3></div><div class="section double-padded"><p>Returns <code>true</code> if the string is <code>y</code>/<code>yes</code> or <code>false</code> if the string is <code>n</code>/<code>no</code>.</p><p>Use <code>RegExp.test()</code> to check if the string evaluates to <code>y/yes</code> or <code>n/no</code>. Omit the second argument, <code>def</code> to set the default answer as <code>no</code>.</p><pre><code class="language-js">const yesNo = (val, def = false) =>
|
|
/^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;
|
|
</code></pre><pre><code class="language-js">yesNo('Y'); // true
|
|
yesNo('yes'); // true
|
|
yesNo('No'); // false
|
|
yesNo('Foo', true); // true
|
|
</code></pre></div></div><br/><footer><p style="display:inline-block"><strong>30 seconds of code</strong> is licensed under the <a href="https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE">CC0-1.0</a> license.<br/>Icons made by <a href="https://www.flaticon.com/authors/smashicons">Smashicons</a> from <a href="https://www.flaticon.com/">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/">CC 3.0 BY</a>.<br/>Ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> is licensed by <a href="https://opensource.org/licenses/MIT">The MIT License</a><br/>Built with the <a href="https://minicss.org">mini.css framework</a>.</p><a href="#top"><span style="display:inline-block;float:right;padding-right:2em">Back to top</span></a></footer></main></div><script src="prism.js"></script></body></html> |