Skip to content

Commit e5a2472

Browse files
committed
# add some snippets
1 parent ebd4934 commit e5a2472

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

note.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3379,3 +3379,80 @@ function randomBetween(min, max) {
33793379
```
33803380
33813381
---
3382+
3383+
## 122. some snippets
3384+
3385+
```js
3386+
// If all redicate function returen true for all elements, return true
3387+
const all = (arr, fn = Boolean) => arr.every(fn);
3388+
3389+
all([4, 2, 3], x => x > 1); // true
3390+
all([1, 2, 3]); // true
3391+
3392+
// check all elements in an array are equal.
3393+
const allEqual = arr => arr.every(val => val === arr[0])
3394+
3395+
allEqual([1, 2, 3, 4, 5, 6]); // false
3396+
allEqual([1, 1, 1]) // true
3397+
3398+
// return the average of numbers
3399+
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
3400+
3401+
average(...[1, 2, 3]); // 2
3402+
average(1, 2, 3); // 2
3403+
3404+
// return the length of a string in bytes
3405+
const byteSize = str => new Blob([str]).size;
3406+
3407+
byteSize('😀'); // 4
3408+
byteSize('Hello World'); // 11
3409+
3410+
// remove falsy values from an array
3411+
const compact = arr => arr.filter(Boolean);
3412+
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]
3413+
3414+
// gets the day of the year from a Date object
3415+
const dayOfYear = date =>
3416+
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
3417+
3418+
dayOfYear(new Date()); // 98
3419+
3420+
// converts an angle from degrees to radians.
3421+
const degreesToRads = deg => (deg * Math.PI) / 180.0;
3422+
degreesToRads(90.0); // ~1.5708
3423+
3424+
// returns the difference between two arrays.
3425+
const difference = (a, b) => {
3426+
const s = new Set(b);
3427+
return a.filter(x => !s.has(x));
3428+
};
3429+
3430+
difference([1, 2, 3], [1, 2, 4]); // [3]
3431+
3432+
// returns the distance between two points.
3433+
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
3434+
distance(1, 1, 2, 3); // 2.23606797749979
3435+
3436+
// returns a new array with n elements removed from the left.
3437+
const drop = (arr, n = 1) => arr.slice(n);
3438+
drop([1, 2, 3]); // [2,3]
3439+
drop([1, 2, 3], 2); // [3]
3440+
drop([1, 2, 3], 42); // []
3441+
3442+
// returns every nth element in an array.
3443+
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
3444+
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
3445+
3446+
// calculates the factorial of a number.
3447+
const factorial = n =>
3448+
n < 0
3449+
? (() => {
3450+
throw new TypeError('Negative numbers are not allowed!');
3451+
})()
3452+
: n <= 1
3453+
? 1
3454+
: n * factorial(n - 1);
3455+
factorial(6); // 720
3456+
```
3457+
3458+
---

0 commit comments

Comments
 (0)