-
Notifications
You must be signed in to change notification settings - Fork 26
/
snippets.cson
2354 lines (2350 loc) · 122 KB
/
snippets.cson
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
'.source.js':
'⚠️ **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`.':
'prefix': 'anagrams'
'body': """
const anagrams = str => {
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str
.split('')
.reduce(
(acc, letter, i) =>
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),
[]
);
};
"""
'.source.js':
'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.':
'prefix': 'arrayToHtmlList'
'body': """
const arrayToHtmlList = (arr, listID) =>
arr.map(item => (document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`));
"""
'.source.js':
'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 (`...`).':
'prefix': 'ary'
'body': """
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
"""
'.source.js':
'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.':
'prefix': 'atob'
'body': """
const atob = str => new Buffer(str, 'base64').toString('binary');
"""
'.source.js':
'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.':
'prefix': 'average'
'body': """
const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;
"""
'.source.js':
'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.':
'prefix': 'averageBy'
'body': """
const averageBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
arr.length;
"""
'.source.js':
'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.':
'prefix': 'bind'
'body': """
const bind = (fn, context, ...args) =>
function() {
return fn.apply(context, args.concat(...arguments));
};
"""
'.source.js':
'Use `Array.forEach()` to return a `function` that uses `Function.apply()` to apply the given context (`obj`) to `fn` for each function specified.':
'prefix': 'bindAll'
'body': """
const bindAll = (obj, ...fns) =>
fns.forEach(
fn =>
(obj[fn] = function() {
return fn.apply(obj);
})
);
"""
'.source.js':
'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.':
'prefix': 'bindKey'
'body': """
const bindKey = (context, fn, ...args) =>
function() {
return context[fn].apply(context, args.concat(...arguments));
};
"""
'.source.js':
'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.':
'prefix': 'btoa'
'body': """
const btoa = str => new Buffer(str, 'binary').toString('base64');
"""
'.source.js':
'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.':
'prefix': 'bottomVisible'
'body': """
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
"""
'.source.js':
'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`.':
'prefix': 'byteSize'
'body': """
const byteSize = str => new Blob([str]).size;
"""
'.source.js':
'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.':
'prefix': 'capitalize'
'body': """
const capitalize = ([first, ...rest], lowerRest = false) =>
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
"""
'.source.js':
'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.':
'prefix': 'capitalizeEveryWord'
'body': """
const capitalizeEveryWord = str => str.replace(/\\\\b[a-z]/g, char => char.toUpperCase());
"""
'.source.js':
'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.':
'prefix': 'castArray'
'body': """
const castArray = val => (Array.isArray(val) ? val : [val]);
"""
'.source.js':
'Chains asynchronous functions. Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.':
'prefix': 'chainAsync'
'body': """
const chainAsync = fns => {
let curr = 0;
const next = () => fns[curr++](next);
next();
};
"""
'.source.js':
'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.':
'prefix': 'chunk'
'body': """
const chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
"""
'.source.js':
'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.':
'prefix': 'clampNumber'
'body': """
const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
"""
'.source.js':
'Clones a regular expression. Use `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regular expression.':
'prefix': 'cloneRegExp'
'body': """
const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
"""
'.source.js':
' Returns the first non-null/undefined argument. Use `Array.find()` to return the first non `null`/`undefined` argument.':
'prefix': 'coalesce'
'body': """
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
"""
'.source.js':
'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.':
'prefix': 'coalesceFactory'
'body': """
const coalesceFactory = valid => (...args) => args.find(valid);
"""
'.source.js':
'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.':
'prefix': 'collectInto'
'body': """
const collectInto = fn => (...args) => fn(args);
"""
'.source.js':
'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.':
'prefix': 'colorize'
'body': """
const colorize = (...args) => ({
black: `\\\\x1b[30m${args.join(' ')}`,
red: `\\\\x1b[31m${args.join(' ')}`,
green: `\\\\x1b[32m${args.join(' ')}`,
yellow: `\\\\x1b[33m${args.join(' ')}`,
blue: `\\\\x1b[34m${args.join(' ')}`,
magenta: `\\\\x1b[35m${args.join(' ')}`,
cyan: `\\\\x1b[36m${args.join(' ')}`,
white: `\\\\x1b[37m${args.join(' ')}`,
bgBlack: `\\\\x1b[40m${args.join(' ')}\\\\x1b[0m`,
bgRed: `\\\\x1b[41m${args.join(' ')}\\\\x1b[0m`,
bgGreen: `\\\\x1b[42m${args.join(' ')}\\\\x1b[0m`,
bgYellow: `\\\\x1b[43m${args.join(' ')}\\\\x1b[0m`,
bgBlue: `\\\\x1b[44m${args.join(' ')}\\\\x1b[0m`,
bgMagenta: `\\\\x1b[45m${args.join(' ')}\\\\x1b[0m`,
bgCyan: `\\\\x1b[46m${args.join(' ')}\\\\x1b[0m`,
bgWhite: `\\\\x1b[47m${args.join(' ')}\\\\x1b[0m`
});
"""
'.source.js':
'Removes falsey values from an array. Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).':
'prefix': 'compact'
'body': """
const compact = arr => arr.filter(Boolean);
"""
'.source.js':
'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.':
'prefix': 'compose'
'body': """
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
"""
'.source.js':
'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.':
'prefix': 'composeRight'
'body': """
const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
"""
'.source.js':
'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).':
'prefix': 'copyToClipboard'
'body': """
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
"""
'.source.js':
'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.':
'prefix': 'countBy'
'body': """
const countBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
"""
'.source.js':
'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.':
'prefix': 'countOccurrences'
'body': """
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0);
"""
'.source.js':
'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.':
'prefix': 'createElement'
'body': """
const createElement = str => {
const el = document.createElement('div');
el.innerHTML = str;
return el.firstElementChild;
};
"""
'.source.js':
'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()`.':
'prefix': 'createEventHub'
'body': """
const createEventHub = () => ({
hub: Object.create(null),
emit(event, data) {
(this.hub[event] || []).forEach(handler => handler(data));
},
on(event, handler) {
if (!this.hub[event]) this.hub[event] = [];
this.hub[event].push(handler);
},
off(event, handler) {
const i = (this.hub[event] || []).findIndex(h => h === handler);
if (i > -1) this.hub[event].splice(i, 1);
}
});
"""
'.source.js':
'Returns the current URL. Use `window.location.href` to get current URL.':
'prefix': 'currentUrl'
'body': """
const currentURL = () => window.location.href;
"""
'.source.js':
'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`.':
'prefix': 'curry'
'body': """
const curry = (fn, arity = fn.length, ...args) =>
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
"""
'.source.js':
'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.':
'prefix': 'decapitalize'
'body': """
const decapitalize = ([first, ...rest], upperRest = false) =>
first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
"""
'.source.js':
'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.':
'prefix': 'deepClone'
'body': """
const deepClone = obj => {
let clone = Object.assign({}, obj);
Object.keys(clone).forEach(
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
);
return clone;
};
"""
'.source.js':
'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.':
'prefix': 'deepFlatten'
'body': """
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
"""
'.source.js':
'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.':
'prefix': 'defaults'
'body': """
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
"""
'.source.js':
'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.':
'prefix': 'defer'
'body': """
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
"""
'.source.js':
'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.':
'prefix': 'delay'
'body': """
const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
"""
'.source.js':
'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.':
'prefix': 'detectDeviceType'
'body': """
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';
"""
'.source.js':
' 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`.':
'prefix': 'difference'
'body': """
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};
"""
'.source.js':
' 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.':
'prefix': 'differenceBy'
'body': """
const differenceBy = (a, b, fn) => {
const s = new Set(b.map(v => fn(v)));
return a.filter(x => !s.has(fn(x)));
};
"""
'.source.js':
'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.':
'prefix': 'differenceWith'
'body': """
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
"""
'.source.js':
'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.':
'prefix': 'digitize'
'body': """
const digitize = n => [...`${n}`].map(i => parseInt(i));
"""
'.source.js':
'Returns the distance between two points. Use `Math.hypot()` to calculate the Euclidean distance between two points.':
'prefix': 'distance'
'body': """
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
"""
'.source.js':
'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.':
'prefix': 'drop'
'body': """
const drop = (arr, n = 1) => arr.slice(n);
"""
'.source.js':
'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.':
'prefix': 'dropRight'
'body': """
const dropRight = (arr, n = 1) => arr.slice(0, -n);
"""
'.source.js':
'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.':
'prefix': 'dropRightWhile'
'body': """
const dropRightWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
return arr;
};
"""
'.source.js':
'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.':
'prefix': 'dropWhile'
'body': """
const dropWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
return arr;
};
"""
'.source.js':
'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.':
'prefix': 'elementIsVisibleInViewport'
'body': """
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
"""
'.source.js':
'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.':
'prefix': 'elo'
'body': """
const elo = ([...ratings], kFactor = 32, selfRating) => {
const [a, b] = ratings;
const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));
const newRating = (rating, i) =>
(selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));
if (ratings.length === 2) {
return [newRating(a, 1), newRating(b, 0)];
} else {
for (let i = 0; i < ratings.length; i++) {
let j = i;
while (j < ratings.length - 1) {
[ratings[i], ratings[j + 1]] = elo([ratings[i], ratings[j + 1]], kFactor);
j++;
}
}
}
return ratings;
};
"""
'.source.js':
'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.':
'prefix': 'equals'
'body': """
const equals = (a, b) => {
if (a === b) return true;
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if (!a || !b || (typeof a != 'object' && typeof b !== 'object')) return a === b;
if (a === null || a === undefined || b === null || b === undefined) return false;
if (a.prototype !== b.prototype) return false;
let keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) return false;
return keys.every(k => equals(a[k], b[k]));
};
"""
'.source.js':
'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).':
'prefix': 'escapeHTML'
'body': """
const escapeHTML = str =>
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
);
"""
'.source.js':
'Escapes a string to use in a regular expression. Use `String.replace()` to escape special characters.':
'prefix': 'escapeRegExp'
'body': """
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\\\\]\\\\\\\\]/g, '\\\\\\\\\$&');
"""
'.source.js':
'Returns every nth element in an array. Use `Array.filter()` to create a new array that contains every nth element of a given array.':
'prefix': 'everyNth'
'body': """
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
"""
'.source.js':
'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.':
'prefix': 'extendhex'
'body': """
const extendHex = shortHex =>
'#' +
shortHex
.slice(shortHex.startsWith('#') ? 1 : 0)
.split('')
.map(x => x + x)
.join('');
"""
'.source.js':
'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.':
'prefix': 'factorial'
'body': """
const factorial = n =>
n < 0
? (() => {
throw new TypeError('Negative numbers are not allowed!');
})()
: n <= 1 ? 1 : n * factorial(n - 1);
"""
'.source.js':
'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.':
'prefix': 'fibonacci'
'body': """
const fibonacci = n =>
Array.from({ length: n }).reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
);
"""
'.source.js':
'Filters out the non-unique values in an array. Use `Array.filter()` for an array containing only the unique values.':
'prefix': 'filterNonUnique'
'body': """
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
"""
'.source.js':
'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.':
'prefix': 'findkey'
'body': """
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
"""
'.source.js':
' 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.':
'prefix': 'findLast'
'body': """
const findLast = (arr, fn) => arr.filter(fn).slice(-1)[0];
"""
'.source.js':
'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.':
'prefix': 'findLastIndex'
'body': """
const findLastIndex = (arr, fn) =>
arr
.map((val, i) => [i, val])
.filter(val => fn(val[1], val[0], arr))
.slice(-1)[0][0];
"""
'.source.js':
'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.':
'prefix': 'findLastKey'
'body': """
const findLastKey = (obj, fn) =>
Object.keys(obj)
.reverse()
.find(key => fn(obj[key], key, obj));
"""
'.source.js':
'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).':
'prefix': 'flatten'
'body': """
const flatten = (arr, depth = 1) =>
depth != 1
? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), [])
: arr.reduce((a, v) => a.concat(v), []);
"""
'.source.js':
'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.':
'prefix': 'flip'
'body': """
const flip = fn => (first, ...rest) => fn(...rest, first);
"""
'.source.js':
'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.':
'prefix': 'forEachRight'
'body': """
const forEachRight = (arr, callback) =>
arr
.slice(0)
.reverse()
.forEach(callback);
"""
'.source.js':
'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.':
'prefix': 'formatDuration'
'body': """
const formatDuration = ms => {
if (ms < 0) ms = -ms;
const time = {
day: Math.floor(ms / 86400000),
hour: Math.floor(ms / 3600000) % 24,
minute: Math.floor(ms / 60000) % 60,
second: Math.floor(ms / 1000) % 60,
millisecond: Math.floor(ms) % 1000
};
return Object.entries(time)
.filter(val => val[1] !== 0)
.map(val => val[1] + ' ' + (val[1] !== 1 ? val[0] + 's' : val[0]))
.join(', ');
};
"""
'.source.js':
'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.':
'prefix': 'forOwn'
'body': """
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
"""
'.source.js':
'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.':
'prefix': 'forOwnRight'
'body': """
const forOwnRight = (obj, fn) =>
Object.keys(obj)
.reverse()
.forEach(key => fn(obj[key], key, obj));
"""
'.source.js':
'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 `_`.':
'prefix': 'fromCamelCase'
'body': """
const fromCamelCase = (str, separator = '_') =>
str
.replace(/([a-z\\\\d])([A-Z])/g, '$1' + separator + '$2')
.replace(/([A-Z]+)([A-Z][a-z\\\\d]+)/g, '$1' + separator + '$2')
.toLowerCase();
"""
'.source.js':
'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.':
'prefix': 'functionName'
'body': """
const functionName = fn => (console.debug(fn.name), fn);
"""
'.source.js':
'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`.':
'prefix': 'gcd'
'body': """
const gcd = (...arr) => {
const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
return [...arr].reduce((a, b) => _gcd(a, b));
};
"""
'.source.js':
'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`.':
'prefix': 'geometricProgression'
'body': """
const geometricProgression = (end, start = 1, step = 2) =>
Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(
(v, i) => start * step ** i
);
"""
'.source.js':
' 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.':
'prefix': 'get'
'body': """
const get = (from, ...selectors) =>
[...selectors].map(s =>
s
.replace(/\\\\[([^\\\\[\\\\]]*)\\\\]/g, '.$1.')
.split('.')
.filter(t => t !== '')
.reduce((prev, cur) => prev && prev[cur], from)
);
"""
'.source.js':
'Returns the difference (in days) between two dates. Calculate the difference (in days) between two `Date` objects.':
'prefix': 'getDaysDiffBetweenDates'
'body': """
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 3600 * 24);
"""
'.source.js':
'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`.':
'prefix': 'getScrollPosition'
'body': """
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
"""
'.source.js':
'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.':
'prefix': 'getStyle'
'body': """
const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
"""
'.source.js':
'Returns the native type of a value. Returns lowercased constructor name of value, `"undefined"` or `"null"` if value is `undefined` or `null`.':
'prefix': 'getType'
'body': """
const getType = v =>
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
"""
'.source.js':
'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`.':
'prefix': 'getURLParameters'
'body': """
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{}
);
"""
'.source.js':
'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.':
'prefix': 'groupby'
'body': """
const groupBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
acc[val] = (acc[val] || []).concat(arr[i]);
return acc;
}, {});
"""
'.source.js':
'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)`.':
'prefix': 'hammingDistance'
'body': """
const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
"""
'.source.js':
'Returns `true` if the element has the specified class, `false` otherwise. Use `element.classList.contains()` to check if the element has the specified class.':
'prefix': 'hasClass'
'body': """
const hasClass = (el, className) => el.classList.contains(className);
"""
'.source.js':
'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.':
'prefix': 'hasFlags'
'body': """
const hasFlags = (...flags) =>
flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
"""
'.source.js':
'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.':
'prefix': 'hashBrowser'
'body': """
const hashBrowser = val =>
crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => {
let hexes = [],
view = new DataView(h);
for (let i = 0; i < view.byteLength; i += 4)
hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
return hexes.join('');
});
"""
'.source.js':
'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.':
'prefix': 'hashNode'
'body': """
const crypto = require('crypto');
const hashNode = val =>
new Promise(resolve =>
setTimeout(
() =>
resolve(
crypto
.createHash('sha256')
.update(val)
.digest('hex')
),
0
)
);
"""
'.source.js':
'Returns the head of a list. Use `arr[0]` to return the first element of the passed array.':
'prefix': 'head'
'body': """
const head = arr => arr[0];
"""
'.source.js':
'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.':
'prefix': 'hexToRGB'
'body': """
const hexToRGB = hex => {
let alpha = false,
h = hex.slice(hex.startsWith('#') ? 1 : 0);
if (h.length === 3) h = [...h].map(x => x + x).join('');
else if (h.length === 8) alpha = true;
h = parseInt(h, 16);
return (
'rgb' +
(alpha ? 'a' : '') +
'(' +
(h >>> (alpha ? 24 : 16)) +
', ' +
((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) +
', ' +
((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
(alpha ? `, ${h & 0x000000ff}` : '') +
')'
);
};
"""
'.source.js':
'Hides all the elements specified. Use the spread operator (`...`) and `Array.forEach()` to apply `display: none` to each element specified.':
'prefix': 'hide'
'body': """
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
"""
'.source.js':
'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.':
'prefix': 'httpGet'
'body': """
const httpGet = (url, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = () => callback(request.responseText);
request.onerror = () => err(request);
request.send();
};
"""
'.source.js':
'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.':
'prefix': 'httpPost'
'body': """
const httpPost = (url, data, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
request.onload = () => callback(request.responseText);
request.onerror = () => err(request);
request.send(data);
};
"""
'.source.js':
'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.':
'prefix': 'httpsRedirect'
'body': """
const httpsRedirect = () => {
if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
};
"""
'.source.js':
'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.':
'prefix': 'indexOfAll'
'body': """
const indexOfAll = (arr, val) => {
const indices = [];
arr.forEach((el, i) => el === val && indices.push(i));
return indices;
};
"""
'.source.js':
'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.':
'prefix': 'initial'
'body': """
const initial = arr => arr.slice(0, -1);
"""
'.source.js':
'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`.':
'prefix': 'initialize2DArray'
'body': """
const initialize2DArray = (w, h, val = null) =>
Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));
"""
'.source.js':
'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`.':
'prefix': 'initializeArrayWithRange'
'body': """
const initializeArrayWithRange = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start);
"""
'.source.js':
'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`.':
'prefix': 'initializeArrayWithRangeRight'
'body': """
const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(
(v, i, arr) => (arr.length - i - 1) * step + start
);
"""
'.source.js':
'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`.':
'prefix': 'initializeArrayWithValues'
'body': """
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
"""
'.source.js':
'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`.':
'prefix': 'inRange'
'body': """
const inRange = (n, start, end = null) => {
if (end && start > end) end = [start, (start = end)][0];
return end == null ? n >= 0 && n < start : n >= start && n < end;
};
"""
'.source.js':
'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`.':
'prefix': 'intersection'
'body': """
const intersection = (a, b) => {
const s = new Set(b);
return a.filter(x => s.has(x));
};
"""
'.source.js':
'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.':
'prefix': 'intersectionBy'
'body': """
const intersectionBy = (a, b, fn) => {
const s = new Set(b.map(x => fn(x)));
return a.filter(x => s.has(fn(x)));
};
"""
'.source.js':
'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.':
'prefix': 'intersectionWith'
'body': """
const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);
"""
'.source.js':
'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.':
'prefix': 'invertKeyValues'
'body': """
const invertKeyValues = (obj, fn) =>
Object.keys(obj).reduce((acc, key) => {
const val = fn ? fn(obj[key]) : obj[key];
acc[val] = acc[val] || [];
acc[val].push(key);
return acc;
}, {});
"""
'.source.js':
'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`.':
'prefix': 'is'
'body': """
const is = (type, val) => val instanceof type;
"""
'.source.js':
'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.':
'prefix': 'isAbsoluteURL'
'body': """
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
"""
'.source.js':
'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.':
'prefix': 'isArrayLike'
'body': """
const isArrayLike = val => {
try {
return [...val], true;
} catch (e) {
return false;
}
};
"""
'.source.js':
'Checks if the given argument is a native boolean element. Use `typeof` to check if a value is classified as a boolean primitive.':
'prefix': 'isBoolean'
'body': """
const isBoolean = val => typeof val === 'boolean';
"""
'.source.js':
'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`.':
'prefix': 'isDivisible'
'body': """
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
"""
'.source.js':
'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`.':
'prefix': 'isEmpty'
'body': """
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
"""
'.source.js':
'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.':
'prefix': 'isEven'
'body': """
const isEven = num => num % 2 === 0;
"""
'.source.js':
'Checks if the given argument is a function. Use `typeof` to check if a value is classified as a function primitive.':
'prefix': 'isFunction'
'body': """
const isFunction = val => typeof val === 'function';
"""
'.source.js':
'Checks if a string is lower case. Convert the given string to lower case, using `String.toLowerCase()` and compare it to the original.':
'prefix': 'isLowerCase'
'body': """
const isLowerCase = str => str === str.toLowerCase();
"""
'.source.js':
'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`.':
'prefix': 'isNil'
'body': """
const isNil = val => val === undefined || val === null;
"""
'.source.js':
'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`.':
'prefix': 'isNull'
'body': """
const isNull = val => val === null;
"""
'.source.js':
'Checks if the given argument is a number. Use `typeof` to check if a value is classified as a number primitive.':
'prefix': 'isNumber'
'body': """
const isNumber = val => typeof val === 'number';
"""
'.source.js':
'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.':