forked from Chalarangelo/30-seconds-of-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.html
310 lines (306 loc) · 110 KB
/
function.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<!DOCTYPE html><html lang="en"><head><link rel="stylesheet" href="./style.css"><title>Function - 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 ([email protected])"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#111"><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="https://30secondsofcode.org/logos/logo_512.png"><link rel="icon" type="image/png" href="./logos/logo_128.png"><link rel="manifest" href="manifest.json"><script>const search = (node) => {
if(node.value.toLowerCase().trim() === ''){
document.querySelector('nav').querySelectorAll('li > a').forEach(x => x.style.display = '');
document.querySelector('nav').querySelectorAll('h4:not(.static-link)').forEach(x => x.classList = 'collapse');
return;
}
let matchingTags = [];
Array.from(document.querySelector('nav').querySelectorAll('li')).forEach(x => {
let data = [x.textContent.toLowerCase(), ...x.querySelector('a').getAttribute('tags').split(',')].map(v => !!(v.indexOf(node.value.toLowerCase()) + 1));
if(data.includes(true)){
x.style.display = '';
matchingTags.push(x.querySelector('a').getAttribute('tags').split(',')[0]);
}
else x.style.display = 'none';
});
Array.from(document.querySelector('nav').querySelectorAll('h4:not(.static-link)')).forEach(x => {
x.classList = matchingTags.includes(x.textContent.toLowerCase()) ? 'collapse toggled' : 'collapse';
})
}
function scrollToTop(){
const c = document.querySelector('.card-container').scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
document.querySelector('.card-container').scrollTo(0, c - c / 4);
}
};
function scrollTo(element, to, id, duration) {
if (duration <= 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 40;
setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop === to) {
window.location.href = "#"+id;
return;
}
scrollTo(element, to, id, duration - 40);
}, 40);
};
function loader() {
registerClickListener();
if(window.innerWidth >= '768')
document.querySelector('nav').scrollTop = Array.from(document.querySelectorAll('h4')).filter(v => v.innerHTML === 'Function')[0].offsetTop;
else
document.querySelector('nav').scrollTop = Array.from(document.querySelectorAll('h4')).filter(v => v.innerHTML === 'Function')[0].offsetTop;
}
function registerClickListener() {
document.addEventListener('click', function (event) {
if ( event.target.classList.contains('collapse') ) {
event.target.classList = event.target.classList.contains('toggled') ? 'collapse' : 'collapse toggled';
}
else if (event.target.classList.contains('menu-button')) {
document.querySelector('nav').classList = event.target.classList.contains('toggled') ? '' : 'col-nav';
document.querySelector('[type="search"]').classList = event.target.classList.contains('toggled') ? '' : 'col-nav';
event.target.classList = event.target.classList.contains('toggled') ? 'menu-button' : 'menu-button toggled';
}
else if (!document.querySelector('nav').contains(event.target) && !document.querySelector('[type="search"]').contains(event.target) && window.innerWidth < '768') {
document.querySelector('nav').classList = '';
document.querySelector('[type="search"]').classList = '';
document.querySelector('.menu-button').classList = 'menu-button';
}
else if (event.target.classList.contains('social')){
if (event.target.classList.contains('fb')){
window.location = "https://www.facebook.com/30secondsofcode";
}
else if (event.target.classList.contains('instagram')) {
window.location = "https://www.instagram.com/30secondsofcode";
}
else if (event.target.classList.contains('twitter')) {
window.location = "https://twitter.com/30secondsofcode";
}
}
else if (event.target.classList.contains('copy-button')) {
const text = event.target.parentElement.parentElement.querySelector(':not(pre) + pre').textContent;
const textArea = document.createElement("textarea");
textArea.value = text.trim();
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
document.body.removeChild(textArea);
let tst = document.createElement('div');
tst.classList = 'toast';
tst.innerHTML = 'Snippet copied to clipboard!';
document.body.appendChild(tst);
setTimeout(function() {
tst.style.opacity = 0;
setTimeout(function() {
document.body.removeChild(tst);
},300);
},1700);
}
}, false);
}</script></head><body onload="loader()" class="card-page"><a href="https://github.com/30-seconds/30-seconds-of-code" class="github-corner" aria-label="View source on Github"><svg width="56" height="56" viewBox="0 0 250 250" style="fill:#009688;color:#fff;position:fixed;top:0;border:0;right:0;z-index:1000" 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><button class="menu-button"></button><header><h1 class="logo"><a href="./index"><img src="https://30secondsofcode.org/logos/logo_256.png" alt="logo"/><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></a></h1></header><div class="container card-container"><input class="search" type="search" id="searchInput" onkeyup="search(this)" placeholder="Search..." aria-label="Snippet search"><nav><h4 class="collapse">Adapter</h4><ul><li><a tags="adapter,function,intermediate" href="./adapter#ary">ary</a></li><li><a tags="adapter,function,intermediate" href="./adapter#call">call</a></li><li><a tags="adapter,function,array,intermediate" href="./adapter#collectinto">collectInto</a></li><li><a tags="adapter,function,intermediate" href="./adapter#flip">flip</a></li><li><a tags="adapter,function,intermediate" href="./adapter#over">over</a></li><li><a tags="adapter,function,intermediate" href="./adapter#overargs">overArgs</a></li><li><a tags="adapter,function,promise,intermediate" href="./adapter#pipeasyncfunctions">pipeAsyncFunctions</a></li><li><a tags="adapter,function,intermediate" href="./adapter#pipefunctions">pipeFunctions</a></li><li><a tags="adapter,function,promise,intermediate" href="./adapter#promisify">promisify</a></li><li><a tags="adapter,function,intermediate" href="./adapter#rearg">rearg</a></li><li><a tags="adapter,intermediate" href="./adapter#spreadover">spreadOver</a></li><li><a tags="adapter,function,intermediate" href="./adapter#unary">unary</a></li></ul><h4 class="collapse">Array</h4><ul><li><a tags="array,function,beginner" href="./index#all">all</a></li><li><a tags="array,function,beginner" href="./index#allequal">allEqual</a></li><li><a tags="array,function,beginner" href="./index#any">any</a></li><li><a tags="array,string,utility,intermediate" href="./index#arraytocsv">arrayToCSV</a></li><li><a tags="array,intermediate" href="./index#bifurcate">bifurcate</a></li><li><a tags="array,function,intermediate" href="./index#bifurcateby">bifurcateBy</a></li><li><a tags="array,intermediate" href="./index#chunk">chunk</a></li><li><a tags="array,beginner" href="./index#compact">compact</a></li><li><a tags="array,object,intermediate" href="./index#countby">countBy</a></li><li><a tags="array,intermediate" href="./index#countoccurrences">countOccurrences</a></li><li><a tags="array,recursion,intermediate" href="./index#deepflatten">deepFlatten</a></li><li><a tags="array,math,beginner" href="./index#difference">difference</a></li><li><a tags="array,function,intermediate" href="./index#differenceby">differenceBy</a></li><li><a tags="array,function,intermediate" href="./index#differencewith">differenceWith</a></li><li><a tags="array,beginner" href="./index#drop">drop</a></li><li><a tags="array,beginner" href="./index#dropright">dropRight</a></li><li><a tags="array,function,intermediate" href="./index#droprightwhile">dropRightWhile</a></li><li><a tags="array,function,intermediate" href="./index#dropwhile">dropWhile</a></li><li><a tags="array,beginner" href="./index#everynth">everyNth</a></li><li><a tags="array,beginner" href="./index#filterfalsy">filterFalsy</a></li><li><a tags="array,beginner" href="./index#filternonunique">filterNonUnique</a></li><li><a tags="array,function,intermediate" href="./index#filternonuniqueby">filterNonUniqueBy</a></li><li><a tags="array,beginner" href="./index#findlast">findLast</a></li><li><a tags="array,function,intermediate" href="./index#findlastindex">findLastIndex</a></li><li><a tags="array,intermediate" href="./index#flatten">flatten</a></li><li><a tags="array,function,intermediate" href="./index#foreachright">forEachRight</a></li><li><a tags="array,object,intermediate" href="./index#groupby">groupBy</a></li><li><a tags="array,beginner" href="./index#head">head</a></li><li><a tags="array,intermediate" href="./index#indexofall">indexOfAll</a></li><li><a tags="array,beginner" href="./index#initial">initial</a></li><li><a tags="array,intermediate" href="./index#initialize2darray">initialize2DArray</a></li><li><a tags="array,math,intermediate" href="./index#initializearraywithrange">initializeArrayWithRange</a></li><li><a tags="array,math,intermediate" href="./index#initializearraywithrangeright">initializeArrayWithRangeRight</a></li><li><a tags="array,math,intermediate" href="./index#initializearraywithvalues">initializeArrayWithValues</a></li><li><a tags="array,recursion,intermediate" href="./index#initializendarray">initializeNDArray</a></li><li><a tags="array,math,intermediate" href="./index#intersection">intersection</a></li><li><a tags="array,function,intermediate" href="./index#intersectionby">intersectionBy</a></li><li><a tags="array,function,intermediate" href="./index#intersectionwith">intersectionWith</a></li><li><a tags="array,intermediate" href="./index#issorted">isSorted</a></li><li><a tags="array,intermediate" href="./index#join">join</a></li><li><a tags="array,string,object,advanced" href="./index#jsontocsv">JSONtoCSV</a></li><li><a tags="array,beginner" href="./index#last">last</a></li><li><a tags="array,string,utility,intermediate" href="./index#longestitem">longestItem</a></li><li><a tags="array,object,advanced" href="./index#mapobject">mapObject</a></li><li><a tags="array,math,beginner" href="./index#maxn">maxN</a></li><li><a tags="array,math,beginner" href="./index#minn">minN</a></li><li><a tags="array,function,beginner" href="./index#none">none</a></li><li><a tags="array,beginner" href="./index#nthelement">nthElement</a></li><li><a tags="array,beginner" href="./index#offset">offset</a></li><li><a tags="array,object,function,intermediate" href="./index#partition">partition</a></li><li><a tags="array,recursion,advanced" href="./index#permutations">permutations</a></li><li><a tags="array,intermediate" href="./index#pull">pull</a></li><li><a tags="array,advanced" href="./index#pullatindex">pullAtIndex</a></li><li><a tags="array,advanced" href="./index#pullatvalue">pullAtValue</a></li><li><a tags="array,function,advanced" href="./index#pullby">pullBy</a></li><li><a tags="array,intermediate" href="./index#reducedfilter">reducedFilter</a></li><li><a tags="array,function,intermediate" href="./index#reducesuccessive">reduceSuccessive</a></li><li><a tags="array,function,intermediate" href="./index#reducewhich">reduceWhich</a></li><li><a tags="array,beginner" href="./index#reject">reject</a></li><li><a tags="array,intermediate" href="./index#remove">remove</a></li><li><a tags="array,random,beginner" href="./index#sample">sample</a></li><li><a tags="array,random,intermediate" href="./index#samplesize">sampleSize</a></li><li><a tags="array,intermediate" href="./index#shank">shank</a></li><li><a tags="array,random,intermediate" href="./index#shuffle">shuffle</a></li><li><a tags="array,math,beginner" href="./index#similarity">similarity</a></li><li><a tags="array,math,intermediate" href="./index#sortedindex">sortedIndex</a></li><li><a tags="array,math,function,intermediate" href="./index#sortedindexby">sortedIndexBy</a></li><li><a tags="array,math,intermediate" href="./index#sortedlastindex">sortedLastIndex</a></li><li><a tags="array,math,function,intermediate" href="./index#sortedlastindexby">sortedLastIndexBy</a></li><li><a tags="array,sort,advanced,intermediate" href="./index#stablesort">stableSort</a></li><li><a tags="array,math,intermediate" href="./index#symmetricdifference">symmetricDifference</a></li><li><a tags="array,function,intermediate" href="./index#symmetricdifferenceby">symmetricDifferenceBy</a></li><li><a tags="array,function,intermediate" href="./index#symmetricdifferencewith">symmetricDifferenceWith</a></li><li><a tags="array,beginner" href="./index#tail">tail</a></li><li><a tags="array,beginner" href="./index#take">take</a></li><li><a tags="array,intermediate" href="./index#takeright">takeRight</a></li><li><a tags="array,function,intermediate" href="./index#takerightwhile">takeRightWhile</a></li><li><a tags="array,function,intermediate" href="./index#takewhile">takeWhile</a></li><li><a tags="array,intermediate" href="./index#tohash">toHash</a></li><li><a tags="array,math,beginner" href="./index#union">union</a></li><li><a tags="array,function,intermediate" href="./index#unionby">unionBy</a></li><li><a tags="array,function,intermediate" href="./index#unionwith">unionWith</a></li><li><a tags="array,beginner" href="./index#uniqueelements">uniqueElements</a></li><li><a tags="array,function,intermediate" href="./index#uniqueelementsby">uniqueElementsBy</a></li><li><a tags="array,function,intermediate" href="./index#uniqueelementsbyright">uniqueElementsByRight</a></li><li><a tags="array,math,intermediate" href="./index#uniquesymmetricdifference">uniqueSymmetricDifference</a></li><li><a tags="array,intermediate" href="./index#unzip">unzip</a></li><li><a tags="array,function,advanced" href="./index#unzipwith">unzipWith</a></li><li><a tags="array,beginner" href="./index#without">without</a></li><li><a tags="array,math,intermediate" href="./index#xprod">xProd</a></li><li><a tags="array,intermediate" href="./index#zip">zip</a></li><li><a tags="array,object,intermediate" href="./index#zipobject">zipObject</a></li><li><a tags="array,function,advanced" href="./index#zipwith">zipWith</a></li></ul><h4 class="collapse">Browser</h4><ul><li><a tags="browser,array,intermediate" href="./browser#arraytohtmllist">arrayToHtmlList</a></li><li><a tags="browser,intermediate" href="./browser#bottomvisible">bottomVisible</a></li><li><a tags="browser,string,advanced" href="./browser#copytoclipboard">copyToClipboard</a></li><li><a tags="browser,advanced" href="./browser#counter">counter</a></li><li><a tags="browser,utility,beginner" href="./browser#createelement">createElement</a></li><li><a tags="browser,event,advanced" href="./browser#createeventhub">createEventHub</a></li><li><a tags="browser,url,beginner" href="./browser#currenturl">currentURL</a></li><li><a tags="browser,intermediate" href="./browser#detectdevicetype">detectDeviceType</a></li><li><a tags="browser,intermediate" href="./browser#elementcontains">elementContains</a></li><li><a tags="browser,advanced" href="./browser#elementisvisibleinviewport">elementIsVisibleInViewport</a></li><li><a tags="browser,beginner" href="./browser#getimages">getImages</a></li><li><a tags="browser,intermediate" href="./browser#getscrollposition">getScrollPosition</a></li><li><a tags="browser,css,beginner" href="./browser#getstyle">getStyle</a></li><li><a tags="browser,css,beginner" href="./browser#hasclass">hasClass</a></li><li><a tags="browser,utility,advanced,promise,advanced" href="./browser#hashbrowser">hashBrowser</a></li><li><a tags="browser,css,beginner" href="./browser#hide">hide</a></li><li><a tags="browser,url,intermediate" href="./browser#httpsredirect">httpsRedirect</a></li><li><a tags="browser,beginner" href="./browser#insertafter">insertAfter</a></li><li><a tags="browser,beginner" href="./browser#insertbefore">insertBefore</a></li><li><a tags="browser,beginner" href="./browser#isbrowsertabfocused">isBrowserTabFocused</a></li><li><a tags="browser,array,beginner" href="./browser#nodelisttoarray">nodeListToArray</a></li><li><a tags="browser,event,advanced" href="./browser#observemutations">observeMutations</a></li><li><a tags="browser,event,intermediate" href="./browser#off">off</a></li><li><a tags="browser,event,intermediate" href="./browser#on">on</a></li><li><a tags="browser,event,advanced" href="./browser#onuserinputchange">onUserInputChange</a></li><li><a tags="browser,utility,intermediate" href="./browser#prefix">prefix</a></li><li><a tags="browser,utility,intermediate" href="./browser#recordanimationframes">recordAnimationFrames</a></li><li><a tags="browser,url,beginner" href="./browser#redirect">redirect</a></li><li><a tags="browser,function,advanced,promise,url" href="./browser#runasync">runAsync</a></li><li><a tags="browser,intermediate" href="./browser#scrolltotop">scrollToTop</a></li><li><a tags="browser,beginner" href="./browser#setstyle">setStyle</a></li><li><a tags="browser,css,beginner" href="./browser#show">show</a></li><li><a tags="browser,css,intermediate" href="./browser#smoothscroll">smoothScroll</a></li><li><a tags="browser,beginner" href="./browser#toggleclass">toggleClass</a></li><li><a tags="browser,event,intermediate" href="./browser#triggerevent">triggerEvent</a></li><li><a tags="browser,utility,random,intermediate" href="./browser#uuidgeneratorbrowser">UUIDGeneratorBrowser</a></li></ul><h4 class="collapse">Date</h4><ul><li><a tags="date,beginner" href="./date#dayofyear">dayOfYear</a></li><li><a tags="date,math,string,utility,intermediate" href="./date#formatduration">formatDuration</a></li><li><a tags="date,intermediate" href="./date#getcolontimefromdate">getColonTimeFromDate</a></li><li><a tags="date,intermediate" href="./date#getdaysdiffbetweendates">getDaysDiffBetweenDates</a></li><li><a tags="date,beginner" href="./date#getmeridiemsuffixofinteger">getMeridiemSuffixOfInteger</a></li><li><a tags="date,utility,beginner" href="./date#isafterdate">isAfterDate</a></li><li><a tags="date,utility,beginner" href="./date#isbeforedate">isBeforeDate</a></li><li><a tags="date,utility,beginner" href="./date#issamedate">isSameDate</a></li><li><a tags="date,math,beginner" href="./date#maxdate">maxDate</a></li><li><a tags="date,math,beginner" href="./date#mindate">minDate</a></li><li><a tags="date,intermediate" href="./date#tomorrow">tomorrow</a></li></ul><h4 class="collapse">Function</h4><ul><li><a tags="function,intermediate" href="#attempt">attempt</a></li><li><a tags="function,object,intermediate" href="#bind">bind</a></li><li><a tags="function,object,intermediate" href="#bindkey">bindKey</a></li><li><a tags="function,intermediate" href="#chainasync">chainAsync</a></li><li><a tags="function,intermediate" href="#compose">compose</a></li><li><a tags="function,intermediate" href="#composeright">composeRight</a></li><li><a tags="function,intermediate" href="#converge">converge</a></li><li><a tags="function,recursion,intermediate" href="#curry">curry</a></li><li><a tags="function,intermediate" href="#debounce">debounce</a></li><li><a tags="function,intermediate" href="#defer">defer</a></li><li><a tags="function,intermediate" href="#delay">delay</a></li><li><a tags="function,utility,beginner" href="#functionname">functionName</a></li><li><a tags="function,intermediate" href="#hz">hz</a></li><li><a tags="function,advanced" href="#memoize">memoize</a></li><li><a tags="function,beginner" href="#negate">negate</a></li><li><a tags="function,intermediate" href="#once">once</a></li><li><a tags="function,intermediate" href="#partial">partial</a></li><li><a tags="function,intermediate" href="#partialright">partialRight</a></li><li><a tags="function,promise,intermediate" href="#runpromisesinseries">runPromisesInSeries</a></li><li><a tags="function,promise,intermediate" href="#sleep">sleep</a></li><li><a tags="function,advanced" href="#throttle">throttle</a></li><li><a tags="function,intermediate" href="#times">times</a></li><li><a tags="function,intermediate" href="#uncurry">uncurry</a></li><li><a tags="function,array,intermediate" href="#unfold">unfold</a></li><li><a tags="function,intermediate" href="#when">when</a></li></ul><h4 class="collapse">Math</h4><ul><li><a tags="math,beginner" href="./math#approximatelyequal">approximatelyEqual</a></li><li><a tags="math,array,beginner" href="./math#average">average</a></li><li><a tags="math,array,function,intermediate" href="./math#averageby">averageBy</a></li><li><a tags="math,intermediate" href="./math#binomialcoefficient">binomialCoefficient</a></li><li><a tags="math,beginner" href="./math#clampnumber">clampNumber</a></li><li><a tags="math,beginner" href="./math#degreestorads">degreesToRads</a></li><li><a tags="math,array,beginner" href="./math#digitize">digitize</a></li><li><a tags="math,beginner" href="./math#distance">distance</a></li><li><a tags="math,array,advanced" href="./math#elo">elo</a></li><li><a tags="math,recursion,beginner" href="./math#factorial">factorial</a></li><li><a tags="math,array,beginner" href="./math#fibonacci">fibonacci</a></li><li><a tags="math,recursion,beginner" href="./math#gcd">gcd</a></li><li><a tags="math,intermediate" href="./math#geometricprogression">geometricProgression</a></li><li><a tags="math,beginner" href="./math#hammingdistance">hammingDistance</a></li><li><a tags="math,beginner" href="./math#inrange">inRange</a></li><li><a tags="math,beginner" href="./math#isdivisible">isDivisible</a></li><li><a tags="math,beginner" href="./math#iseven">isEven</a></li><li><a tags="math,utility,beginner" href="./math#isnegativezero">isNegativeZero</a></li><li><a tags="math,beginner,intermediate" href="./math#isprime">isPrime</a></li><li><a tags="math,recursion,beginner" href="./math#lcm">lcm</a></li><li><a tags="math,utility,advanced" href="./math#luhncheck">luhnCheck</a></li><li><a tags="math,array,function,beginner" href="./math#maxby">maxBy</a></li><li><a tags="math,array,intermediate" href="./math#median">median</a></li><li><a tags="math,array,beginner" href="./math#midpoint">midpoint</a></li><li><a tags="math,array,function,beginner" href="./math#minby">minBy</a></li><li><a tags="math,intermediate" href="./math#percentile">percentile</a></li><li><a tags="math,beginner" href="./math#powerset">powerset</a></li><li><a tags="math,array,intermediate" href="./math#primes">primes</a></li><li><a tags="math,beginner" href="./math#radstodegrees">radsToDegrees</a></li><li><a tags="math,utility,random,intermediate" href="./math#randomintarrayinrange">randomIntArrayInRange</a></li><li><a tags="math,utility,random,beginner" href="./math#randomintegerinrange">randomIntegerInRange</a></li><li><a tags="math,utility,random,beginner" href="./math#randomnumberinrange">randomNumberInRange</a></li><li><a tags="math,intermediate" href="./math#round">round</a></li><li><a tags="math,utility,intermediate" href="./math#sdbm">sdbm</a></li><li><a tags="math,array,intermediate" href="./math#standarddeviation">standardDeviation</a></li><li><a tags="math,array,beginner" href="./math#sum">sum</a></li><li><a tags="math,array,function,intermediate" href="./math#sumby">sumBy</a></li><li><a tags="math,intermediate" href="./math#sumpower">sumPower</a></li><li><a tags="math,beginner" href="./math#tosafeinteger">toSafeInteger</a></li></ul><h4 class="collapse">Node</h4><ul><li><a tags="node,string,utility,beginner" href="./node#atob">atob</a></li><li><a tags="node,string,utility,beginner" href="./node#btoa">btoa</a></li><li><a tags="node,utility,string,intermediate" href="./node#colorize">colorize</a></li><li><a tags="node,intermediate" href="./node#hasflags">hasFlags</a></li><li><a tags="node,utility,promise,intermediate" href="./node#hashnode">hashNode</a></li><li><a tags="node,type,intermediate" href="./node#isduplexstream">isDuplexStream</a></li><li><a tags="node,type,intermediate" href="./node#isreadablestream">isReadableStream</a></li><li><a tags="node,type,intermediate" href="./node#isstream">isStream</a></li><li><a tags="node,intermediate" href="./node#istravisci">isTravisCI</a></li><li><a tags="node,type,intermediate" href="./node#iswritablestream">isWritableStream</a></li><li><a tags="node,json,intermediate" href="./node#jsontofile">JSONToFile</a></li><li><a tags="node,array,string,beginner" href="./node#readfilelines">readFileLines</a></li><li><a tags="node,string,beginner" href="./node#untildify">untildify</a></li><li><a tags="node,utility,random,intermediate" href="./node#uuidgeneratornode">UUIDGeneratorNode</a></li></ul><h4 class="collapse">Object</h4><ul><li><a tags="object,function,intermediate" href="./object#bindall">bindAll</a></li><li><a tags="object,recursion,intermediate" href="./object#deepclone">deepClone</a></li><li><a tags="object,recursion,intermediate" href="./object#deepfreeze">deepFreeze</a></li><li><a tags="object,recursion,advanced" href="./object#deepmapkeys">deepMapKeys</a></li><li><a tags="object,intermediate" href="./object#defaults">defaults</a></li><li><a tags="object,recursion,intermediate" href="./object#dig">dig</a></li><li><a tags="object,array,type,advanced" href="./object#equals">equals</a></li><li><a tags="object,function,intermediate" href="./object#findkey">findKey</a></li><li><a tags="object,function,intermediate" href="./object#findlastkey">findLastKey</a></li><li><a tags="object,recursion,intermediate" href="./object#flattenobject">flattenObject</a></li><li><a tags="object,intermediate" href="./object#forown">forOwn</a></li><li><a tags="object,intermediate" href="./object#forownright">forOwnRight</a></li><li><a tags="object,function,intermediate" href="./object#functions">functions</a></li><li><a tags="object,intermediate" href="./object#get">get</a></li><li><a tags="object,function,intermediate" href="./object#invertkeyvalues">invertKeyValues</a></li><li><a tags="object,intermediate" href="./object#lowercasekeys">lowercaseKeys</a></li><li><a tags="object,function,intermediate" href="./object#mapkeys">mapKeys</a></li><li><a tags="object,function,intermediate" href="./object#mapvalues">mapValues</a></li><li><a tags="object,type,intermediate" href="./object#matches">matches</a></li><li><a tags="object,type,function,intermediate" href="./object#matcheswith">matchesWith</a></li><li><a tags="object,array,intermediate" href="./object#merge">merge</a></li><li><a tags="object,intermediate" href="./object#nest">nest</a></li><li><a tags="object,array,beginner" href="./object#objectfrompairs">objectFromPairs</a></li><li><a tags="object,array,beginner" href="./object#objecttopairs">objectToPairs</a></li><li><a tags="object,array,intermediate" href="./object#omit">omit</a></li><li><a tags="object,array,function,intermediate" href="./object#omitby">omitBy</a></li><li><a tags="object,array,intermediate" href="./object#orderby">orderBy</a></li><li><a tags="object,array,intermediate" href="./object#pick">pick</a></li><li><a tags="object,array,function,intermediate" href="./object#pickby">pickBy</a></li><li><a tags="object,intermediate" href="./object#renamekeys">renameKeys</a></li><li><a tags="object,beginner" href="./object#shallowclone">shallowClone</a></li><li><a tags="object,array,string,intermediate" href="./object#size">size</a></li><li><a tags="object,array,intermediate" href="./object#transform">transform</a></li><li><a tags="object,logic,array,intermediate" href="./object#truthcheckcollection">truthCheckCollection</a></li><li><a tags="object,advanced" href="./object#unflattenobject">unflattenObject</a></li></ul><h4 class="collapse">String</h4><ul><li><a tags="string,beginner" href="./string#bytesize">byteSize</a></li><li><a tags="string,array,intermediate" href="./string#capitalize">capitalize</a></li><li><a tags="string,regexp,intermediate" href="./string#capitalizeeveryword">capitalizeEveryWord</a></li><li><a tags="string,array,utility,intermediate" href="./string#csvtoarray">CSVToArray</a></li><li><a tags="string,array,object,advanced" href="./string#csvtojson">CSVToJSON</a></li><li><a tags="string,array,intermediate" href="./string#decapitalize">decapitalize</a></li><li><a tags="string,browser,regexp,intermediate" href="./string#escapehtml">escapeHTML</a></li><li><a tags="string,regexp,intermediate" href="./string#escaperegexp">escapeRegExp</a></li><li><a tags="string,intermediate" href="./string#fromcamelcase">fromCamelCase</a></li><li><a tags="string,utility,beginner" href="./string#indentstring">indentString</a></li><li><a tags="string,utility,browser,url,intermediate" href="./string#isabsoluteurl">isAbsoluteURL</a></li><li><a tags="string,regexp,intermediate" href="./string#isanagram">isAnagram</a></li><li><a tags="string,utility,beginner" href="./string#islowercase">isLowerCase</a></li><li><a tags="string,utility,beginner" href="./string#isuppercase">isUpperCase</a></li><li><a tags="string,array,function,utility,beginner" href="./string#mapstring">mapString</a></li><li><a tags="string,utility,regexp,intermediate" href="./string#mask">mask</a></li><li><a tags="string,beginner" href="./string#pad">pad</a></li><li><a tags="string,intermediate" href="./string#palindrome">palindrome</a></li><li><a tags="string,intermediate" href="./string#pluralize">pluralize</a></li><li><a tags="string,regexp,intermediate" href="./string#removenonascii">removeNonASCII</a></li><li><a tags="string,array,beginner" href="./string#reversestring">reverseString</a></li><li><a tags="string,beginner" href="./string#sortcharactersinstring">sortCharactersInString</a></li><li><a tags="string,beginner" href="./string#splitlines">splitLines</a></li><li><a tags="string,recursion,advanced" href="./string#stringpermutations">stringPermutations</a></li><li><a tags="string,utility,regexp,beginner" href="./string#striphtmltags">stripHTMLTags</a></li><li><a tags="string,regexp,intermediate" href="./string#tocamelcase">toCamelCase</a></li><li><a tags="string,regexp,intermediate" href="./string#tokebabcase">toKebabCase</a></li><li><a tags="string,regexp,intermediate" href="./string#tosnakecase">toSnakeCase</a></li><li><a tags="string,regepx,intermediate" href="./string#totitlecase">toTitleCase</a></li><li><a tags="string,beginner" href="./string#truncatestring">truncateString</a></li><li><a tags="string,browser,beginner" href="./string#unescapehtml">unescapeHTML</a></li><li><a tags="string,utility,regexp,advanced" href="./string#urljoin">URLJoin</a></li><li><a tags="string,regexp,intermediate" href="./string#words">words</a></li></ul><h4 class="collapse">Type</h4><ul><li><a tags="type,beginner" href="./type#gettype">getType</a></li><li><a tags="type,array,regexp,beginner" href="./type#is">is</a></li><li><a tags="type,array,intermediate" href="./type#isarraylike">isArrayLike</a></li><li><a tags="type,beginner" href="./type#isboolean">isBoolean</a></li><li><a tags="type,array,object,string,beginner" href="./type#isempty">isEmpty</a></li><li><a tags="type,function,beginner" href="./type#isfunction">isFunction</a></li><li><a tags="type,beginner" href="./type#isnil">isNil</a></li><li><a tags="type,beginner" href="./type#isnull">isNull</a></li><li><a tags="type,math,beginner" href="./type#isnumber">isNumber</a></li><li><a tags="type,object,beginner" href="./type#isobject">isObject</a></li><li><a tags="type,object,beginner" href="./type#isobjectlike">isObjectLike</a></li><li><a tags="type,object,intermediate" href="./type#isplainobject">isPlainObject</a></li><li><a tags="type,function,array,string,intermediate" href="./type#isprimitive">isPrimitive</a></li><li><a tags="type,function,promise,intermediate" href="./type#ispromiselike">isPromiseLike</a></li><li><a tags="type,string,beginner" href="./type#isstring">isString</a></li><li><a tags="type,beginner" href="./type#issymbol">isSymbol</a></li><li><a tags="type,beginner" href="./type#isundefined">isUndefined</a></li><li><a tags="type,json,intermediate" href="./type#isvalidjson">isValidJSON</a></li></ul><h4 class="collapse">Utility</h4><ul><li><a tags="utility,array,type,beginner" href="./utility#castarray">castArray</a></li><li><a tags="utility,regexp,intermediate" href="./utility#cloneregexp">cloneRegExp</a></li><li><a tags="utility,beginner" href="./utility#coalesce">coalesce</a></li><li><a tags="utility,intermediate" href="./utility#coalescefactory">coalesceFactory</a></li><li><a tags="utility,string,intermediate" href="./utility#extendhex">extendHex</a></li><li><a tags="utility,browser,string,url,intermediate" href="./utility#geturlparameters">getURLParameters</a></li><li><a tags="utility,string,math,advanced" href="./utility#hextorgb">hexToRGB</a></li><li><a tags="utility,url,browser,intermediate" href="./utility#httpget">httpGet</a></li><li><a tags="utility,url,browser,intermediate" href="./utility#httppost">httpPost</a></li><li><a tags="utility,browser,intermediate" href="./utility#isbrowser">isBrowser</a></li><li><a tags="utility,function" href="./utility#mostperformant">mostPerformant</a></li><li><a tags="utility,function,beginner" href="./utility#ntharg">nthArg</a></li><li><a tags="utility,string,intermediate" href="./utility#parsecookie">parseCookie</a></li><li><a tags="utility,string,math,advanced" href="./utility#prettybytes">prettyBytes</a></li><li><a tags="utility,random,beginner" href="./utility#randomhexcolorcode">randomHexColorCode</a></li><li><a tags="utility,intermediate" href="./utility#rgbtohex">RGBToHex</a></li><li><a tags="utility,string,intermediate" href="./utility#serializecookie">serializeCookie</a></li><li><a tags="utility,beginner" href="./utility#timetaken">timeTaken</a></li><li><a tags="utility,intermediate" href="./utility#tocurrency">toCurrency</a></li><li><a tags="utility,math,beginner" href="./utility#todecimalmark">toDecimalMark</a></li><li><a tags="utility,math,intermediate" href="./utility#toordinalsuffix">toOrdinalSuffix</a></li><li><a tags="utility,math,intermediate" href="./utility#validatenumber">validateNumber</a></li><li><a tags="utility,regexp,intermediate" href="./utility#yesno">yesNo</a></li></ul><h4 class="static-link"><a href="./archive">Archive</a></h4><h4 class="static-link"><a href="./glossary">Glossary</a></h4><h4 class="static-link"><a href="./contributing">Contributing</a></h4><h4 class="static-link"><a href="./about">About</a></h4><div><button class="social fb"></button><button class="social instagram"></button><button class="social twitter"></button></div></nav><main class="col-centered"><span id="top"><br/><br/></span><h2 class="category-name">Function</h2><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="attempt">attempt</h4><p>Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.</p><p>Use a <code>try... catch</code> block to return either the result of the function or an appropriate error.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">attempt</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">try</span> <span class="token punctuation">{</span>
<span class="token keyword">return</span> <span class="token function">fn</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">);
}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">e</span><span class="token punctuation">) {</span>
<span class="token keyword">return</span> e <span class="token keyword">instanceof</span> <span class="token class-name">Error</span> <span class="token operator">?</span> e <span class="token punctuation">:</span> <span class="token keyword">new</span> <span class="token class-name">Error</span><span class="token punctuation">(</span>e<span class="token punctuation">);
}
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">var</span> elements <span class="token operator">=</span> <span class="token function">attempt</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>selector<span class="token punctuation">) {</span>
<span class="token keyword">return</span> document<span class="token punctuation">.</span><span class="token function">querySelectorAll</span><span class="token punctuation">(</span>selector<span class="token punctuation">);
},</span> <span class="token string">'>_>'</span><span class="token punctuation">);</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>elements <span class="token keyword">instanceof</span> <span class="token class-name">Error</span><span class="token punctuation">)</span> elements <span class="token operator">=</span> <span class="token punctuation">[];</span> <span class="token comment">// elements = []</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="bind">bind</h4><p>Creates a function that invokes <code>fn</code> with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.</p><p>Return a <code>function</code> that uses <code>Function.prototype.apply()</code> to apply the given <code>context</code> to <code>fn</code>. Use <code>Array.prototype.concat()</code> to prepend any additional supplied parameters to the arguments.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">bind</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> context<span class="token punctuation">,</span> <span class="token operator">...</span>boundArgs<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> fn<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>context<span class="token punctuation">, [</span><span class="token operator">...</span>boundArgs<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">]);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">function</span> <span class="token function">greet</span><span class="token punctuation">(</span>greeting<span class="token punctuation">,</span> punctuation<span class="token punctuation">) {</span>
<span class="token keyword">return</span> greeting <span class="token operator">+</span> <span class="token string">' '</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>user <span class="token operator">+</span> punctuation<span class="token punctuation">;
}</span>
<span class="token keyword">const</span> freddy <span class="token operator">=</span> <span class="token punctuation">{</span> user<span class="token punctuation">:</span> <span class="token string">'fred'</span> <span class="token punctuation">};</span>
<span class="token keyword">const</span> freddyBound <span class="token operator">=</span> <span class="token function">bind</span><span class="token punctuation">(</span>greet<span class="token punctuation">,</span> freddy<span class="token punctuation">);</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token function">freddyBound</span><span class="token punctuation">(</span><span class="token string">'hi'</span><span class="token punctuation">,</span> <span class="token string">'!'</span><span class="token punctuation">));</span> <span class="token comment">// 'hi fred!'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="bindkey">bindKey</h4><p>Creates a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.</p><p>Return a <code>function</code> that uses <code>Function.prototype.apply()</code> to bind <code>context[fn]</code> to <code>context</code>. Use the spread operator (<code>...</code>) to prepend any additional supplied parameters to the arguments.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">bindKey</span> <span class="token operator">=</span> <span class="token punctuation">(</span>context<span class="token punctuation">,</span> fn<span class="token punctuation">,</span> <span class="token operator">...</span>boundArgs<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span>
context<span class="token punctuation">[</span>fn<span class="token punctuation">].</span><span class="token function">apply</span><span class="token punctuation">(</span>context<span class="token punctuation">, [</span><span class="token operator">...</span>boundArgs<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">]);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> freddy <span class="token operator">=</span> <span class="token punctuation">{</span>
user<span class="token punctuation">:</span> <span class="token string">'fred'</span><span class="token punctuation">,</span>
greet<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>greeting<span class="token punctuation">,</span> punctuation<span class="token punctuation">) {</span>
<span class="token keyword">return</span> greeting <span class="token operator">+</span> <span class="token string">' '</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>user <span class="token operator">+</span> punctuation<span class="token punctuation">;
}
};</span>
<span class="token keyword">const</span> freddyBound <span class="token operator">=</span> <span class="token function">bindKey</span><span class="token punctuation">(</span>freddy<span class="token punctuation">,</span> <span class="token string">'greet'</span><span class="token punctuation">);</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token function">freddyBound</span><span class="token punctuation">(</span><span class="token string">'hi'</span><span class="token punctuation">,</span> <span class="token string">'!'</span><span class="token punctuation">));</span> <span class="token comment">// 'hi fred!'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="chainasync">chainAsync</h4><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></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">chainAsync</span> <span class="token operator">=</span> fns <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">let</span> curr <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> <span class="token function-variable function">next</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> fns<span class="token punctuation">[</span>curr<span class="token operator">++</span><span class="token punctuation">](</span>next<span class="token punctuation">);</span>
<span class="token function">next</span><span class="token punctuation">();
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">chainAsync</span><span class="token punctuation">([</span>
next <span class="token operator">=></span> <span class="token punctuation">{</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'0 seconds'</span><span class="token punctuation">);</span>
<span class="token function">setTimeout</span><span class="token punctuation">(</span>next<span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">);
},</span>
next <span class="token operator">=></span> <span class="token punctuation">{</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'1 second'</span><span class="token punctuation">);
}
]);</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="compose">compose</h4><p>Performs right-to-left function composition.</p><p>Use <code>Array.prototype.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></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">compose</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token operator">...</span>fns<span class="token punctuation">)</span> <span class="token operator">=></span> fns<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">((</span>f<span class="token punctuation">,</span> g<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token function">g</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">add5</span> <span class="token operator">=</span> x <span class="token operator">=></span> x <span class="token operator">+</span> <span class="token number">5</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> <span class="token function-variable function">multiply</span> <span class="token operator">=</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">=></span> x <span class="token operator">*</span> y<span class="token punctuation">;</span>
<span class="token keyword">const</span> multiplyAndAdd5 <span class="token operator">=</span> <span class="token function">compose</span><span class="token punctuation">(</span>
add5<span class="token punctuation">,</span>
multiply
<span class="token punctuation">);</span>
<span class="token function">multiplyAndAdd5</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">);</span> <span class="token comment">// 15</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="composeright">composeRight</h4><p>Performs left-to-right function composition.</p><p>Use <code>Array.prototype.reduce()</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></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">composeRight</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token operator">...</span>fns<span class="token punctuation">)</span> <span class="token operator">=></span> fns<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">((</span>f<span class="token punctuation">,</span> g<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">g</span><span class="token punctuation">(</span><span class="token function">f</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">add</span> <span class="token operator">=</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">=></span> x <span class="token operator">+</span> y<span class="token punctuation">;</span>
<span class="token keyword">const</span> <span class="token function-variable function">square</span> <span class="token operator">=</span> x <span class="token operator">=></span> x <span class="token operator">*</span> x<span class="token punctuation">;</span>
<span class="token keyword">const</span> addAndSquare <span class="token operator">=</span> <span class="token function">composeRight</span><span class="token punctuation">(</span>add<span class="token punctuation">,</span> square<span class="token punctuation">);</span>
<span class="token function">addAndSquare</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">);</span> <span class="token comment">// 9</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="converge">converge</h4><p>Accepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function.</p><p>Use <code>Array.prototype.map()</code> and <code>Function.prototype.apply()</code> to apply each function to the given arguments. Use the spread operator (<code>...</code>) to call <code>coverger</code> with the results of all other functions.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">converge</span> <span class="token operator">=</span> <span class="token punctuation">(</span>converger<span class="token punctuation">,</span> fns<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">converger</span><span class="token punctuation">(</span><span class="token operator">...</span>fns<span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>fn <span class="token operator">=></span> fn<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> args<span class="token punctuation">)));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> average <span class="token operator">=</span> <span class="token function">converge</span><span class="token punctuation">((</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">=></span> a <span class="token operator">/</span> b<span class="token punctuation">, [</span>
arr <span class="token operator">=></span> arr<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">((</span>a<span class="token punctuation">,</span> v<span class="token punctuation">)</span> <span class="token operator">=></span> a <span class="token operator">+</span> v<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">),</span>
arr <span class="token operator">=></span> arr<span class="token punctuation">.</span>length
<span class="token punctuation">]);</span>
<span class="token function">average</span><span class="token punctuation">([</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">]);</span> <span class="token comment">// 4</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="curry">curry</h4><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></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">curry</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> arity <span class="token operator">=</span> fn<span class="token punctuation">.</span>length<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span>
arity <span class="token operator"><=</span> args<span class="token punctuation">.</span>length <span class="token operator">?</span> <span class="token function">fn</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">) :</span> curry<span class="token punctuation">.</span><span class="token function">bind</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> fn<span class="token punctuation">,</span> arity<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">curry</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span>pow<span class="token punctuation">)(</span><span class="token number">2</span><span class="token punctuation">)(</span><span class="token number">10</span><span class="token punctuation">);</span> <span class="token comment">// 1024</span>
<span class="token function">curry</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span>min<span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)(</span><span class="token number">10</span><span class="token punctuation">)(</span><span class="token number">50</span><span class="token punctuation">)(</span><span class="token number">2</span><span class="token punctuation">);</span> <span class="token comment">// 2</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="debounce">debounce</h4><p>Creates a debounced function that delays invoking the provided function until at least <code>ms</code> milliseconds have elapsed since the last time it was invoked.</p><p>Each time the debounced function is invoked, clear the current pending timeout with <code>clearTimeout()</code> and use <code>setTimeout()</code> to create a new timeout that delays invoking the function until at least <code>ms</code> milliseconds has elapsed. Use <code>Function.prototype.apply()</code> to apply the <code>this</code> context to the function and provide the necessary arguments. Omit the second argument, <code>ms</code>, to set the timeout at a default of 0 ms.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">debounce</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> ms <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">let</span> timeoutId<span class="token punctuation">;</span>
<span class="token keyword">return function</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">) {</span>
<span class="token function">clearTimeout</span><span class="token punctuation">(</span>timeoutId<span class="token punctuation">);</span>
timeoutId <span class="token operator">=</span> <span class="token function">setTimeout</span><span class="token punctuation">(()</span> <span class="token operator">=></span> fn<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> args<span class="token punctuation">),</span> ms<span class="token punctuation">);
};
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js">window<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span>
<span class="token string">'resize'</span><span class="token punctuation">,</span>
<span class="token function">debounce</span><span class="token punctuation">(()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>window<span class="token punctuation">.</span>innerWidth<span class="token punctuation">);</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>window<span class="token punctuation">.</span>innerHeight<span class="token punctuation">);
},</span> <span class="token number">250</span><span class="token punctuation">)
);</span> <span class="token comment">// Will log the window dimensions at most every 250ms</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="defer">defer</h4><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></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">defer</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">setTimeout</span><span class="token punctuation">(</span>fn<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token comment">// Example A:</span>
<span class="token function">defer</span><span class="token punctuation">(</span>console<span class="token punctuation">.</span>log<span class="token punctuation">,</span> <span class="token string">'a'</span><span class="token punctuation">),</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'b'</span><span class="token punctuation">);</span> <span class="token comment">// logs 'b' then 'a'</span>
<span class="token comment">// Example B:</span>
document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'#someElement'</span><span class="token punctuation">).</span>innerHTML <span class="token operator">=</span> <span class="token string">'Hello'</span><span class="token punctuation">;</span>
<span class="token function">longRunningFunction</span><span class="token punctuation">();</span> <span class="token comment">// Browser will not update the HTML until this has finished</span>
<span class="token function">defer</span><span class="token punctuation">(</span>longRunningFunction<span class="token punctuation">);</span> <span class="token comment">// Browser will update the HTML then run the function</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="delay">delay</h4><p>Invokes the provided function after <code>wait</code> milliseconds.</p><p>Use <code>setTimeout()</code> to delay execution of <code>fn</code>. Use the spread (<code>...</code>) operator to supply the function with an arbitrary number of arguments.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">delay</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> wait<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">setTimeout</span><span class="token punctuation">(</span>fn<span class="token punctuation">,</span> wait<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">delay</span><span class="token punctuation">(</span>
<span class="token keyword">function</span><span class="token punctuation">(</span>text<span class="token punctuation">) {</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>text<span class="token punctuation">);
},</span>
<span class="token number">1000</span><span class="token punctuation">,</span>
<span class="token string">'later'</span>
<span class="token punctuation">);</span> <span class="token comment">// Logs 'later' after one second.</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="functionname">functionName</h4><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></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">functionName</span> <span class="token operator">=</span> fn <span class="token operator">=></span> <span class="token punctuation">(</span>console<span class="token punctuation">.</span><span class="token function">debug</span><span class="token punctuation">(</span>fn<span class="token punctuation">.</span>name<span class="token punctuation">),</span> fn<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">functionName</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span>max<span class="token punctuation">);</span> <span class="token comment">// max (logged in debug channel of console)</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="hz">hz</h4><p>Returns the number of times a function executed per second. <code>hz</code> is the unit for <code>hertz</code>, the unit of frequency defined as one cycle per second.</p><p>Use <code>performance.now()</code> to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function <code>iterations</code> times. Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed. Omit the second argument, <code>iterations</code>, to use the default of 100 iterations.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">hz</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> iterations <span class="token operator">=</span> <span class="token number">100</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> before <span class="token operator">=</span> performance<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">();</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator"><</span> iterations<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token function">fn</span><span class="token punctuation">();</span>
<span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token number">1000</span> <span class="token operator">*</span> iterations<span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token punctuation">(</span>performance<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">()</span> <span class="token operator">-</span> before<span class="token punctuation">);
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token comment">// 10,000 element array</span>
<span class="token keyword">const</span> numbers <span class="token operator">=</span> <span class="token function">Array</span><span class="token punctuation">(</span><span class="token number">10000</span><span class="token punctuation">)
.</span><span class="token function">fill</span><span class="token punctuation">()
.</span><span class="token function">map</span><span class="token punctuation">((</span>_<span class="token punctuation">,</span> i<span class="token punctuation">)</span> <span class="token operator">=></span> i<span class="token punctuation">);</span>
<span class="token comment">// Test functions with the same goal: sum up the elements in the array</span>
<span class="token keyword">const</span> <span class="token function-variable function">sumReduce</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> numbers<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">((</span>acc<span class="token punctuation">,</span> n<span class="token punctuation">)</span> <span class="token operator">=></span> acc <span class="token operator">+</span> n<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">);</span>
<span class="token keyword">const</span> <span class="token function-variable function">sumForLoop</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">let</span> sum <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator"><</span> numbers<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> sum <span class="token operator">+=</span> numbers<span class="token punctuation">[</span>i<span class="token punctuation">];</span>
<span class="token keyword">return</span> sum<span class="token punctuation">;
};</span>
<span class="token comment">// `sumForLoop` is nearly 10 times faster</span>
Math<span class="token punctuation">.</span><span class="token function">round</span><span class="token punctuation">(</span><span class="token function">hz</span><span class="token punctuation">(</span>sumReduce<span class="token punctuation">));</span> <span class="token comment">// 572</span>
Math<span class="token punctuation">.</span><span class="token function">round</span><span class="token punctuation">(</span><span class="token function">hz</span><span class="token punctuation">(</span>sumForLoop<span class="token punctuation">));</span> <span class="token comment">// 4784</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="memoize">memoize</h4><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></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">memoize</span> <span class="token operator">=</span> fn <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> cache <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Map</span><span class="token punctuation">();</span>
<span class="token keyword">const</span> <span class="token function-variable function">cached</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span>val<span class="token punctuation">) {</span>
<span class="token keyword">return</span> cache<span class="token punctuation">.</span><span class="token function">has</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span> <span class="token operator">?</span> cache<span class="token punctuation">.</span><span class="token keyword">get</span><span class="token punctuation">(</span>val<span class="token punctuation">) :</span> cache<span class="token punctuation">.</span><span class="token keyword">set</span><span class="token punctuation">(</span>val<span class="token punctuation">,</span> fn<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> val<span class="token punctuation">))</span> <span class="token operator">&&</span> cache<span class="token punctuation">.</span><span class="token keyword">get</span><span class="token punctuation">(</span>val<span class="token punctuation">);
};</span>
cached<span class="token punctuation">.</span>cache <span class="token operator">=</span> cache<span class="token punctuation">;</span>
<span class="token keyword">return</span> cached<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token comment">// See the `anagrams` snippet.</span>
<span class="token keyword">const</span> anagramsCached <span class="token operator">=</span> <span class="token function">memoize</span><span class="token punctuation">(</span>anagrams<span class="token punctuation">);</span>
<span class="token function">anagramsCached</span><span class="token punctuation">(</span><span class="token string">'javascript'</span><span class="token punctuation">);</span> <span class="token comment">// takes a long time</span>
<span class="token function">anagramsCached</span><span class="token punctuation">(</span><span class="token string">'javascript'</span><span class="token punctuation">);</span> <span class="token comment">// returns virtually instantly since it's now cached</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>anagramsCached<span class="token punctuation">.</span>cache<span class="token punctuation">);</span> <span class="token comment">// The cached anagrams map</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="negate">negate</h4><p>Negates a predicate function.</p><p>Take a predicate function and apply the not operator (<code>!</code>) to it with its arguments.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">negate</span> <span class="token operator">=</span> func <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=> !</span><span class="token function">func</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">].</span><span class="token function">filter</span><span class="token punctuation">(</span><span class="token function">negate</span><span class="token punctuation">(</span>n <span class="token operator">=></span> n <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">));</span> <span class="token comment">// [ 1, 3, 5 ]</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="once">once</h4><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></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">once</span> <span class="token operator">=</span> fn <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">let</span> called <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
<span class="token keyword">return function</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">) {</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>called<span class="token punctuation">)</span> <span class="token keyword">return</span><span class="token punctuation">;</span>
called <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> fn<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> args<span class="token punctuation">);
};
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">startApp</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span>event<span class="token punctuation">) {</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> event<span class="token punctuation">);</span> <span class="token comment">// document.body, MouseEvent</span>
<span class="token punctuation">};</span>
document<span class="token punctuation">.</span>body<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'click'</span><span class="token punctuation">,</span> <span class="token function">once</span><span class="token punctuation">(</span>startApp<span class="token punctuation">));</span> <span class="token comment">// only runs `startApp` once upon click</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="partial">partial</h4><p>Creates a function that invokes <code>fn</code> with <code>partials</code> prepended to the arguments it receives.</p><p>Use the spread operator (<code>...</code>) to prepend <code>partials</code> to the list of arguments of <code>fn</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">partial</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> <span class="token operator">...</span>partials<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">fn</span><span class="token punctuation">(</span><span class="token operator">...</span>partials<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">greet</span> <span class="token operator">=</span> <span class="token punctuation">(</span>greeting<span class="token punctuation">,</span> name<span class="token punctuation">)</span> <span class="token operator">=></span> greeting <span class="token operator">+</span> <span class="token string">' '</span> <span class="token operator">+</span> name <span class="token operator">+</span> <span class="token string">'!'</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> greetHello <span class="token operator">=</span> <span class="token function">partial</span><span class="token punctuation">(</span>greet<span class="token punctuation">,</span> <span class="token string">'Hello'</span><span class="token punctuation">);</span>
<span class="token function">greetHello</span><span class="token punctuation">(</span><span class="token string">'John'</span><span class="token punctuation">);</span> <span class="token comment">// 'Hello John!'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="partialright">partialRight</h4><p>Creates a function that invokes <code>fn</code> with <code>partials</code> appended to the arguments it receives.</p><p>Use the spread operator (<code>...</code>) to append <code>partials</code> to the list of arguments of <code>fn</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">partialRight</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> <span class="token operator">...</span>partials<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">fn</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">,</span> <span class="token operator">...</span>partials<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">greet</span> <span class="token operator">=</span> <span class="token punctuation">(</span>greeting<span class="token punctuation">,</span> name<span class="token punctuation">)</span> <span class="token operator">=></span> greeting <span class="token operator">+</span> <span class="token string">' '</span> <span class="token operator">+</span> name <span class="token operator">+</span> <span class="token string">'!'</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> greetJohn <span class="token operator">=</span> <span class="token function">partialRight</span><span class="token punctuation">(</span>greet<span class="token punctuation">,</span> <span class="token string">'John'</span><span class="token punctuation">);</span>
<span class="token function">greetJohn</span><span class="token punctuation">(</span><span class="token string">'Hello'</span><span class="token punctuation">);</span> <span class="token comment">// 'Hello John!'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="runpromisesinseries">runPromisesInSeries</h4><p>Runs an array of promises in series.</p><p>Use <code>Array.prototype.reduce()</code> to create a promise chain, where each promise returns the next promise when resolved.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">runPromisesInSeries</span> <span class="token operator">=</span> ps <span class="token operator">=></span> ps<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">((</span>p<span class="token punctuation">,</span> next<span class="token punctuation">)</span> <span class="token operator">=></span> p<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>next<span class="token punctuation">),</span> Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">());</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">delay</span> <span class="token operator">=</span> d <span class="token operator">=></span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span>r <span class="token operator">=></span> <span class="token function">setTimeout</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> d<span class="token punctuation">));</span>
<span class="token function">runPromisesInSeries</span><span class="token punctuation">([()</span> <span class="token operator">=></span> <span class="token function">delay</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">), ()</span> <span class="token operator">=></span> <span class="token function">delay</span><span class="token punctuation">(</span><span class="token number">2000</span><span class="token punctuation">)]);</span> <span class="token comment">// Executes each promise sequentially, taking a total of 3 seconds to complete</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="sleep">sleep</h4><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></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">sleep</span> <span class="token operator">=</span> ms <span class="token operator">=></span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span>resolve <span class="token operator">=></span> <span class="token function">setTimeout</span><span class="token punctuation">(</span>resolve<span class="token punctuation">,</span> ms<span class="token punctuation">));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">async function</span> <span class="token function">sleepyWork</span><span class="token punctuation">() {</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"I'm going to sleep for 1 second."</span><span class="token punctuation">);</span>
<span class="token keyword">await</span> <span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">);</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'I woke up after 1 second.'</span><span class="token punctuation">);
}</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="throttle">throttle</h4><p>Creates a throttled function that only invokes the provided function at most once per every <code>wait</code> milliseconds</p><p>Use <code>setTimeout()</code> and <code>clearTimeout()</code> to throttle the given method, <code>fn</code>. Use <code>Function.prototype.apply()</code> to apply the <code>this</code> context to the function and provide the necessary <code>arguments</code>. Use <code>Date.now()</code> to keep track of the last time the throttled function was invoked. Omit the second argument, <code>wait</code>, to set the timeout at a default of 0 ms.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">throttle</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> wait<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">let</span> inThrottle<span class="token punctuation">,</span> lastFn<span class="token punctuation">,</span> lastTime<span class="token punctuation">;</span>
<span class="token keyword">return function</span><span class="token punctuation">() {</span>
<span class="token keyword">const</span> context <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">,</span>
args <span class="token operator">=</span> arguments<span class="token punctuation">;</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>inThrottle<span class="token punctuation">) {</span>
fn<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>context<span class="token punctuation">,</span> args<span class="token punctuation">);</span>
lastTime <span class="token operator">=</span> Date<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">();</span>
inThrottle <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;
}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
<span class="token function">clearTimeout</span><span class="token punctuation">(</span>lastFn<span class="token punctuation">);</span>
lastFn <span class="token operator">=</span> <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">() {</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>Date<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">()</span> <span class="token operator">-</span> lastTime <span class="token operator">>=</span> wait<span class="token punctuation">) {</span>
fn<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>context<span class="token punctuation">,</span> args<span class="token punctuation">);</span>
lastTime <span class="token operator">=</span> Date<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">();
}
},</span> Math<span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span>wait <span class="token operator">-</span> <span class="token punctuation">(</span>Date<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">()</span> <span class="token operator">-</span> lastTime<span class="token punctuation">),</span> <span class="token number">0</span><span class="token punctuation">));
}
};
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js">window<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span>
<span class="token string">'resize'</span><span class="token punctuation">,</span>
<span class="token function">throttle</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>evt<span class="token punctuation">) {</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>window<span class="token punctuation">.</span>innerWidth<span class="token punctuation">);</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>window<span class="token punctuation">.</span>innerHeight<span class="token punctuation">);
},</span> <span class="token number">250</span><span class="token punctuation">)
);</span> <span class="token comment">// Will log the window dimensions at most every 250ms</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="times">times</h4><p>Iterates over a callback <code>n</code> times</p><p>Use <code>Function.call()</code> to call <code>fn</code> <code>n</code> times or until it returns <code>false</code>. Omit the last argument, <code>context</code>, to use an <code>undefined</code> object (or the global object in non-strict mode).</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">times</span> <span class="token operator">=</span> <span class="token punctuation">(</span>n<span class="token punctuation">,</span> fn<span class="token punctuation">,</span> context <span class="token operator">=</span> undefined<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">while</span> <span class="token punctuation">(</span>fn<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>context<span class="token punctuation">,</span> i<span class="token punctuation">)</span> <span class="token operator">!==</span> <span class="token boolean">false</span> <span class="token operator">&& ++</span>i <span class="token operator"><</span> n<span class="token punctuation">) {}
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">var</span> output <span class="token operator">=</span> <span class="token string">''</span><span class="token punctuation">;</span>
<span class="token function">times</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> i <span class="token operator">=></span> <span class="token punctuation">(</span>output <span class="token operator">+=</span> i<span class="token punctuation">));</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>output<span class="token punctuation">);</span> <span class="token comment">// 01234</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="uncurry">uncurry</h4><p>Uncurries a function up to depth <code>n</code>.</p><p>Return a variadic function. Use <code>Array.prototype.reduce()</code> on the provided arguments to call each subsequent curry level of the function. If the <code>length</code> of the provided arguments is less than <code>n</code> throw an error. Otherwise, call <code>fn</code> with the proper amount of arguments, using <code>Array.prototype.slice(0, n)</code>. Omit the second argument, <code>n</code>, to uncurry up to depth <code>1</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">uncurry</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> n <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> <span class="token function-variable function">next</span> <span class="token operator">=</span> acc <span class="token operator">=></span> args <span class="token operator">=></span> args<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">((</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">x</span><span class="token punctuation">(</span>y<span class="token punctuation">),</span> acc<span class="token punctuation">);</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>n <span class="token operator">></span> args<span class="token punctuation">.</span>length<span class="token punctuation">)</span> <span class="token keyword">throw new</span> <span class="token class-name">RangeError</span><span class="token punctuation">(</span><span class="token string">'Arguments too few!'</span><span class="token punctuation">);</span>
<span class="token keyword">return</span> <span class="token function">next</span><span class="token punctuation">(</span>fn<span class="token punctuation">)(</span>args<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> n<span class="token punctuation">));
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">add</span> <span class="token operator">=</span> x <span class="token operator">=></span> y <span class="token operator">=></span> z <span class="token operator">=></span> x <span class="token operator">+</span> y <span class="token operator">+</span> z<span class="token punctuation">;</span>
<span class="token keyword">const</span> uncurriedAdd <span class="token operator">=</span> <span class="token function">uncurry</span><span class="token punctuation">(</span>add<span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">);</span>
<span class="token function">uncurriedAdd</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">);</span> <span class="token comment">// 6</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="unfold">unfold</h4><p>Builds an array, using an iterator function and an initial seed value.</p><p>Use a <code>while</code> loop and <code>Array.prototype.push()</code> to call the function repeatedly until it returns <code>false</code>. The iterator function accepts one argument (<code>seed</code>) and must always return an array with two elements ([<code>value</code>, <code>nextSeed</code>]) or <code>false</code> to terminate.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">unfold</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fn<span class="token punctuation">,</span> seed<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">let</span> result <span class="token operator">=</span> <span class="token punctuation">[],</span>
val <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token keyword">null</span><span class="token punctuation">,</span> seed<span class="token punctuation">];</span>
<span class="token keyword">while</span> <span class="token punctuation">((</span>val <span class="token operator">=</span> <span class="token function">fn</span><span class="token punctuation">(</span>val<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">])))</span> result<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>val<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]);</span>
<span class="token keyword">return</span> result<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">var</span> <span class="token function-variable function">f</span> <span class="token operator">=</span> n <span class="token operator">=></span> <span class="token punctuation">(</span>n <span class="token operator">></span> <span class="token number">50</span> <span class="token operator">?</span> <span class="token boolean">false</span> <span class="token punctuation">: [</span><span class="token operator">-</span>n<span class="token punctuation">,</span> n <span class="token operator">+</span> <span class="token number">10</span><span class="token punctuation">]);</span>
<span class="token function">unfold</span><span class="token punctuation">(</span>f<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">);</span> <span class="token comment">// [-10, -20, -30, -40, -50]</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="when">when</h4><p>Tests a value, <code>x</code>, against a predicate function. If <code>true</code>, return <code>fn(x)</code>. Else, return <code>x</code>.</p><p>Return a function expecting a single value, <code>x</code>, that returns the appropriate value based on <code>pred</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">when</span> <span class="token operator">=</span> <span class="token punctuation">(</span>pred<span class="token punctuation">,</span> whenTrue<span class="token punctuation">)</span> <span class="token operator">=></span> x <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token function">pred</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token function">whenTrue</span><span class="token punctuation">(</span>x<span class="token punctuation">) :</span> x<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> doubleEvenNumbers <span class="token operator">=</span> <span class="token function">when</span><span class="token punctuation">(</span>x <span class="token operator">=></span> x <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">,</span> x <span class="token operator">=></span> x <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">);</span>
<span class="token function">doubleEvenNumbers</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">);</span> <span class="token comment">// 4</span>
<span class="token function">doubleEvenNumbers</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">);</span> <span class="token comment">// 1</span>
</pre></div></main><footer class="col-full-width container"><div class="col-centered"><p style="display:inline-block"><strong>30 seconds of code</strong> is licensed under the <a href="https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE">CC0-1.0</a> license.<br>Logos made by <a href="https://github.com/Chalarangelo">Angelos Chalaris</a> and ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> are licensed under the <a href="https://opensource.org/licenses/MIT">MIT</a> license.<br>Sponsored by <img src="https://30secondsofcode.org/sponsors/DO_Logo_icon_blue.svg" style="vertical-align:sub;padding-right:2px;padding-left:2px" width="20px" height="20px"><a href="https://www.digitalocean.com" alt="DigitalOcean"><span style="color:#0080ff">DigitalOcean</span></a>.</p><br/><p style="display:inline-block"><a href="./about">About</a> <a href="./contributing">Contributing</a> <a href="./archive">Archive</a> <a href="./glossary">Glossary</a></p></div></footer><a class="scroll-to-top" href="#top"></a></div></body></html>