-
Notifications
You must be signed in to change notification settings - Fork 26
/
javascript.json
1320 lines (1320 loc) · 126 KB
/
javascript.json
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"snippet-anagrams": {
"prefix": "anagrams",
"body": "const anagrams = str => {\n if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];\n return str\n .split('')\n .reduce(\n (acc, letter, i) =>\n acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),\n []\n );\n};",
"description": "⚠️ **WARNING**: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations. Generates all anagrams of a string (contains duplicates). Use recursion. For each letter in the given string, create all the partial anagrams for the rest of its letters. Use `Array.map()` to combine the letter with each partial anagram, then `Array.reduce()` to combine all anagrams in one array. Base cases are for string `length` equal to `2` or `1`."
}
"snippet-arrayToHtmlList": {
"prefix": "arrayToHtmlList",
"body": "const arrayToHtmlList = (arr, listID) =>\n arr.map(item => (document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`));",
"description": "Converts the given array elements into `<li>` tags and appends them to the list of the given id. Use `Array.map()` and `document.querySelector()` to create a list of html tags."
}
"snippet-ary": {
"prefix": "ary",
"body": "const ary = (fn, n) => (...args) => fn(...args.slice(0, n));",
"description": "Creates a function that accepts up to `n` arguments, ignoring any additional arguments. Call the provided function, `fn`, with up to `n` arguments, using `Array.slice(0,n)` and the spread operator (`...`)."
}
"snippet-atob": {
"prefix": "atob",
"body": "const atob = str => new Buffer(str, 'base64').toString('binary');",
"description": "Decodes a string of data which has been encoded using base-64 encoding. Create a `Buffer` for the given string with base-64 encoding and use `Buffer.toString('binary')` to return the decoded string."
}
"snippet-average": {
"prefix": "average",
"body": "const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;",
"description": "Returns the average of two or more numbers. Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array."
}
"snippet-aveargeBy": {
"prefix": "aveargeBy",
"body": "const averageBy = (arr, fn) =>\n arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /\n arr.length;",
"description": "Returns the average of an array, after mapping each element to a value using the provided function. Use `Array.map()` to map each element to the value returned by `fn`, `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array."
}
"snippet-bind": {
"prefix": "bind",
"body": "const bind = (fn, context, ...args) =>\n function() {\n return fn.apply(context, args.concat(...arguments));\n };",
"description": "Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments. Return a `function` that uses `Function.apply()` to apply the given `context` to `fn`. Use `Array.concat()` to prepend any additional supplied parameters to the arguments."
}
"snippet-bindAll": {
"prefix": "bindAll",
"body": "const bindAll = (obj, ...fns) =>\n fns.forEach(\n fn =>\n (obj[fn] = function() {\n return fn.apply(obj);\n })\n );",
"description": "Use `Array.forEach()` to return a `function` that uses `Function.apply()` to apply the given context (`obj`) to `fn` for each function specified."
}
"snippet-bindKey": {
"prefix": "bindKey",
"body": "const bindKey = (context, fn, ...args) =>\n function() {\n return context[fn].apply(context, args.concat(...arguments));\n };",
"description": "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. Return a `function` that uses `Function.apply()` to bind `context[fn]` to `context`. Use `Array.concat()` to prepend any additional supplied parameters to the arguments."
}
"snippet-btoa": {
"prefix": "btoa",
"body": "const btoa = str => new Buffer(str, 'binary').toString('base64');",
"description": "Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data. Create a `Buffer` for the given string with binary encoding and use `Buffer.toString('base64')` to return the encoded string."
}
"snippet-bottomVisible": {
"prefix": "bottomVisible",
"body": "const bottomVisible = () =>\n document.documentElement.clientHeight + window.scrollY >=\n (document.documentElement.scrollHeight || document.documentElement.clientHeight);",
"description": "Returns `true` if the bottom of the page is visible, `false` otherwise. Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible."
}
"snippet-byteSize": {
"prefix": "byteSize",
"body": "const byteSize = str => new Blob([str]).size;",
"description": "Returns the length of a string in bytes. Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`."
}
"snippet-call": {
"prefix": "call",
"body": "const call = (key, ...args) => context => context[key](...args);",
"description": "Given a key and a set of arguments, call them when given a context. Primarily useful in composition. Use a closure to call a stored key with stored arguments."
}
"snippet-capitalize": {
"prefix": "capitalize",
"body": "const capitalize = ([first, ...rest], lowerRest = false) =>\n first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));",
"description": "Capitalizes the first letter of a string. Use array destructuring and `String.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again. Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase."
}
"snippet-capitalizeEveryWord": {
"prefix": "capitalizeEveryWord",
"body": "const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());",
"description": "Capitalizes the first letter of every word in a string. Use `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it."
}
"snippet-castArray": {
"prefix": "castArray",
"body": "const castArray = val => (Array.isArray(val) ? val : [val]);",
"description": "Casts the provided value as an array if it's not one. Use `Array.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly."
}
"snippet-chainAsync": {
"prefix": "chainAsync",
"body": "const chainAsync = fns => {\n let curr = 0;\n const next = () => fns[curr++](next);\n next();\n};",
"description": "Chains asynchronous functions. Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed."
}
"snippet-chunk": {
"prefix": "chunk",
"body": "const chunk = (arr, size) =>\n Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>\n arr.slice(i * size, i * size + size)\n );",
"description": "Chunks an array into smaller arrays of a specified size. Use `Array.from()` to create a new array, that fits the number of chunks that will be produced. Use `Array.slice()` to map each element of the new array to a chunk the length of `size`. If the original array can't be split evenly, the final chunk will contain the remaining elements."
}
"snippet-clampNumber": {
"prefix": "clampNumber",
"body": "const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));",
"description": "Clamps `num` within the inclusive range specified by the boundary values `a` and `b`. If `num` falls within the range, return `num`. Otherwise, return the nearest number in the range."
}
"snippet-cloneRegExp": {
"prefix": "cloneRegExp",
"body": "const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);",
"description": "Clones a regular expression. Use `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regular expression."
}
"snippet-coalesce": {
"prefix": "coalesce",
"body": "const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));",
"description": " Returns the first non-null/undefined argument. Use `Array.find()` to return the first non `null`/`undefined` argument."
}
"snippet-coalesceFactory": {
"prefix": "coalesceFactory",
"body": "const coalesceFactory = valid => (...args) => args.find(valid);",
"description": "Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function. Use `Array.find()` to return the first argument that returns `true` from the provided argument validation function."
}
"snippet-collectInto": {
"prefix": "collectInto",
"body": "const collectInto = fn => (...args) => fn(args);",
"description": "Changes a function that accepts an array into a variadic function. Given a function, return a closure that collects all inputs into an array-accepting function."
}
"snippet-colorize": {
"prefix": "colorize",
"body": "const colorize = (...args) => ({\n black: `\\x1b[30m${args.join(' ')}`,\n red: `\\x1b[31m${args.join(' ')}`,\n green: `\\x1b[32m${args.join(' ')}`,\n yellow: `\\x1b[33m${args.join(' ')}`,\n blue: `\\x1b[34m${args.join(' ')}`,\n magenta: `\\x1b[35m${args.join(' ')}`,\n cyan: `\\x1b[36m${args.join(' ')}`,\n white: `\\x1b[37m${args.join(' ')}`,\n bgBlack: `\\x1b[40m${args.join(' ')}\\x1b[0m`,\n bgRed: `\\x1b[41m${args.join(' ')}\\x1b[0m`,\n bgGreen: `\\x1b[42m${args.join(' ')}\\x1b[0m`,\n bgYellow: `\\x1b[43m${args.join(' ')}\\x1b[0m`,\n bgBlue: `\\x1b[44m${args.join(' ')}\\x1b[0m`,\n bgMagenta: `\\x1b[45m${args.join(' ')}\\x1b[0m`,\n bgCyan: `\\x1b[46m${args.join(' ')}\\x1b[0m`,\n bgWhite: `\\x1b[47m${args.join(' ')}\\x1b[0m`\n});",
"description": "Add special characters to text to print in color in the console (combined with `console.log()`). Use template literals and special characters to add the appropriate color code to the string output. For background colors, add a special character that resets the background color at the end of the string."
}
"snippet-compact": {
"prefix": "compact",
"body": "const compact = arr => arr.filter(Boolean);",
"description": "Removes falsey values from an array. Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `\"\"`, `undefined`, and `NaN`)."
}
"snippet-compose": {
"prefix": "compose",
"body": "const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));",
"description": "Performs right-to-left function composition. Use `Array.reduce()` to perform right-to-left function composition. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary."
}
"snippet-composeRight": {
"prefix": "composeRight",
"body": "const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));",
"description": "Performs left-to-right function composition. Use `Array.reduce()` to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary."
}
"snippet-copyToClipboard": {
"prefix": "copyToClipboard",
"body": "const copyToClipboard = str => {\n const el = document.createElement('textarea');\n el.value = str;\n el.setAttribute('readonly', '');\n el.style.position = 'absolute';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n const selected =\n document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n if (selected) {\n document.getSelection().removeAllRanges();\n document.getSelection().addRange(selected);\n }\n};",
"description": "Copy a string to the clipboard. Only works as a result of user action (i.e. inside a `click` event listener). Create a new `<textarea>` element, fill it with the supplied data and add it to the HTML document. Use `Selection.getRangeAt()`to store the selected range (if any). Use `document.execCommand('copy')` to copy to the clipboard. Remove the `<textarea>` element from the HTML document. Finally, use `Selection().addRange()` to recover the original selected range (if any)."
}
"snippet-countBy": {
"prefix": "countBy",
"body": "const countBy = (arr, fn) =>\n arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {\n acc[val] = (acc[val] || 0) + 1;\n return acc;\n } {});",
"description": "Groups the elements of an array based on the given function and returns the count of elements in each group. Use `Array.map()` to map the values of an array to a function or property name. Use `Array.reduce()` to create an object, where the keys are produced from the mapped results."
}
"snippet-countOccurrences": {
"prefix": "countOccurrences",
"body": "const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0);",
"description": "Counts the occurrences of a value in an array. Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array."
}
"snippet-createElement": {
"prefix": "createElement",
"body": "const createElement = str => {\n const el = document.createElement('div');\n el.innerHTML = str;\n return el.firstElementChild;\n};",
"description": "Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned. Use `document.createElement()` to create a new element. Set its `innerHTML` to the string supplied as the argument. Use `ParentNode.firstElementChild` to return the element version of the string."
}
"snippet-createEventHub": {
"prefix": "createEventHub",
"body": "const createEventHub = () => ({\n hub: Object.create(null),\n emit(event, data) {\n (this.hub[event] || []).forEach(handler => handler(data));\n }\n on(event, handler) {\n if (!this.hub[event]) this.hub[event] = [];\n this.hub[event].push(handler);\n }\n off(event, handler) {\n const i = (this.hub[event] || []).findIndex(h => h === handler);\n if (i > -1) this.hub[event].splice(i, 1);\n }\n});",
"description": "Creates a pub/sub ([publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods. Use `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`. For `emit`, resolve the array of handlers based on the `event` argument and then run each one with `Array.forEach()` by passing in the data as an argument. For `on`, create an array for the event if it does not yet exist, then use `Array.push()` to add the handler to the array. For `off`, use `Array.findIndex()` to find the index of the handler in the event array and remove it using `Array.splice()`."
}
"snippet-currentUrl": {
"prefix": "currentUrl",
"body": "const currentURL = () => window.location.href;",
"description": "Returns the current URL. Use `window.location.href` to get current URL."
}
"snippet-curry": {
"prefix": "curry",
"body": "const curry = (fn, arity = fn.length, ...args) =>\n arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);",
"description": "Curries a function. Use recursion. If the number of provided arguments (`args`) is sufficient, call the passed function `fn`. Otherwise, return a curried function `fn` 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. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`."
}
"snippet-decapitalize": {
"prefix": "decapitalize",
"body": "const decapitalize = ([first, ...rest], upperRest = false) =>\n first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));",
"description": "Decapitalizes the first letter of a string. Use array destructuring and `String.toLowerCase()` to decapitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again. Omit the `upperRest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase."
}
"snippet-deepClone": {
"prefix": "deepClone",
"body": "const deepClone = obj => {\n let clone = Object.assign({} obj);\n Object.keys(clone).forEach(\n key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])\n );\n return clone;\n};",
"description": "Creates a deep clone of an object. Use recursion. Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original. Use `Object.keys()` and `Array.forEach()` to determine which key-value pairs need to be deep cloned."
}
"snippet-deepFlatten": {
"prefix": "deepFlatten",
"body": "const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));",
"description": "Deep flattens an array. Use recursion. Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. Recursively flatten each element that is an array."
}
"snippet-defaults": {
"prefix": "defaults",
"body": "const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);",
"description": "Assigns default values for all properties in an object that are `undefined`. Use `Object.assign()` to create a new empty object and copy the original one to maintain key order, use `Array.reverse()` and the spread operator `...` to combine the default values from left to right, finally use `obj` again to overwrite properties that originally had a value."
}
"snippet-defer": {
"prefix": "defer",
"body": "const defer = (fn, ...args) => setTimeout(fn, 1, ...args);",
"description": "Defers invoking a function until the current call stack has cleared. Use `setTimeout()` 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 (`...`) operator to supply the function with an arbitrary number of arguments."
}
"snippet-delay": {
"prefix": "delay",
"body": "const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);",
"description": "Invokes the provided function after `wait` milliseconds. Use `setTimeout()` to delay execution of `fn`. Use the spread (`...`) operator to supply the function with an arbitrary number of arguments."
}
"snippet-detectDeviceType": {
"prefix": "detectDeviceType",
"body": "const detectDeviceType = () =>\n /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)\n ? 'Mobile'\n : 'Desktop';",
"description": "Detects wether the website is being opened in a mobile device or a desktop/laptop. Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop."
}
"snippet-difference": {
"prefix": "difference",
"body": "const difference = (a, b) => {\n const s = new Set(b);\n return a.filter(x => !s.has(x));\n};",
"description": " Returns the difference between two arrays. Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`."
}
"snippet-differenceBy": {
"prefix": "differenceBy",
"body": "const differenceBy = (a, b, fn) => {\n const s = new Set(b.map(v => fn(v)));\n return a.filter(x => !s.has(fn(x)));\n};",
"description": " Returns the difference between two arrays, after applying the provided function to each array element of both. Create a `Set` by applying `fn` to each element in `b`, then use `Array.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set."
}
"snippet-differenceWith": {
"prefix": "differenceWith",
"body": "const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);",
"description": "Filters out all values from an array for which the comparator function does not return `true`. Use `Array.filter()` and `Array.findIndex()` to find the appropriate values."
}
"snippet-digitize": {
"prefix": "digitize",
"body": "const digitize = n => [...`${n}`].map(i => parseInt(i));",
"description": "Converts a number to an array of digits. Convert the number to a string, using the spread operator (`...`) to build an array. Use `Array.map()` and `parseInt()` to transform each value to an integer."
}
"snippet-distance": {
"prefix": "distance",
"body": "const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);",
"description": "Returns the distance between two points. Use `Math.hypot()` to calculate the Euclidean distance between two points."
}
"snippet-drop": {
"prefix": "drop",
"body": "const drop = (arr, n = 1) => arr.slice(n);",
"description": "Returns a new array with `n` elements removed from the left. Use `Array.slice()` to slice the remove the specified number of elements from the left."
}
"snippet-dropRight": {
"prefix": "dropRight",
"body": "const dropRight = (arr, n = 1) => arr.slice(0, -n);",
"description": "Returns a new array with `n` elements removed from the right. Use `Array.slice()` to slice the remove the specified number of elements from the right."
}
"snippet-dropRightWhile": {
"prefix": "dropRightWhile",
"body": "const dropRightWhile = (arr, func) => {\n while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);\n return arr;\n};",
"description": "Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array. Loop through the array, using `Array.slice()` to drop the last element of the array until the returned value from the function is `true`. Returns the remaining elements."
}
"snippet-dropWhile": {
"prefix": "dropWhile",
"body": "const dropWhile = (arr, func) => {\n while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);\n return arr;\n};",
"description": "Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array. Loop through the array, using `Array.slice()` to drop the first element of the array until the returned value from the function is `true`. Returns the remaining elements."
}
"snippet-elementIsVisibleInViewport": {
"prefix": "elementIsVisibleInViewport",
"body": "const elementIsVisibleInViewport = (el, partiallyVisible = false) => {\n const { top, left, bottom, right } = el.getBoundingClientRect();\n const { innerHeight, innerWidth } = window;\n return partiallyVisible\n ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&\n ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))\n : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;\n};",
"description": "Returns `true` if the element specified is visible in the viewport, `false` otherwise. Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values to determine if a given element is visible in the viewport. Omit the second argument to determine if the element is entirely visible, or specify `true` to determine if it is partially visible."
}
"snippet-elo": {
"prefix": "elo",
"body": "const elo = ([...ratings], kFactor = 32, selfRating) => {\n const [a, b] = ratings;\n const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));\n const newRating = (rating, i) =>\n (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));\n if (ratings.length === 2) {\n return [newRating(a, 1), newRating(b, 0)];\n } else {\n for (let i = 0; i < ratings.length; i++) {\n let j = i;\n while (j < ratings.length - 1) {\n [ratings[i], ratings[j + 1]] = elo([ratings[i], ratings[j + 1]], kFactor);\n j++;\n }\n }\n }\n return ratings;\n};",
"description": "Computes the new ratings between two or more opponents using the [Elo rating system](https://en.wikipedia.org/wiki/Elo_rating_system). It takes an array of pre-ratings and returns an array containing post-ratings. The array should be ordered from best performer to worst performer (winner -> loser). Use the exponent `**` operator and math operators to compute the expected score (chance of winning). of each opponent and compute the new rating for each. Loop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion. Omit the second argument to use the default `kFactor` of 32."
}
"snippet-equals": {
"prefix": "equals",
"body": "const equals = (a, b) => {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (!a || !b || (typeof a != 'object' && typeof b !== 'object')) return a === b;\n if (a === null || a === undefined || b === null || b === undefined) return false;\n if (a.prototype !== b.prototype) return false;\n let keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n return keys.every(k => equals(a[k], b[k]));\n};",
"description": "Performs a deep comparison between two values to determine if they are equivalent. Check if the two values are identical, if they are both `Date` objects with the same time, using `Date.getTime()` or if they are both non-object values with an equivalent value (strict comparison). Check if only one value is `null` or `undefined` or if their prototypes differ. If none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys, then use `Array.every()` to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively."
}
"snippet-escapeHTML": {
"prefix": "escapeHTML",
"body": "const escapeHTML = str =>\n str.replace(\n /[&<>'\"]/g,\n tag =>\n ({\n '&': '&',\n '<': '<',\n '>': '>',\n \"'\": ''',\n '\"': '"'\n }[tag] || tag)\n );",
"description": "Escapes a string for use in HTML. Use `String.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object)."
}
"snippet-escapeRegExp": {
"prefix": "escapeRegExp",
"body": "const escapeRegExp = str => str.replace(/[.*+?^${}()|[\\]\\]/g, '\\\\$&');",
"description": "Escapes a string to use in a regular expression. Use `String.replace()` to escape special characters."
}
"snippet-everyNth": {
"prefix": "everyNth",
"body": "const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);",
"description": "Returns every nth element in an array. Use `Array.filter()` to create a new array that contains every nth element of a given array."
}
"snippet-extendhex": {
"prefix": "extendhex",
"body": "const extendHex = shortHex =>\n '#' +\n shortHex\n .slice(shortHex.startsWith('#') ? 1 : 0)\n .split('')\n .map(x => x + x)\n .join('');",
"description": "Extends a 3-digit color code to a 6-digit color code. Use `Array.map()`, `String.split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form. `Array.slice()` is used to remove `#` from string start since it's added once."
}
"snippet-factorial": {
"prefix": "factorial",
"body": "const factorial = n =>\n n < 0\n ? (() => {\n throw new TypeError('Negative numbers are not allowed!');\n })()\n : n <= 1 ? 1 : n * factorial(n - 1);",
"description": "Calculates the factorial of a number. Use recursion. If `n` is less than or equal to `1`, return `1`. Otherwise, return the product of `n` and the factorial of `n - 1`. Throws an exception if `n` is a negative number."
}
"snippet-fibonacci": {
"prefix": "fibonacci",
"body": "const fibonacci = n =>\n Array.from({ length: n }).reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n );",
"description": "Generates an array, containing the Fibonacci sequence, up until the nth term. Create an empty array of the specific length, initializing the first two values (`0` and `1`). Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two."
}
"snippet-filterNonUnique": {
"prefix": "filterNonUnique",
"body": "const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));",
"description": "Filters out the non-unique values in an array. Use `Array.filter()` for an array containing only the unique values."
}
"snippet-findkey": {
"prefix": "findkey",
"body": "const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));",
"description": "Returns the first key that satisfies the provided testing function. Otherwise `undefined` is returned. Use `Object.keys(obj)` to get all the properties of the object, `Array.find()` to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object."
}
"snippet-findLast": {
"prefix": "findLast",
"body": "const findLast = (arr, fn) => arr.filter(fn).slice(-1)[0];",
"description": " Returns the last element for which the provided function returns a truthy value. Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.slice(-1)` to get the last one."
}
"snippet-findLastIndex": {
"prefix": "findLastIndex",
"body": "const findLastIndex = (arr, fn) =>\n arr\n .map((val, i) => [i, val])\n .filter(val => fn(val[1], val[0], arr))\n .slice(-1)[0][0];",
"description": "Returns the index of the last element for which the provided function returns a truthy value. Use `Array.map()` to map each element to an array with its index and value. Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.slice(-1)` to get the last one."
}
"snippet-findLastKey": {
"prefix": "findLastKey",
"body": "const findLastKey = (obj, fn) =>\n Object.keys(obj)\n .reverse()\n .find(key => fn(obj[key], key, obj));",
"description": "Returns the last key that satisfies the provided testing function. Otherwise `undefined` is returned. Use `Object.keys(obj)` to get all the properties of the object, `Array.reverse()` to reverse their order and `Array.find()` to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object."
}
"snippet-flatten": {
"prefix": "flatten",
"body": "const flatten = (arr, depth = 1) =>\n depth != 1\n ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), [])\n : arr.reduce((a, v) => a.concat(v), []);",
"description": "Flattens an array up to the specified depth. Use recursion, decrementing `depth` by 1 for each level of depth. Use `Array.reduce()` and `Array.concat()` to merge elements or arrays. Base case, for `depth` equal to `1` stops recursion. Omit the second argument, `depth` to flatten only to a depth of `1` (single flatten)."
}
"snippet-flip": {
"prefix": "flip",
"body": "const flip = fn => (first, ...rest) => fn(...rest, first);",
"description": "Flip takes a function as an argument, then makes the first argument the last. Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest."
}
"snippet-forEachRight": {
"prefix": "forEachRight",
"body": "const forEachRight = (arr, callback) =>\n arr\n .slice(0)\n .reverse()\n .forEach(callback);",
"description": "Executes a provided function once for each array element, starting from the array's last element. Use `Array.slice(0)` to clone the given array, `Array.reverse()` to reverse it and `Array.forEach()` to iterate over the reversed array."
}
"snippet-formatDuration": {
"prefix": "formatDuration",
"body": "const formatDuration = ms => {\n if (ms < 0) ms = -ms;\n const time = {\n day: Math.floor(ms / 86400000),\n hour: Math.floor(ms / 3600000) % 24,\n minute: Math.floor(ms / 60000) % 60,\n second: Math.floor(ms / 1000) % 60,\n millisecond: Math.floor(ms) % 1000\n };\n return Object.entries(time)\n .filter(val => val[1] !== 0)\n .map(val => val[1] + ' ' + (val[1] !== 1 ? val[0] + 's' : val[0]))\n .join(', ');\n};",
"description": "Returns the human readable format of the given number of milliseconds. Divide `ms` with the appropriate values to obtain the appropriate values for `day`, `hour`, `minute`, `second` and `millisecond`. Use `Object.entries()` with `Array.filter()` to keep only non-zero values. Use `Array.map()` to create the string for each value, pluralizing appropriately. Use `String.join(', ')` to combine the values into a string."
}
"snippet-forOwn": {
"prefix": "forOwn",
"body": "const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));",
"description": "Iterates over all own properties of an object, running a callback for each one. Use `Object.keys(obj)` to get all the properties of the object, `Array.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object."
}
"snippet-forOwnRight": {
"prefix": "forOwnRight",
"body": "const forOwnRight = (obj, fn) =>\n Object.keys(obj)\n .reverse()\n .forEach(key => fn(obj[key], key, obj));",
"description": "Iterates over all own properties of an object in reverse, running a callback for each one. Use `Object.keys(obj)` to get all the properties of the object, `Array.reverse()` to reverse their order and `Array.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object."
}
"snippet-fromCamelCase": {
"prefix": "fromCamelCase",
"body": "const fromCamelCase = (str, separator = '_') =>\n str\n .replace(/([a-z\\d])([A-Z])/g, '$1' + separator + '$2')\n .replace(/([A-Z]+)([A-Z][a-z\\d]+)/g, '$1' + separator + '$2')\n .toLowerCase();",
"description": "Converts a string from camelcase. Use `String.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase. Omit the second argument to use a default `separator` of `_`."
}
"snippet-functionName": {
"prefix": "functionName",
"body": "const functionName = fn => (console.debug(fn.name), fn);",
"description": "Logs the name of a function. Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console."
}
"snippet-functions": {
"prefix": "functions",
"body": "const functions = (obj, inherited = false) =>\n (inherited\n ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))]\n : Object.keys(obj)\n ).filter(key => typeof obj[key] === 'function');",
"description": "Returns an array of function property names from own (and optionally inherited) enumerable properties of an object. Use `Object.keys(obj)` to iterate over the object's own properties. If `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties. Use `Array.filter()` to keep only those properties that are functions. Omit the second argument, `inherited`, to not include inherited properties by default."
}
"snippet-gcd": {
"prefix": "gcd",
"body": "const gcd = (...arr) => {\n const _gcd = (x, y) => (!y ? x : gcd(y, x % y));\n return [...arr].reduce((a, b) => _gcd(a, b));\n};",
"description": "Calculates the greatest common divisor between two or more numbers/arrays. The inner `_gcd` function uses recursion. Base case is when `y` equals `0`. In this case, return `x`. Otherwise, return the GCD of `y` and the remainder of the division `x/y`."
}
"snippet-geometricProgression": {
"prefix": "geometricProgression",
"body": "const geometricProgression = (end, start = 1, step = 2) =>\n Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(\n (v, i) => start * step ** i\n );",
"description": "Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`. Returns an error if `step` equals `1`. Use `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. Omit the second argument, `start`, to use a default value of `1`. Omit the third argument, `step`, to use a default value of `2`."
}
"snippet-get": {
"prefix": "get",
"body": "const get = (from, ...selectors) =>\n [...selectors].map(s =>\n s\n .replace(\/\\[([^[\\]]*)]\/g, '.$1.')\n .split('.')\n .filter(t => t !== '')\n .reduce((prev, cur) => prev && prev[cur], from)\n );",
"description": " Retrieve a set of properties indicated by the given selectors from an object. Use `Array.map()` for each selector, `String.replace()` to replace square brackets with dots, `String.split('.')` to split each selector, `Array.filter()` to remove empty values and `Array.reduce()` to get the value indicated by it."
}
"snippet-getDaysDiffBetweenDates": {
"prefix": "getDaysDiffBetweenDates",
"body": "const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>\n (dateFinal - dateInitial) / (1000 * 3600 * 24);",
"description": "Returns the difference (in days) between two dates. Calculate the difference (in days) between two `Date` objects."
}
"snippet-getScrollPosition": {
"prefix": "getScrollPosition",
"body": "const getScrollPosition = (el = window) => ({\n x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,\n y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop\n});",
"description": "Returns the scroll position of the current page. Use `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`. You can omit `el` to use a default value of `window`."
}
"snippet-getStyle": {
"prefix": "getStyle",
"body": "const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];",
"description": "Returns the value of a CSS rule for the specified element. Use `Window.getComputedStyle()` to get the value of the CSS rule for the specified element."
}
"snippet-getType": {
"prefix": "getType",
"body": "const getType = v =>\n v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();",
"description": "Returns the native type of a value. Returns lowercased constructor name of value, `\"undefined\"` or `\"null\"` if value is `undefined` or `null`."
}
"snippet-getURLParameters": {
"prefix": "getURLParameters",
"body": "const getURLParameters = url =>\n (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(\n (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),\n {}\n );",
"description": "Returns an object containing the parameters of the current URL. Use `String.match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object. Pass `location.search` as the argument to apply to the current `url`."
}
"snippet-groupby": {
"prefix": "groupby",
"body": "const groupBy = (arr, fn) =>\n arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {\n acc[val] = (acc[val] || []).concat(arr[i]);\n return acc;\n }, {});",
"description": "Groups the elements of an array based on the given function. Use `Array.map()` to map the values of an array to a function or property name. Use `Array.reduce()` to create an object, where the keys are produced from the mapped results."
}
"snippet-hammingDistance": {
"prefix": "hammingDistance",
"body": "const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;",
"description": "Calculates the Hamming distance between two values. Use XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`. Count and return the number of `1`s in the string, using `match(/1/g)`."
}
"snippet-hasClass": {
"prefix": "hasClass",
"body": "const hasClass = (el, className) => el.classList.contains(className);",
"description": "Returns `true` if the element has the specified class, `false` otherwise. Use `element.classList.contains()` to check if the element has the specified class."
}
"snippet-hasFlags": {
"prefix": "hasFlags",
"body": "const hasFlags = (...flags) =>\n flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));",
"description": "Check if the current process's arguments contain the specified flags. Use `Array.every()` and `Array.includes()` to check if `process.argv` contains all the specified flags. Use a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly."
}
"snippet-hashBrowser": {
"prefix": "hashBrowser",
"body": "const hashBrowser = val =>\n crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => {\n let hexes = [],\n view = new DataView(h);\n for (let i = 0; i < view.byteLength; i += 4)\n hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));\n return hexes.join('');\n });",
"description": "Creates a hash for a value using the [SHA-256](https://en.wikipedia.org/wiki/SHA-2) algorithm. Returns a promise. Use the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) API to create a hash for the given value."
}
"snippet-hashNode": {
"prefix": "hashNode",
"body": "const crypto = require('crypto');\nconst hashNode = val =>\n new Promise(resolve =>\n setTimeout(\n () =>\n resolve(\n crypto\n .createHash('sha256')\n .update(val)\n .digest('hex')\n ),\n 0\n )\n );",
"description": "Creates a hash for a value using the [SHA-256](https://en.wikipedia.org/wiki/SHA-2) algorithm. Returns a promise. Use `crypto` API to create a hash for the given value."
}
"snippet-head": {
"prefix": "head",
"body": "const head = arr => arr[0];",
"description": "Returns the head of a list. Use `arr[0]` to return the first element of the passed array."
}
"snippet-hexToRGB": {
"prefix": "hexToRGB",
"body": "const hexToRGB = hex => {\n let alpha = false,\n h = hex.slice(hex.startsWith('#') ? 1 : 0);\n if (h.length === 3) h = [...h].map(x => x + x).join('');\n else if (h.length === 8) alpha = true;\n h = parseInt(h, 16);\n return (\n 'rgb' +\n (alpha ? 'a' : '') +\n '(' +\n (h >>> (alpha ? 24 : 16)) +\n ', ' +\n ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) +\n ', ' +\n ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +\n (alpha ? `, ${h & 0x000000ff}` : '') +\n ')'\n );\n};",
"description": "Converts a color code to a `rgb()` or `rgba()` string if alpha value is provided. Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If an alpha value is provided alongside 6-digit hex, give `rgba()` string in return."
}
"snippet-hide": {
"prefix": "hide",
"body": "const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));",
"description": "Hides all the elements specified. Use the spread operator (`...`) and `Array.forEach()` to apply `display: none` to each element specified."
}
"snippet-httpGet": {
"prefix": "httpGet",
"body": "const httpGet = (url, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open('GET', url, true);\n request.onload = () => callback(request.responseText);\n request.onerror = () => err(request);\n request.send();\n};",
"description": "Makes a `GET` request to the passed URL. Use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `get` request to the given `url`. Handle the `onload` event, by calling the given `callback` the `responseText`. Handle the `onerror` event, by running the provided `err` function. Omit the third argument, `err`, to log errors to the console's `error` stream by default."
}
"snippet-httpPost": {
"prefix": "httpPost",
"body": "const httpPost = (url, data, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open('POST', url, true);\n request.setRequestHeader('Content-type', 'application/json; charset=utf-8');\n request.onload = () => callback(request.responseText);\n request.onerror = () => err(request);\n request.send(data);\n};",
"description": "Makes a `POST` request to the passed URL. Use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `post` request to the given `url`. Set the value of an `HTTP` request header with `setRequestHeader` method. Handle the `onload` event, by calling the given `callback` the `responseText`. Handle the `onerror` event, by running the provided `err` function. Omit the third argument, `data`, to send no data to the provided `url`. Omit the fourth argument, `err`, to log errors to the console's `error` stream by default."
}
"snippet-httpsRedirect": {
"prefix": "httpsRedirect",
"body": "const httpsRedirect = () => {\n if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);\n};",
"description": "Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history. Use `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.split()` and remove the protocol part of the URL."
}
"snippet-indexOfAll": {
"prefix": "indexOfAll",
"body": "const indexOfAll = (arr, val) => {\n const indices = [];\n arr.forEach((el, i) => el === val && indices.push(i));\n return indices;\n};",
"description": "Returns all indices of `val` in an array. If `val` never occurs, returns `[]`. Use `Array.forEach()` to loop over elements and `Array.push()` to store indices for matching elements. Return the array of indices."
}
"snippet-initial": {
"prefix": "initial",
"body": "const initial = arr => arr.slice(0, -1);",
"description": "Returns all the elements of an array except the last one. Use `arr.slice(0,-1)` to return all but the last element of the array."
}
"snippet-initialize2DArray": {
"prefix": "initialize2DArray",
"body": "const initialize2DArray = (w, h, val = null) =>\n Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));",
"description": "Initializes a 2D array of given width and height and value. Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`."
}
"snippet-initializeArrayWithRange": {
"prefix": "initializeArrayWithRange",
"body": "const initializeArrayWithRange = (end, start = 0, step = 1) =>\n Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start);",
"description": "Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`. Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range. You can omit `start` to use a default value of `0`. You can omit `step` to use a default value of `1`."
}
"snippet-initializeArrayWithRangeRight": {
"prefix": "initializeArrayWithRangeRight",
"body": "const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>\n Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(\n (v, i, arr) => (arr.length - i - 1) * step + start\n );",
"description": "Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`. Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range. You can omit `start` to use a default value of `0`. You can omit `step` to use a default value of `1`."
}
"snippet-initializeArrayWithValues": {
"prefix": "initializeArrayWithValues",
"body": "const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);",
"description": "Initializes and fills an array with the specified values. Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values. You can omit `val` to use a default value of `0`."
}
"snippet-inRange": {
"prefix": "inRange",
"body": "const inRange = (n, start, end = null) => {\n if (end && start > end) end = [start, (start = end)][0];\n return end == null ? n >= 0 && n < start : n >= start && n < end;\n};",
"description": "Checks if the given number falls within the given range. Use arithmetic comparison to check if the given number is in the specified range. If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`."
}
"snippet-intersection": {
"prefix": "intersection",
"body": "const intersection = (a, b) => {\n const s = new Set(b);\n return a.filter(x => s.has(x));\n};",
"description": "Returns a list of elements that exist in both arrays. Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`."
}
"snippet-intersectionBy": {
"prefix": "intersectionBy",
"body": "const intersectionBy = (a, b, fn) => {\n const s = new Set(b.map(x => fn(x)));\n return a.filter(x => s.has(fn(x)));\n};",
"description": "Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both. Create a `Set` by applying `fn` to all elements in `b`, then use `Array.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them."
}
"snippet-intersectionWith": {
"prefix": "intersectionWith",
"body": "const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);",
"description": "Returns a list of elements that exist in both arrays, using a provided comparator function. Use `Array.filter()` and `Array.findIndex()` in combination with the provided comparator to determine intersecting values."
}
"snippet-invertKeyValues": {
"prefix": "invertKeyValues",
"body": "const invertKeyValues = (obj, fn) =>\n Object.keys(obj).reduce((acc, key) => {\n const val = fn ? fn(obj[key]) : obj[key];\n acc[val] = acc[val] || [];\n acc[val].push(key);\n return acc;\n }, {});",
"description": "Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key. Use `Object.keys()` and `Array.reduce()` to invert the key-value pairs of an object and apply the function provided (if any). Omit the second argument, `fn`, to get the inverted keys without applying a function to them."
}
"snippet-is": {
"prefix": "is",
"body": "const is = (type, val) => val instanceof type;",
"description": "Checks if the provided value is of the specified type (doesn't work with literals). Use the `instanceof` operator to check if the provided value is of the specified `type`."
}
"snippet-isAbsoluteURL": {
"prefix": "isAbsoluteURL",
"body": "const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);",
"description": "Returns `true` if the given string is an absolute URL, `false` otherwise. Use a regular expression to test if the string is an absolute URL."
}
"snippet-isArrayLike": {
"prefix": "isArrayLike",
"body": "const isArrayLike = val => {\n try {\n return [...val], true;\n } catch (e) {\n return false;\n }\n};",
"description": "Checks if the provided argument is array-like (i.e. is iterable). Use the spread operator (`...`) to check if the provided argument is iterable inside a `try... catch` block and the comma operator (`,`) to return the appropriate value."
}
"snippet-isBoolean": {
"prefix": "isBoolean",
"body": "const isBoolean = val => typeof val === 'boolean';",
"description": "Checks if the given argument is a native boolean element. Use `typeof` to check if a value is classified as a boolean primitive."
}
"snippet-isDivisible": {
"prefix": "isDivisible",
"body": "const isDivisible = (dividend, divisor) => dividend % divisor === 0;",
"description": "Checks if the first numeric argument is divisible by the second one. Use the modulo operator (`%`) to check if the remainder is equal to `0`."
}
"snippet-isEmpty": {
"prefix": "isEmpty",
"body": "const isEmpty = val => val == null || !(Object.keys(val) || val).length;",
"description": "Returns true if the a value is an empty object, collection, map or set, has no enumerable properties or is any type that is not considered a collection. Check if the provided value is `null` or if its `length` is equal to `0`."
}
"snippet-isEven": {
"prefix": "isEven",
"body": "const isEven = num => num % 2 === 0;",
"description": "Returns `true` if the given number is even, `false` otherwise. Checks whether a number is odd or even using the modulo (`%`) operator. Returns `true` if the number is even, `false` if the number is odd."
}
"snippet-isFunction": {
"prefix": "isFunction",
"body": "const isFunction = val => typeof val === 'function';",
"description": "Checks if the given argument is a function. Use `typeof` to check if a value is classified as a function primitive."
}
"snippet-isLowerCase": {
"prefix": "isLowerCase",
"body": "const isLowerCase = str => str === str.toLowerCase();",
"description": "Checks if a string is lower case. Convert the given string to lower case, using `String.toLowerCase()` and compare it to the original."
}
"snippet-isNil": {
"prefix": "isNil",
"body": "const isNil = val => val === undefined || val === null;",
"description": "Returns `true` if the specified value is `null` or `undefined`, `false` otherwise. Use the strict equality operator to check if the value and of `val` are equal to `null` or `undefined`."
}
"snippet-isNull": {
"prefix": "isNull",
"body": "const isNull = val => val === null;",
"description": "Returns `true` if the specified value is `null`, `false` otherwise. Use the strict equality operator to check if the value and of `val` are equal to `null`."
}
"snippet-isNumber": {
"prefix": "isNumber",
"body": "const isNumber = val => typeof val === 'number';",
"description": "Checks if the given argument is a number. Use `typeof` to check if a value is classified as a number primitive."
}
"snippet-isObject": {
"prefix": "isObject",
"body": "const isObject = obj => obj === Object(obj);",
"description": "Returns a boolean determining if the passed value is an object or not. Uses the `Object` constructor to create an object wrapper for the given value. If the value is `null` or `undefined`, create and return an empty object. Οtherwise, return an object of a type that corresponds to the given value."
}
"snippet-isObjectLike": {
"prefix": "isObjectLike",
"body": "```js\nconst isObjectLike = val => val !== null && typeof val === 'object';",
"description": "Checks if a value is object-like. Check if the provided value is not `null` and its `typeof` is equal to `'object'`."
}
"snippet-isPlainObject": {
"prefix": "isPlainObject",
"body": "const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;",
"description": "Checks if the provided value is an bbject created by the Object constructor. Check if the provided value is truthy, use `typeof` to check if it is an object and `Object.constructor` to make sure the constructor is equal to `Object`."
}
"snippet-isPrime": {
"prefix": "isPrime",
"body": "const isPrime = num => {\n const boundary = Math.floor(Math.sqrt(num));\n for (var i = 2; i <= boundary; i++) if (num % i == 0) return false;\n return num >= 2;\n};",
"description": " Checks if the provided integer is a prime number. Check numbers from `2` to the square root of the given number. Return `false` if any of them divides the given number, else return `true`, unless the number is less than `2`."
}
"snippet-isPrimitive": {
"prefix": "isPrimitive",
"body": "const isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null;",
"description": "Returns a boolean determining if the passed value is primitive or not. Use `Array.includes()` on an array of type strings which are not primitive, supplying the type using `typeof`. Since `typeof null` evaluates to `'object'`, it needs to be directly compared."
}
"snippet-isPromiseLike": {
"prefix": "isPromiseLike",
"body": "const isPromiseLike = obj =>\n obj !== null &&\n (typeof obj === 'object' || typeof obj === 'function') &&\n typeof obj.then === 'function';",
"description": "Returns `true` if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), `false` otherwise. Check if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`."
}
"snippet-isSorted": {
"prefix": "isSorted",
"body": "const isSorted = arr => {\n const direction = arr[0] > arr[1] ? -1 : 1;\n for (let [i, val] of arr.entries())\n if (i === arr.length - 1) return direction;\n else if ((val - arr[i + 1]) * direction > 0) return 0;\n};",
"description": "Returns `1` if the array is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted. Calculate the ordering `direction` for the first two elements. Use `Object.entries()` to loop over array objects and compare them in pairs. Return `0` if the `direction` changes or the `direction` if the last element is reached."
}
"snippet-isString": {
"prefix": "isString",
"body": "const isString = val => typeof val === 'string';",
"description": " Checks if the given argument is a string. Use `typeof` to check if a value is classified as a string primitive."
}
"snippet-isSymbol": {
"prefix": "isSymbol",
"body": "const isSymbol = val => typeof val === 'symbol';",
"description": "Checks if the given argument is a symbol. Use `typeof` to check if a value is classified as a symbol primitive."
}
"snippet-isTravisCI": {
"prefix": "isTravisCI",
"body": "const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;",
"description": "Checks if the current environment is [Travis CI](https://travis-ci.org/). Checks if the current environment has the `TRAVIS` and `CI` environment variables ([reference](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables))."
}
"snippet-isUndefined": {
"prefix": "isUndefined",
"body": "const isUndefined = val => val === undefined;",
"description": "Returns `true` if the specified value is `undefined`, `false` otherwise. Use the strict equality operator to check if the value and of `val` are equal to `undefined`."
}
"snippet-isUpperCase": {
"prefix": "isUpperCase",
"body": "const isUpperCase = str => str === str.toUpperCase();",
"description": "Checks if a string is upper case. Convert the given string to upper case, using `String.toUpperCase()` and compare it to the original."
}
"snippet-isValidJSON": {
"prefix": "isValidJSON",
"body": "const isValidJSON = obj => {\n try {\n JSON.parse(obj);\n return true;\n } catch (e) {\n return false;\n }\n};",
"description": "Checks if the provided argument is a valid JSON. Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON."
}
"snippet-join": {
"prefix": "join",
"body": "const join = (arr, separator = ',', end = separator) =>\n arr.reduce(\n (acc, val, i) =>\n i == arr.length - 2\n ? acc + val + end\n : i == arr.length - 1 ? acc + val : acc + val + separator,\n ''\n );",
"description": "Joins all elements of an array into a string and returns this string. Uses a separator and an end separator. Use `Array.reduce()` to combine elements into a string. Omit the second argument, `separator`, to use a default separator of `','`. Omit the third argument, `end`, to use the same value as `separator` by default."
}
"snippet-JSONToFile": {
"prefix": "JSONToFile",
"body": "const fs = require('fs');\nconst JSONToFile = (obj, filename) =>\n fs.writeFile(`\\$\\{filename\\}.json`, JSON.stringify(obj, null, 2));",
"description": "Writes a JSON object to a file. Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file."
}
"snippet-last": {
"prefix": "last",
"body": "const last = arr => arr[arr.length - 1];",
"description": "Returns the last element in an array. Use `arr.length - 1` to compute the index of the last element of the given array and returning it."
}
"snippet-lcm": {
"prefix": "lcm",
"body": "const lcm = (...arr) => {\n const gcd = (x, y) => (!y ? x : gcd(y, x % y));\n const _lcm = (x, y) => x * y / gcd(x, y);\n return [...arr].reduce((a, b) => _lcm(a, b));\n};",
"description": " Returns the least common multiple of two or more numbers. Use the greatest common divisor (GCD) formula and the fact that `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple. The GCD formula uses recursion."
}
"snippet-longestItem": {
"prefix": "longestItem",
"body": "const longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0];",
"description": "Takes any number of iterable objects or objects with a `length` property and returns the longest one. Use `Array.sort()` to sort all arguments by `length`, return the first (longest) one."
}
"snippet-lowercaseKeys": {
"prefix": "lowercaseKeys",
"body": "const lowercaseKeys = obj =>\n Object.keys(obj).reduce((acc, key) => {\n acc[key.toLowerCase()] = obj[key];\n return acc;\n }, {});",
"description": "Creates a new object from the specified object, where all the keys are in lowercase. Use `Object.keys()` and `Array.reduce()` to create a new object from the specified object. Convert each key in the original object to lowercase, using `String.toLowerCase()`."
}
"snippet-luhnCheck": {
"prefix": "luhnCheck",
"body": "const luhnCheck = num => {\n let arr = (num + '')\n .split('')\n .reverse()\n .map(x => parseInt(x));\n let lastDigit = arr.splice(0, 1)[0];\n let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + (val * 2) % 9 || 9), 0);\n sum += lastDigit;\n return",
"description": "Implementation of the [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc. Use `String.split('')`, `Array.reverse()` and `Array.map()` in combination with `parseInt()` to obtain an array of digits. Use `Array.splice(0,1)` to obtain the last digit. Use `Array.reduce()` to implement the Luhn Algorithm. Return `true` if `sum` is divisible by `10`, `false` otherwise."
}
"snippet-mapKeys": {
"prefix": "mapKeys",
"body": "const mapKeys = (obj, fn) =>\n Object.keys(obj).reduce((acc, k) => {\n acc[fn(obj[k], k, obj)] = obj[k];\n return acc;\n }, {});",
"description": "Creates an object with keys generated by running the provided function for each key and the same values as the provided object. Use `Object.keys(obj)` to iterate over the object's keys. Use `Array.reduce()` to create a new object with the same values and mapped keys using `fn`."
}
"snippet-mapObject": {
"prefix": "mapObject",
"body": "const mapObject = (arr, fn) =>\n (a => (\n (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})\n ))();",
"description": "Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value. Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations)."
}
"snippet-mapValues": {
"prefix": "mapValues",
"body": "const mapValues = (obj, fn) =>\n Object.keys(obj).reduce((acc, k) => {\n acc[k] = fn(obj[k], k, obj);\n return acc;\n }, {});",
"description": "Creates an object with the same keys as the provided object and values generated by running the provided function for each value. Use `Object.keys(obj)` to iterate over the object's keys. Use `Array.reduce()` to create a new object with the same keys and mapped values using `fn`."
}
"snippet-mask": {
"prefix": "mask",
"body": "const mask = (cc, num = 4, mask = '*') =>\n ('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num);",
"description": "Replaces all but the last `num` of characters with the specified mask character. Use `String.slice()` to grab the portion of the characters that need to be masked and use `String.replace()` with a regexp to replace every character with the mask character. Concatenate the masked characters with the remaining unmasked portion of the string. Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string. Omit the third argument, `mask`, to use a default character of `'*'` for the mask."
}
"snippet-matches": {
"prefix": "matches",
"body": "const matches = (obj, source) =>\n Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);",
"description": "Compares two objects to determine if the first one contains equivalent property values to the second one. Use `Object.keys(source)` to get all the keys of the second object, then `Array.every()`, `Object.hasOwnProperty()` and strict comparison to determine if all keys exist in the first object and have the same values."
}
"snippet-matchesWith": {
"prefix": "matchesWith",
"body": "const matchesWith = (obj, source, fn) =>\n Object.keys(source).every(\n key =>\n obj.hasOwnProperty(key) && fn\n ? fn(obj[key], source[key], key, obj, source)\n : obj[key] == source[key]\n );",
"description": "Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function. Use `Object.keys(source)` to get all the keys of the second object, then `Array.every()`, `Object.hasOwnProperty()` and the provided function to determine if all keys exist in the first object and have equivalent values. If no function is provided, the values will be compared using the equality operator."
}
"snippet-maxBy": {
"prefix": "maxBy",
"body": "const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));",
"description": "Returns the maximum value of an array, after mapping each element to a value using the provided function. Use `Array.map()` to map each element to the value returned by `fn`, `Math.max()` to get the maximum value."
}
"snippet-maxN": {
"prefix": "maxN",
"body": "const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);",
"description": "Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in descending order). Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order. Use `Array.slice()` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array."
}
"snippet-median": {
"prefix": "median",
"body": "const median = arr => { \n const mid = Math.floor(arr.length / 2),\n nums = [...arr].sort((a, b) => a - b);\n return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;\n };",
"description": "Returns the median of an array of numbers. Find the middle of the array, use `Array.sort()` to sort the values. Return the number at the midpoint if `length` is odd, otherwise the average of the two middle numbers."
}
"snippet-memoize": {
"prefix": "memoize",
"body": "const memoize = fn => {\n const cache = new Map();\n const cached = function(val) {\n return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);\n };\n cached.cache = cache;\n return cached;\n};",
"description": "Returns the memoized (cached) function. Create an empty cache by instantiating a new `Map` 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 `function` keyword must be used in order to allow the memoized function to have its `this` context changed if necessary. Allow access to the `cache` by setting it as a property on the returned function."
}
"snippet-merge": {
"prefix": "merge",
"body": "const merge = (...objs) =>\n [...objs].reduce(\n (acc, obj) =>\n Object.keys(obj).reduce((a, k) => {\n acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];\n return acc;\n }, {}),\n {}\n );",
"description": "Creates a new object from the combination of two or more objects. Use `Array.reduce()` combined with `Object.keys(obj)` to iterate over all objects and keys. Use `hasOwnProperty()` and `Array.concat()` to append values for keys existing in multiple objects."
}
"snippet-minBy": {
"prefix": "minBy",
"body": "const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));",
"description": "Returns the minimum value of an array, after mapping each element to a value using the provided function. Use `Array.map()` to map each element to the value returned by `fn`, `Math.min()` to get the maximum value."
}
"snippet-minN": {
"prefix": "minN",
"body": "const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);",
"description": "Returns the `n` minimum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in ascending order). Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order. Use `Array.slice()` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array."
}
"snippet-negate": {
"prefix": "negate",
"body": "const negate = func => (...args) => !func(...args);",
"description": "Negates a predicate function. Take a predicate function and apply the not operator (`!`) to it with its arguments."
}
"snippet-nthArg": {
"prefix": "nthArg",
"body": "const nthArg = n => (...args) => args.slice(n)[0];",
"description": "Creates a function that gets the argument at index `n`. If `n` is negative, the nth argument from the end is returned. Use `Array.slice()` to get the desired argument at index `n`."
}
"snippet-nthElement": {
"prefix": "nthElement",
"body": "const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];",
"description": "Returns the nth element of an array. Use `Array.slice()` to get an array containing the nth element at the first place. If the index is out of bounds, return `[]`. Omit the second argument, `n`, to get the first element of the array."
}
"snippet-objectFromPairs": {
"prefix": "objectFromPairs",
"body": "const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {});",
"description": "Creates an object from the given key-value pairs. Use `Array.reduce()` to create and combine key-value pairs."
}
"snippet-objectToPairs": {
"prefix": "objectToPairs",
"body": "const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);",
"description": "Creates an array of key-value pair arrays from an object. Use `Object.keys()` and `Array.map()` to iterate over the object's keys and produce an array with key-value pairs."
}
"snippet-observeMutations": {
"prefix": "observeMutations",
"body": "const observeMutations = (element, callback, options) => {\n const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m)));\n observer.observe(\n element,\n Object.assign(\n {\n childList: true,\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n subtree: true\n },\n options\n )\n );\n return observer;\n};",
"description": " Returns a new MutationObserver and runs the provided callback for each mutation on the specified element. Use a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to observe mutations on the given element. Use `Array.forEach()` to run the callback for each mutation that is observed. Omit the third argument, `options`, to use the default [options](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationObserverInit) (all `true`)."
}
"snippet-off": {
"prefix": "off",
"body": "const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);",
"description": "Removes an event listener from an element. Use `EventTarget.removeEventListener()` to remove an event listener from an element. Omit the fourth argument `opts` to use `false` or specify it based on the options used when the event listener was added."
}
"snippet-omit": {
"prefix": "omit",
"body": "const omit = (obj, arr) =>\n Object.keys(obj)\n .filter(k => !arr.includes(k))\n .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});",
"description": "Omits the key-value pairs corresponding to the given keys from an object. Use `Object.keys(obj)`, `Array.filter()` and `Array.includes()` to remove the provided keys. Use `Array.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs."
}
"snippet-omitBy": {
"prefix": "omitBy",
"body": "const omitBy = (obj, fn) =>\n Object.keys(obj)\n .filter(k => !fn(obj[k], k))\n .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});",
"description": "Creates an object composed of the properties the given function returns falsey for. The function is invoked with two arguments: (value, key). Use `Object.keys(obj)` and `Array.filter()`to remove the keys for which `fn` returns a truthy value. Use `Array.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs."
}
"snippet-on": {
"prefix": "on",
"body": "const on = (el, evt, fn, opts = {}) => {\n const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e);\n el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);\n if (opts.target) return delegatorFn;\n};",
"description": "Adds an event listener to an element with the ability to use event delegation. Use `EventTarget.addEventListener()` to add an event listener to an element. If there is a `target` property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct `this` context. Returns a reference to the custom delegator function, in order to be possible to use with [`off`](#off). Omit `opts` to default to non-delegation behavior and event bubbling."
}
"snippet-once": {
"prefix": "once",
"body": "const once = fn => {\n let called = false;\n return function(...args) {\n if (called) return;\n called = true;\n return fn.apply(this, args);\n };\n};",
"description": "Ensures a function is called only once. Utilizing a closure, use a flag, `called`, and set it to `true` once the function is called for the first time, preventing it from being called again. In order to allow the function to have its `this` context changed (such as in an event listener), the `function` 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 (`...`) operator."
}
"snippet-onUserInputChange": {
"prefix": "onUserInputChange",
"body": "const onUserInputChange = callback => {\n let type = 'mouse',\n lastTime = 0;\n const mousemoveHandler = () => {\n const now = performance.now();\n if (now - lastTime < 20)\n (type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler);\n lastTime = now;\n };\n document.addEventListener('touchstart', () => {\n if (type === 'touch') return;\n (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler);\n });\n};",
"description": "Run the callback whenever the user input type changes (`mouse` or `touch`). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops). Use two event listeners. Assume `mouse` input initially and bind a `touchstart` event listener to the document. On `touchstart`, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms, using `performance.now()`. Run the callback with the input type as an argument in either of these situations."
}
"snippet-orderBy": {
"prefix": "orderBy",
"body": "const orderBy = (arr, props, orders) =>\n [...arr].sort((a, b) =>\n props.reduce((acc, prop, i) => {\n if (acc === 0) {\n const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]];\n acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;\n }\n return acc;\n }, 0)\n );",
"description": "Returns a sorted array of objects ordered by properties and orders. Uses `Array.sort()`, `Array.reduce()` on the `props` array with a default value of `0`, use array destructuring to swap the properties position depending on the order passed. If no `orders` array is passed it sort by `'asc'` by default."
}
"snippet-over": {
"prefix": "over",
"body": "const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));",
"description": "Creates a function that invokes each provided function with the arguments it receives and returns the results. Use `Array.map()` and `Function.apply()` to apply each function to the given arguments."
}
"snippet-palindrome": {
"prefix": "palindrome",
"body": "const palindrome = str => {\n const s = str.toLowerCase().replace(/[\\W_]/g, '');\n return (\n s ===\n s\n .split('')\n .reverse()\n .join('')\n );\n};",
"description": "Returns `true` if the given string is a palindrome, `false` otherwise. Convert string `String.toLowerCase()` and use `String.replace()` to remove non-alphanumeric characters from it. Then, `String.split('')` into individual characters, `Array.reverse()`, `String.join('')` and compare to the original, unreversed string, after converting it `String.tolowerCase()`."
}
"snippet-parseCookie": {
"prefix": "parseCookie",
"body": "const parseCookie = str =>\n str\n .split(';')\n .map(v => v.split('='))\n .reduce((acc, v) => {\n acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());\n return acc;\n }, {});",
"description": "Parse an HTTP Cookie header string and return an object of all cookie name-value pairs. Use `String.split(';')` to separate key-value pairs from each other. Use `Array.map()` and `String.split('=')` to separate keys from values in each pair. Use `Array.reduce()` and `decodeURIComponent()` to create an object with all key-value pairs."
}
"snippet-partial": {
"prefix": "partial",
"body": "const partial = (fn, ...partials) => (...args) => fn(...partials, ...args);",
"description": "Creates a function that invokes `fn` with `partials` prepended to the arguments it receives. Use the spread operator (`...`) to prepend `partials` to the list of arguments of `fn`."
}
"snippet-partailRight": {
"prefix": "partailRight",
"body": "const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials);",
"description": "Creates a function that invokes `fn` with `partials` appended to the arguments it receives. Use the spread operator (`...`) to append `partials` to the list of arguments of `fn`."
}
"snippet-partition": {
"prefix": "partition",
"body": "const partition = (arr, fn) =>\n arr.reduce(\n (acc, val, i, arr) => {\n acc[fn(val, i, arr) ? 0 : 1].push(val);\n return acc;\n },\n [[], []]\n );",
"description": "Groups the elements into two arrays, depending on the provided function's truthiness for each element. Use `Array.reduce()` to create an array of two arrays. Use `Array.push()` to add elements for which `fn` returns `true` to the first array and elements for which `fn` returns `false` to the second one."
}
"snippet-percentile": {
"prefix": "percentile",
"body": "const percentile = (arr, val) =>\n 100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;",
"description": "Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value. Use `Array.reduce()` to calculate how many numbers are below the value and how many are the same value and apply the percentile formula."
}
"snippet-pick": {
"prefix": "pick",
"body": "const pick = (obj, arr) =>\n arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});",
"description": "Picks the key-value pairs corresponding to the given keys from an object. Use `Array.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object."
}
"snippet-pickBy": {
"prefix": "pickBy",
"body": "const pickBy = (obj, fn) =>\n Object.keys(obj)\n .filter(k => fn(obj[k], k))\n .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});",
"description": "Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key). Use `Object.keys(obj)` and `Array.filter()`to remove the keys for which `fn` returns a falsey value. Use `Array.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs."
}
"snippet-pipeFunctions": {
"prefix": "pipeFunctions",
"body": "const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));",
"description": "Performs left-to-right function composition. Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary."
}
"snippet-pluralize": {
"prefix": "pluralize",
"body": "const pluralize = (val, word, plural = word + 's') => {\n const _pluralize = (num, word, plural = word + 's') =>\n [1, -1].includes(Number(num)) ? word : plural;\n if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]);\n return _pluralize(val, word, plural);\n};",
"description": "Returns the singular or plural form of the word based on the input number. If the first argument is an `object`, it will use a closure by returning a function that can auto-pluralize words that don't simply end in `s` if the supplied dictionary contains the word. If `num` is either `-1` or `1`, return the singular form of the word. If `num` is any other number, return the plural form. Omit the third argument to use the default of the singular word + `s`, or supply a custom pluralized word when necessary. If the first argument is an `object`, utilize a closure by returning a function which can use the supplied dictionary to resolve the correct plural form of the word."
}
"snippet-powerset": {
"prefix": "powerset",
"body": "const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);",
"description": "Returns the powerset of a given array of numbers. Use `Array.reduce()` combined with `Array.map()` to iterate over elements and combine into an array containing all combinations."
}
"snippet-prettyBytes": {
"prefix": "prettyBytes",
"body": "const prettyBytes = (num, precision = 3, addSpace = true) => {\n const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];\n const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);\n const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));\n return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];\n};",
"description": "Converts a number in bytes to a human-readable string. Use an array dictionary of units to be accessed based on the exponent. Use `Number.toPrecision()` to truncate the number to a certain number of digits. Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not. Omit the second argument, `precision`, to use a default precision of `3` digits. Omit the third argument, `addSpace`, to add space between the number and unit by default."
}
"snippet-primes": {
"prefix": "primes",
"body": "const primes = num => {\n let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2),\n sqroot = Math.floor(Math.sqrt(num)),\n numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2);\n numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y == x)));\n return arr;\n};",
"description": "Generates primes up to a given number, using the Sieve of Eratosthenes. Generate an array from `2` to the given number. Use `Array.filter()` to filter out the values divisible by any number from `2` to the square root of the provided number."
}
"snippet-promisify": {
"prefix": "promisify",
"body": "const promisify = func => (...args) =>\n new Promise((resolve, reject) =>\n func(...args, (err, result) => (err ? reject(err) : resolve(result)))\n );",
"description": "Converts an asynchronous function to return a promise. Use currying to return a function returning a `Promise` that calls the original function. Use the `...rest` operator to pass in all the parameters. *In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*"
}
"snippet-pull": {
"prefix": "pull",
"body": "const pull = (arr, ...args) => {\n let argState = Array.isArray(args[0]) ? args[0] : args;\n let pulled = arr.filter((v, i) => !argState.includes(v));\n arr.length = 0;\n pulled.forEach(v => arr.push(v));\n};",
"description": "Mutates the original array to filter out the values specified. Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. _(For a snippet that does not mutate the original array see [`without`](#without))_"
}
"snippet-pullAtIndex": {
"prefix": "pullAtIndex",
"body": "const pullAtIndex = (arr, pullArr) => {\n let removed = [];\n let pulled = arr\n .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))\n .filter((v, i) => !pullArr.includes(i));\n arr.length = 0;\n pulled.forEach(v => arr.push(v));\n return removed;\n};",
"description": "Mutates the original array to filter out the values at the specified indexes. Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. Use `Array.push()` to keep track of pulled values"
}
"snippet-pullAtValue": {
"prefix": "pullAtValue",
"body": "const pullAtValue = (arr, pullArr) => {\n let removed = [],\n pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)),\n mutateTo = arr.filter((v, i) => !pullArr.includes(v));\n arr.length = 0;\n mutateTo.forEach(v => arr.push(v));\n return removed;\n};",
"description": "Mutates the original array to filter out the values specified. Returns the removed elements. Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. Use `Array.push()` to keep track of pulled values"
}
"snippet-randomHexColorCode": {
"prefix": "randomHexColorCode",
"body": "const randomHexColorCode = () => {\n let n = ((Math.random() * 0xfffff) | 0).toString(16);\n return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n);\n};",
"description": "Generates a random hexadecimal color code. Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using `toString(16)`."
}
"snippet-randomIntArrayInRange": {
"prefix": "randomIntArrayInRange",
"body": "const randomIntArrayInRange = (min, max, n = 1) =>\n Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);",
"description": "Returns an array of n random integers in the specified range. Use `Array.from()` to create an empty array of the specific length, `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer."
}
"snippet-randomIntegerInRange": {
"prefix": "randomIntegerInRange",
"body": "const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;",
"description": "Returns a random integer in the specified range. Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer."
}
"snippet-randomNumberInRange": {
"prefix": "randomNumberInRange",
"body": "const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;",
"description": " Returns a random number in the specified range. Use `Math.random()` to generate a random value, map it to the desired range using multiplication."
}
"snippet-readFileLines": {
"prefix": "readFileLines",
"body": "const fs = require('fs');\nconst readFileLines = filename =>\n fs\n .readFileSync(filename)\n .toString('UTF8')\n .split('\n');",
"description": "Returns an array of lines from the specified file. Use `readFileSync` function in `fs` node package to create a `Buffer` from a file. convert buffer to string using `toString(encoding)` function. creating an array from contents of file by `split`ing file content line by line (each `\n`)."
}
"snippet-redirect": {
"prefix": "redirect",
"body": "const redirect = (url, asLink = true) =>\n asLink ? (window.location.href = url) : window.location.replace(url);",
"description": "Redirects to a specified URL. Use `window.location.href` or `window.location.replace()` to redirect to `url`. Pass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`)."
}
"snippet-reducedFilter": {
"prefix": "reducedFilter",
"body": "const reducedFilter = (data, keys, fn) =>\n data.filter(fn).map(el =>\n keys.reduce((acc, key) => {\n acc[key] = el[key];\n return acc;\n }, {})\n );",
"description": "Filter an array of objects based on a condition while also filtering out unspecified keys. Use `Array.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value. On the filtered array, use `Array.map()` to return the new object using `Array.reduce()` to filter out the keys which were not supplied as the `keys` argument."
}
"snippet-reduceSuccessive": {
"prefix": "reduceSuccessive",
"body": "const reduceSuccessive = (arr, fn, acc) =>\n arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);",
"description": "Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values. Use `Array.reduce()` to apply the given function to the given array, storing each new result."
}
"snippet-reduceWhich": {
"prefix": "reduceWhich",
"body": "const reduceWhich = (arr, comparator = (a, b) => a - b) =>\n arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));",
"description": "Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule. Use `Array.reduce()` in combination with the `comparator` function to get the appropriate element in the array. You can omit the second parameter, `comparator`, to use the default one that returns the minimum element in the array."
}
"snippet-remove": {
"prefix": "remove",
"body": "const remove = (arr, func) =>\n Array.isArray(arr)\n ? arr.filter(func).reduce((acc, val) => {\n arr.splice(arr.indexOf(val), 1);\n return acc.concat(val);\n }, [])\n : [];",
"description": "Removes elements from an array for which the given function returns `false`. Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`. The `func` is invoked with three arguments (`value, index, array`)."
}
"snippet-removeNonASCII": {
"prefix": "removeNonASCII",
"body": "const removeNonASCII = str => str.replace(/[^\\x20-\\x7E]/g, '');",
"description": "Removes non-printable ASCII characters. Use a regular expression to remove non-printable ASCII characters."
}
"snippet-reverseString": {
"prefix": "reverseString",
"body": "const reverseString = str => [...str].reverse().join('');",
"description": "Reverses a string. Use the spread operator (`...`) and `Array.reverse()` to reverse the order of the characters in the string. Combine characters to get a string using `String.join('')`."
}
"snippet-RGBToHex": {
"prefix": "RGBToHex",
"body": "const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');",
"description": "Converts the values of RGB components to a color code. Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value."
}
"snippet-round": {
"prefix": "round",
"body": "const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);",
"description": "Rounds a number to a specified amount of digits. Use `Math.round()` and template literals to round the number to the specified number of digits. Omit the second argument, `decimals` to round to an integer."
}
"snippet-runAsync": {
"prefix": "runAsync",
"body": "const runAsync = fn => {\n const blob = `var fn = ${fn.toString()}; postMessage(fn());`;\n const worker = new Worker(\n URL.createObjectURL(new Blob([blob]), {\n type: 'application/javascript; charset=utf-8'\n })\n );\n return new Promise((res, rej) => {\n worker.onmessage = ({ data }) => {\n res(data), worker.terminate();\n };\n worker.onerror = err => {\n rej(err), worker.terminate();\n };\n });\n};",
"description": "Runs a function in a separate thread by using a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), allowing long running functions to not block the UI. Create a new `Worker` using a `Blob` object URL, the contents of which should be the stringified version of the supplied function. Immediately post the return value of calling the function back. Return a promise, listening for `onmessage` and `onerror` events and resolving the data posted back from the worker, or throwing an error."
}
"snippet-runPromisesInSeries": {
"prefix": "runPromisesInSeries",
"body": "const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());",
"description": "Runs an array of promises in series. Use `Array.reduce()` to create a promise chain, where each promise returns the next promise when resolved."
}
"snippet-sample": {
"prefix": "sample",
"body": "const sample = arr => arr[Math.floor(Math.random() * arr.length)];",
"description": "Returns a random element from an array. Use `Math.random()` to generate a random number, multiply it by `length` and round it of to the nearest whole number using `Math.floor()`. This method also works with strings."
}
"snippet-sampleSize": {
"prefix": "sampleSize",
"body": "const sampleSize = ([...arr], n = 1) => {\n let m = arr.length;\n while (m) {\n const i = Math.floor(Math.random() * m--);\n [arr[m], arr[i]] = [arr[i], arr[m]];\n }\n return arr.slice(0, n);\n};",
"description": "Gets `n` random elements at unique keys from `array` up to the size of `array`. Shuffle the array using the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle). Use `Array.slice()` to get the first `n` elements. Omit the second argument, `n` to get only one element at random from the array."
}
"snippet-scrollToTop": {
"prefix": "scrollToTop",
"body": "const scrollToTop = () => {\n const c = document.documentElement.scrollTop || document.body.scrollTop;\n if (c > 0) {\n window.requestAnimationFrame(scrollToTop);\n window.scrollTo(0, c - c / 8);\n }\n};",
"description": "Smooth-scrolls to the top of the page. Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`. Scroll by a fraction of the distance from the top. Use `window.requestAnimationFrame()` to animate the scrolling."
}
"snippet-sdbm": {
"prefix": "sdbm",
"body": "const sdbm = str => {\n let arr = str.split('');\n return arr.reduce(\n (hashCode, currentVal) =>\n (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode),\n 0\n );\n};",
"description": "Hashes the input string into a whole number. Use `String.split('')` and `Array.reduce()` to create a hash of the input string, utilizing bit shifting."
}