Skip to content

Instantly share code, notes, and snippets.

@apotashov
Last active May 7, 2021 14:06
Show Gist options
  • Select an option

  • Save apotashov/dc6cdc3e4bd31e320d8df6801b4ea18c to your computer and use it in GitHub Desktop.

Select an option

Save apotashov/dc6cdc3e4bd31e320d8df6801b4ea18c to your computer and use it in GitHub Desktop.
JS: Helpful Snippets - Part 1
/**
* all
* allEqual
* approximatelyEqual
* arrayToCSV
* arrayToHtmlList
* attempt
* average
* averageBy
* bifurcate
* bifurcateBy
* bottomVisible
* byteSize
* capitalize
* capitalizeEveryWord
* castArray
* compact
* countOccurrences
* createDirIfNotExists
* currentURL
* dayOfYear
* decapitalize
* deepFlatten
* default
* defer
* degreesToRads
* difference
* differenceBy
* differenceWith
* digitize
* distance
* drop (Drop Elements)
* dropRight
* dropRightWhile
* dropWhile
* elementContains
* filterNonUnique (Filter Duplicate Elements)
* findKey
* findLast
* flatten
* forEachRight
* forOwn
* functionName
*/
/**
* 1. all
*
* This snippet returns true if the predicate function
* returns true for all elements in a collection and
* false otherwise. You can omit the second argument
* fn if you want to use Boolean as a default value.
*
* @param {*} arr array object.
* @param {*} fn default compare function.
*/
const all = (arr, fn = Boolean) => arr.every(fn);
console.log(all([4, 3, 3], x => x > 2));
console.log(all([1, 2, 3]));
/**
* 2. allEqual
*
* This snippet checks whether all elements of the array are equal.
*
* @param {*} arr
*/
const allEqual = arr => arr.every(val => val === arr[0]);
console.log(allEqual([1, 2, 3, 4, 5, 6]));
console.log(allEqual([1, 1, 2, 1]));
/**
* 3. approximatelyEqual
*
* This snippet checks whether two numbers are approximately
* equal to each other, with a small difference.
*
* @param {*} v1
* @param {*} v2
* @param {*} epsilon
*/
const approximatelyEqual = (v1, v2, epsilon = 0.001) =>
Math.abs(v1 - v2) < epsilon;
console.log(approximatelyEqual(Math.PI / 2.0, 1.5708));
/**
* 4. arrayToCSV
*
* This snippet converts the elements that don’t
* have commas or double quotes to strings with
* comma-separated values.
*
* @param {*} arr
* @param {*} delimiter
*/
const arrayToCSV = (arr, delimiter = ",") =>
arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join("\n");
console.log(arrayToCSV([["a", "b"], ["c", "d"]]));
console.log(arrayToCSV([["a", "b"], ["c", "d"]], ";"));
/**
* 5. arrayToHtmlList
*
* This snippet converts the elements of an array into
* <li> tags and appends them to the list of the given ID.
*
* @param {*} arr
* @param {*} listID
*/
const arrayToHtmlList = (arr, listID) =>
(el => (
(el = document.querySelector("#" + listID)),
(el.innerHTML += arr.map(item => `<li class="item">${item}</li>`).join(""))
))();
// Working on DOM ready only.
window.onload = () => {
arrayToHtmlList(["item 1", "item 2"], "myListID");
};
/**
* 6. attempt
*
* This snippet executes a function, returning either
* the result or the caught error object.
*
* @param {*} fn
* @param {...any} args
*/
const attempt = (fn, ...args) => {
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
window.onload = () => {
// Run function with arguments.
let elements = attempt(selector => {
return document.querySelectorAll(selector);
}, ".news__item");
if (elements instanceof Error) elements = [];
console.log(elements);
};
/**
* 7. average
*
* This snippet returns the average
* of two or more numerical values.
*
* @param {...any} nums
*/
const average = (...nums) =>
nums.reduce((acc, val) => acc + val, 0) / nums.length;
console.log(average(...[1, 2, 23, 14]));
console.log(average(1, 2, 16, 24));
/**
* 8. averageBy
*
* This snippet returns the average of an array
* after initially doing the mapping of each
* element to a value using a given function.
*
* @param {*} arr
* @param {*} fn
*/
const averageBy = (arr, fn) =>
arr
.map(typeof fn === "function" ? fn : val => val[fn])
.reduce((acc, val) => acc + val, 0) / arr.length;
console.log(averageBy([{ n: 4 }, { n: 8 }, { n: 8 }, { n: 6 }], o => o.n));
console.log(averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], "n"));
/**
* 9. bifurcate
*
* This snippet splits values into two groups
* and then puts a truthy element of filter
* in the first group, and in the second
* group otherwise.
*
* @param {*} arr
* @param {*} filter
*/
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [
[],
[]
]);
console.log(
bifurcate(["beep", "boop", "foo", "bar"], [true, true, false, true])
);
/**
* 10. bifurcateBy
*
* This snippet splits values into two groups,
* based on a predicate function. If the predicate
* function returns a truthy value, the element
* will be placed in the first group. Otherwise,
* it will be placed in the second group.
*
* @param {*} arr
* @param {*} fn
*/
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [
[],
[]
]);
console.log(bifurcateBy(["beep", "boop", "foo", "bar"], x => x[0] === "b"));
/**
* 11. bottomVisible
*
* This snippet checks whether the bottom
* of a page is visible.
*/
const bottomVisible = () =>
document.documentElement.clientHeight + window.screenY >=
(document.documentElement.scrollHeight ||
document.documentElement.clientHeight());
console.log(bottomVisible());
/**
* 12. byteSize
*
* This snippet returns the
* ength of a string in bytes.
*
* @param {*} str
*/
const byteSize = str => new Blob([str]).size;
console.log(byteSize("😀"));
console.log(byteSize("Hello World"));
/**
* 13. capitalize
*
* This snippet capitalizes
* the first letter of a string.
*
* @param {*} param0
*/
const capitalize = ([first, ...rest]) => first.toUpperCase() + rest.join("");
console.log(capitalize("fooBar"));
console.log(capitalize("fooBar", true));
/**
* 14. capitalizeEveryWord
*
* This snippet capitalizes the first
* letter of every word in a given string.
*/
const capitalizeEveryWord = str =>
str.replace(/\b[a-z]/g, char => char.toUpperCase());
console.log(capitalizeEveryWord("hello world!"));
/**
* 15. castArray
*
* This snippet converts a non-array value into array.
*
* @param {*} val
*/
const castArray = val => (Array.isArray(val) ? val : [val]);
console.log(castArray("foo"));
console.log(castArray([1]));
/**
* 16. compact
*
* This snippet removes false values from an array.
*
* @param {*} arr
*/
const compact = arr => arr.filter(Boolean);
// Remove: 0, false, "", "e" * 23, NaN, etc.
console.log(compact([0, 1, false, 2, "", 3, "a", "e" * 23, NaN, "s", 34]));
/**
* 17. countOccurrences
*
* This snippet counts the occurrences of a value in an array.
*
* @param {*} arr
* @param {*} val
*/
const countOccurrences = (arr, val) =>
arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
console.log(countOccurrences([1, 1, 2, 1, 2, 3], 1));
/**
* 18. Create Directory (NodeJS Only)
*
* This snippet uses existsSync() to check whether
* a directory exists and then mkdirSync()
* to create it if it doesn’t.
*/
// const fs = require("fs");
// const createDirIfNotExists = dir =>
// !fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined;
// createDirIfNotExists("test");
/**
* 19. currentURL
*
* This snippet returns the current URL.
*/
const currentURL = () => window.location.href;
console.log(currentURL());
/**
* 20. dayOfYear
*
* This snippet gets the day of the year from a Date object.
*/
const dayOfYear = date =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
console.log(dayOfYear(new Date()));
/**
* 21. decapitalize
*
* This snippet turns the first letter
* of a string into lowercase.
* @param {*} param0
*/
const decapitalize = ([first, ...rest]) => first.toLowerCase() + rest.join("");
console.log(decapitalize("FooBar"));
/**
* 22. deepFlatten
*
* This snippet flattens an array recursively.
*
* @param {*} arr
*/
const deepFlatten = arr =>
[].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
console.log(deepFlatten([1, [2], [[3], 4], 5]));
/**
* 23. default
*
* This snippet assigns default values for all
* properties in an object that are undefined.
*
* @param {*} obj
* @param {...any} defs
*/
const defaults = (obj, ...defs) =>
Object.assign({}, obj, ...defs.reverse(), obj);
console.log(defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }));
/**
* 24. defer
*
* This snippet delays the execution of a function
* until the current call stack is cleared.
*
* @param {*} fn
* @param {...any} args
*/
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
defer(console.log, "a"), console.log("b");
/**
* 25. degreesToRads
*
* This code snippet can be used to convert
* a value from degrees to radians.
*
* @param {*} deg
*/
const degreesToRads = deg => (deg * Math.PI) / 180.0;
console.log(degreesToRads(90.0));
/**
* 26. difference
*
* This snippet finds the difference between two arrays.
*
* @param {*} a
* @param {*} b
*/
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};
console.log(difference([1, 2, 3, 5], [1, 2, 4]));
/**
* 27. differenceBy
*
* This method returns the difference between two arrays,
* after applying a given function to each element of both lists.
*
* @param {*} a
* @param {*} b
* @param {*} fn
*/
const differenceBy = (a, b, fn) => {
const s = new Set(b.map(fn));
return a.filter(x => !s.has(fn(x)));
};
console.log(differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor));
console.log(differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x));
/**
* 28. differenceWith
*
* This snippet removes the values for which the
* comparator function returns false.
*
* @param {*} arr
* @param {*} val
* @param {*} comp
*/
const differenceWith = (arr, val, comp) =>
arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
console.log(
differenceWith(
[1, 1.2, 1.5, 3, 0],
[1.9, 3, 0],
(a, b) => Math.round(a) === Math.round(b)
)
);
/**
* 29. digitize
*
* This snippet gets a number as input
* and returns an array of its digits.
*
* @param {*} n
*/
const digitize = n => [...`${n}`].map(i => parseInt(i));
console.log(digitize(431));
/**
* 30. distance
*
* This snippet returns the distance between two
* points by calculating the Euclidean distance.
*
* @param {*} x0
* @param {*} y0
* @param {*} x1
* @param {*} y1
*/
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
console.log(distance(1, 1, 2, 3));
/**
* 31. Drop Elements
*
* This snippet returns a new array
* with n elements removed from the left.
*
* @param {*} arr
* @param {*} n
*/
const drop = (arr, n = 1) => arr.slice(n);
console.log(drop([1, 2, 3]));
console.log(drop([1, 2, 3], 2));
console.log(drop([1, 2, 3], 42));
/**
* 32. dropRight
*
* This snippet returns a new array with n elements
* removed from the right.
*
* @param {*} arr
* @param {*} n
*/
const dropRight = (arr, n = 1) => arr.slice(0, -n);
console.log(dropRight([1, 2, 3]));
console.log(dropRight([1, 2, 3], 2));
console.log(dropRight([1, 2, 3], 42));
/**
* 33. dropRightWhile
*
* This snippet removes elements from the right side of
* an array until the passed function returns true.
*
* @param {*} arr
* @param {*} func
*/
const dropRightWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
return arr;
};
console.log(dropRightWhile([1, 2, 3, 4], n => n < 3));
/**
* 34. dropWhile
*
* This snippet removes elements from an array
* until the passed function returns true.
*
* @param {*} arr
* @param {*} func
*/
const dropWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
return arr;
};
console.log(dropWhile([1, 2, 3, 4], n => n >= 3));
/**
* 35. elementContains
*
* This snippet checks whether the parent element contains the child.
*
* @param {*} parent
* @param {*} child
*/
const elementContains = (parent, child) =>
parent !== child && parent.contains(child);
console.log(
elementContains(
document.querySelector("head"),
document.querySelector("title")
)
);
console.log(
elementContains(
document.querySelector("body"),
document.querySelector("body")
)
);
/**
* 36. Filter Duplicate Elements
*
* This snippet removes duplicate values in an array.
*
* @param {*} arr
*/
const filterNonUnique = arr => [...new Set(arr)];
console.log(filterNonUnique([1, 2, 2, 3, 4, 4, 5]));
/**
* 38. findLast
*
* This snippet returns the last element for
* which a given function returns a truthy value.
*
* @param {*} arr
* @param {*} fn
*/
const findLast = (arr, fn) => arr.filter(fn).pop();
console.log(findLast([1, 2, 3, 4], n => n % 2 === 1));
/**
* 39. flatten
*
* This snippet flattens an array up to a specified
* depth using recursion.
*
* @param {*} arr
* @param {*} depth
*/
const flatten = (arr, depth = 1) =>
arr.reduce(
(a, v) =>
a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v),
[]
);
console.log(flatten([1, [2], 3, 4]));
console.log(flatten([1, [2, [3, [4, 5], 6], 7], 8], 2));
/**
* 40. forEachRight
*
* This snippet executes a function for each element of
* an array starting from the array’s last element.
*
* @param {*} arr
* @param {*} callback
*/
const forEachRight = (arr, callback) =>
arr
.slice(0)
.reverse()
.forEach(callback);
console.log(forEachRight([1, 2, 3, 4], val => console.log(val)));
/**
* 41. forOwn
*
* This snippet iterates on each property of an object
* and iterates a callback for each one respectively.
*
* @param {*} obj
* @param {*} fn
*/
const forOwn = (obj, fn) =>
Object.keys(obj).forEach(key => fn(obj[key], key, obj));
console.log(forOwn({ foo: "bar", a: 1 }, v => console.log(v)));
/**
* 42. functionName
*
* This snippet prints the name of a function into the console.
*
* @param {*} fn
*/
const functionName = fn => (console.debug(fn.name), fn);
console.log(functionName(Math.max));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment