diff --git a/note/javascript/array/cast-a-value-as-an-array.md b/note/javascript/array/cast-a-value-as-an-array.md new file mode 100644 index 0000000..a6c7267 --- /dev/null +++ b/note/javascript/array/cast-a-value-as-an-array.md @@ -0,0 +1,29 @@ +--- +title: How to cast a value as an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to cast a value as an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const castArray = value => Array.isArray(value) ? value : [value]; +``` + +### Example + +```js {.wrap} +castArray(1); // [1] +castArray([1, 2, 3]); // [1, 2, 3] +``` \ No newline at end of file diff --git a/note/javascript/array/check-if-an-array-is-empty.md b/note/javascript/array/check-if-an-array-is-empty.md new file mode 100644 index 0000000..934701a --- /dev/null +++ b/note/javascript/array/check-if-an-array-is-empty.md @@ -0,0 +1,33 @@ +--- +title: How to check if an array is empty in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to check if an array is empty only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isEmpty = arr => !Array.isArray(arr) || arr.length === 0; +``` +Parameters `arr` is an array. + + + + +### Example + +```js {.wrap} +isEmpty([]); // true +isEmpty([1, 2, 3]); // false +``` \ No newline at end of file diff --git a/note/javascript/array/clone-an-array.md b/note/javascript/array/clone-an-array.md new file mode 100644 index 0000000..5e4c90f --- /dev/null +++ b/note/javascript/array/clone-an-array.md @@ -0,0 +1,56 @@ +--- +title: How to clone an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to clone an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const clone = arr => arr.slice(0); +``` +Parameters `arr` is an array. + + + + +### Or + +```js {.wrap} +const clone = arr => [...arr]; +``` + +### Or + +```js {.wrap} +const clone = arr => Array.from(arr); +``` + +### Or + +```js {.wrap} +const clone = arr => arr.map(x => x); +``` + +### Or + +```js {.wrap} +const clone = arr => JSON.parse(JSON.stringify(arr)); +``` + +### Or + +```js {.wrap} +const clone = arr => arr.concat([]); +``` \ No newline at end of file diff --git a/note/javascript/array/compare-two-arrays-regardless-of-order.md b/note/javascript/array/compare-two-arrays-regardless-of-order.md new file mode 100644 index 0000000..bd53a13 --- /dev/null +++ b/note/javascript/array/compare-two-arrays-regardless-of-order.md @@ -0,0 +1,33 @@ +--- +title: How to compare two arrays regardless of order in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to compare two arrays regardless of order only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort()); +``` +Parameters `a` and `b` are arrays. + + + +### Example + +```js {.wrap} +isEqual([1, 2, 3], [1, 2, 3]); // true +isEqual([1, 2, 3], [1, 3, 2]); // true +isEqual([1, 2, 3], [1, '2', 3]); // false +``` diff --git a/note/javascript/array/compare-two-arrays.md b/note/javascript/array/compare-two-arrays.md new file mode 100644 index 0000000..0447c13 --- /dev/null +++ b/note/javascript/array/compare-two-arrays.md @@ -0,0 +1,38 @@ +--- +title: How to compare two arrays in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to compare two arrays only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b); +``` +Parameters `a` and `b` are arrays. + + + +### Or + +```js {.wrap} +const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]); +``` + +### Example + +```js {.wrap} +isEqual([1, 2, 3], [1, 2, 3]); // true +isEqual([1, 2, 3], [1, '2', 3]); // false +``` \ No newline at end of file diff --git a/note/javascript/array/convert-an-array-of-objects-to-a-single-object.md b/note/javascript/array/convert-an-array-of-objects-to-a-single-object.md new file mode 100644 index 0000000..e999e13 --- /dev/null +++ b/note/javascript/array/convert-an-array-of-objects-to-a-single-object.md @@ -0,0 +1,42 @@ +--- +title: How to convert an array of objects to a single object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to convert an array of objects to a single object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {}); +``` + +### Example + +```js {.wrap} +toObject( + [ + { id: '1', name: 'Alpha', gender: 'Male' }, + { id: '2', name: 'Bravo', gender: 'Male' }, + { id: '3', name: 'Charlie', gender: 'Female' }, + ], + 'id' +); +/* +{ + '1': { id: '1', name: 'Alpha', gender: 'Male' }, + '2': { id: '2', name: 'Bravo', gender: 'Male' }, + '3': { id: '3', name: 'Charlie', gender: 'Female' }, +} +*/ +``` \ No newline at end of file diff --git a/note/javascript/array/convert-an-array-of-strings-to-numbers.md b/note/javascript/array/convert-an-array-of-strings-to-numbers.md new file mode 100644 index 0000000..2ad91ce --- /dev/null +++ b/note/javascript/array/convert-an-array-of-strings-to-numbers.md @@ -0,0 +1,34 @@ +--- +title: How to convert an array of strings to numbers in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to convert an array of strings to numbers only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toNumbers = arr => arr.map(Number); +``` + +### Or + +```js {.wrap} +const toNumbers = arr => arr.map(x => +x); +``` + +### Example + +```js {.wrap} +toNumbers(['2', '3', '4']); // [2, 3, 4] +``` \ No newline at end of file diff --git a/note/javascript/array/count-by-the-properties-of-an-array-of-objects.md b/note/javascript/array/count-by-the-properties-of-an-array-of-objects.md new file mode 100644 index 0000000..414409c --- /dev/null +++ b/note/javascript/array/count-by-the-properties-of-an-array-of-objects.md @@ -0,0 +1,36 @@ +--- +title: How to count by the properties of an array of objects in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to count by the properties of an array of objects only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const countBy = (arr, prop) => arr.reduce((prev, curr) => (prev[curr[prop]] = ++prev[curr[prop]] || 1, prev), {}); +``` + +### Example + +```js {.wrap} +countBy([ + { branch: 'audi', model: 'q8', year: '2019' }, + { branch: 'audi', model: 'rs7', year: '2020' }, + { branch: 'ford', model: 'mustang', year: '2019' }, + { branch: 'ford', model: 'explorer', year: '2020' }, + { branch: 'bmw', model: 'x7', year: '2020' }, +], 'branch'); + +// { 'audi': 2, 'ford': 2, 'bmw': 1 } +``` \ No newline at end of file diff --git a/note/javascript/array/count-the-occurrences-of-a-value-in-an-array.md b/note/javascript/array/count-the-occurrences-of-a-value-in-an-array.md new file mode 100644 index 0000000..5f109df --- /dev/null +++ b/note/javascript/array/count-the-occurrences-of-a-value-in-an-array.md @@ -0,0 +1,35 @@ +--- +title: How to count the occurrences of a value in an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to count the occurrences of a value in an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); +``` + +### Or + +```js {.wrap} +const countOccurrences = (arr, val) => arr.filter(item => item === val).length; +``` + +### Example + +```js {.wrap} +countOccurrences([2, 1, 3, 3, 2, 3], 2); // 2 +countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3 +``` \ No newline at end of file diff --git a/note/javascript/array/count-the-occurrences-of-array-elements.md b/note/javascript/array/count-the-occurrences-of-array-elements.md new file mode 100644 index 0000000..c6034a8 --- /dev/null +++ b/note/javascript/array/count-the-occurrences-of-array-elements.md @@ -0,0 +1,29 @@ +--- +title: How to count the occurrences of array elements in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to count the occurrences of array elements only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const countOccurrences = arr => arr.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {}); +``` + +### Example + +```js {.wrap} +countOccurrences([2, 1, 3, 3, 2, 3]); // { '1': 1, '2': 2, '3': 3 } +countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']); // { 'a': 3, 'b': 2, 'c': 1 } +``` \ No newline at end of file diff --git a/note/javascript/array/create-an-array-of-cumulative-sum.md b/note/javascript/array/create-an-array-of-cumulative-sum.md new file mode 100644 index 0000000..5a93dcc --- /dev/null +++ b/note/javascript/array/create-an-array-of-cumulative-sum.md @@ -0,0 +1,44 @@ +--- +title: How to create an array of cumulative sum in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to create an array of cumulative sum only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const accumulate = arr => arr.map((sum => value => sum += value)(0)); +``` + +### Or + +```js {.wrap} +const accumulate = arr => arr.reduce((a, b, i) => i === 0 ? [b] : [...a, b + a[i - 1]], []); +``` + +### Or + +```js {.wrap} +const accumulate = arr => arr.reduce((a, b, i) => i === 0 ? [b] : [...a, b + a[i - 1]], 0); +``` + +### Example + +```js {.wrap} +accumulate([1, 2, 3, 4]); // [1, 3, 6, 10] +// 1 = 1 +// 1 + 2 = 3 +// 1 + 2 + 3 = 6 +// 1 + 2 + 3 + 4 = 10 +``` \ No newline at end of file diff --git a/note/javascript/array/create-an-array-of-numbers-in-the-given-range.md b/note/javascript/array/create-an-array-of-numbers-in-the-given-range.md new file mode 100644 index 0000000..0ebb308 --- /dev/null +++ b/note/javascript/array/create-an-array-of-numbers-in-the-given-range.md @@ -0,0 +1,40 @@ +--- +title: How to create an array of numbers in the given range in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to create an array of numbers in the given range only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const range = (min, max) => [...Array(max - min + 1).keys()].map(i => i + min); +``` + +### Or + +```js {.wrap} +const range = (min, max) => Array(max - min + 1).fill(0).map((_, i) => min + i); +``` + +### Or + +```js {.wrap} +const range = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i); +``` + +### Example + +```js {.wrap} +range(5, 10); // [5, 6, 7, 8, 9, 10] +``` \ No newline at end of file diff --git a/note/javascript/array/create-cartesian-product.md b/note/javascript/array/create-cartesian-product.md new file mode 100644 index 0000000..046ba99 --- /dev/null +++ b/note/javascript/array/create-cartesian-product.md @@ -0,0 +1,37 @@ +--- +title: How to create cartesian product in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to create cartesian product only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const cartesian = (...sets) => sets.reduce((acc, set) => acc.flatMap((x) => set.map((y) => [...x, y])), [[]]); +``` + +### Example + +```js {.wrap} +cartesian([1, 2], [3, 4]); // [ [1, 3], [1, 4], [2, 3], [2, 4] ] + +/* + 3 4 + --------------- +1 | [1, 3] [1, 4] + | +2 | [2, 3] [2, 4] + +*/ +``` diff --git a/note/javascript/array/empty-an-array.md b/note/javascript/array/empty-an-array.md new file mode 100644 index 0000000..3c0fc01 --- /dev/null +++ b/note/javascript/array/empty-an-array.md @@ -0,0 +1,28 @@ +--- +title: How to empty an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to empty an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const empty = arr => arr.length = 0; +``` + +### Or + +```js {.wrap} +arr = []; +``` \ No newline at end of file diff --git a/note/javascript/array/find-the-closest-number-from-an-array.md b/note/javascript/array/find-the-closest-number-from-an-array.md new file mode 100644 index 0000000..195b552 --- /dev/null +++ b/note/javascript/array/find-the-closest-number-from-an-array.md @@ -0,0 +1,35 @@ +--- +title: How to find the closest number from an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to find the closest number from an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Find the number from `arr` which is closest to `n` +const closest = (arr, n) => arr.reduce((prev, curr) => Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev); +``` + +### Or + +```js {.wrap} +const closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0]; +``` + +### Example + +```js {.wrap} +closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33 +``` \ No newline at end of file diff --git a/note/javascript/array/find-the-index-of-the-last-matching-item-of-an-array.md b/note/javascript/array/find-the-index-of-the-last-matching-item-of-an-array.md new file mode 100644 index 0000000..d1cdddc --- /dev/null +++ b/note/javascript/array/find-the-index-of-the-last-matching-item-of-an-array.md @@ -0,0 +1,35 @@ +--- +title: How to find the index of the last matching item of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to find the index of the last matching item of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const lastIndex = (arr, predicate) => arr.reduce((prev, curr, index) => predicate(curr) ? index : prev, -1); +``` + +### Or + +```js {.wrap} +const lastIndex = (arr, predicate) => arr.map(item => predicate(item)).lastIndexOf(true); +``` + +### Example + +```js {.wrap} +lastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], i => i % 2 === 1); // 4 +lastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], i => i > 6); // 5 +``` \ No newline at end of file diff --git a/note/javascript/array/find-the-index-of-the-maximum-item-of-an-array.md b/note/javascript/array/find-the-index-of-the-maximum-item-of-an-array.md new file mode 100644 index 0000000..a129321 --- /dev/null +++ b/note/javascript/array/find-the-index-of-the-maximum-item-of-an-array.md @@ -0,0 +1,29 @@ +--- +title: How to find the index of the maximum item of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to find the index of the maximum item of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const indexOfMax = arr => arr.reduce((prev, curr, i, a) => curr > a[prev] ? i : prev, 0); +``` + +### Example + +```js {.wrap} +indexOfMax([1, 3, 9, 7, 5]); // 2 +indexOfMax([1, 3, 7, 7, 5]); // 2 +``` \ No newline at end of file diff --git a/note/javascript/array/find-the-index-of-the-minimum-item-of-an-array.md b/note/javascript/array/find-the-index-of-the-minimum-item-of-an-array.md new file mode 100644 index 0000000..94e18c7 --- /dev/null +++ b/note/javascript/array/find-the-index-of-the-minimum-item-of-an-array.md @@ -0,0 +1,29 @@ +--- +title: How to find the index of the minimum item of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to find the index of the minimum item of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const indexOfMin = arr => arr.reduce((prev, curr, i, a) => curr < a[prev] ? i : prev, 0); +``` + +### Example + +```js {.wrap} +indexOfMin([6, 4, 8, 2, 10]); // 3 +indexOfMin([6, 4, 2, 2, 10]); // 2 +``` \ No newline at end of file diff --git a/note/javascript/array/find-the-length-of-the-longest-string-in-an-array.md b/note/javascript/array/find-the-length-of-the-longest-string-in-an-array.md new file mode 100644 index 0000000..82d5d59 --- /dev/null +++ b/note/javascript/array/find-the-length-of-the-longest-string-in-an-array.md @@ -0,0 +1,28 @@ +--- +title: How to find the length of the longest string in an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to find the length of the longest string in an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const findLongest = words => Math.max(...(words.map(el => el.length))); +``` + +### Example + +```js {.wrap} +findLongest(['always','look','on','the','bright','side','of','life']); // 6 +``` \ No newline at end of file diff --git a/note/javascript/array/find-the-maximum-item-of-an-array-by-given-key.md b/note/javascript/array/find-the-maximum-item-of-an-array-by-given-key.md new file mode 100644 index 0000000..16b0651 --- /dev/null +++ b/note/javascript/array/find-the-maximum-item-of-an-array-by-given-key.md @@ -0,0 +1,34 @@ +--- +title: How to find the maximum item of an array by given key in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to find the maximum item of an array by given key only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const maxBy = (arr, key) => arr.reduce((a, b) => a[key] >= b[key] ? a : b, {}); +``` + +### Example + +```js {.wrap} +const people = [ + { name: 'Bar', age: 24 }, + { name: 'Baz', age: 32 }, + { name: 'Foo', age: 42 }, + { name: 'Fuzz', age: 36 }, +]; +maxBy(people, 'age'); // { name: 'Foo', age: 42 } +``` \ No newline at end of file diff --git a/note/javascript/array/find-the-maximum-item-of-an-array.md b/note/javascript/array/find-the-maximum-item-of-an-array.md new file mode 100644 index 0000000..1fc918f --- /dev/null +++ b/note/javascript/array/find-the-maximum-item-of-an-array.md @@ -0,0 +1,22 @@ +--- +title: How to find the maximum item of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to find the maximum item of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const max = arr => Math.max(...arr); +``` \ No newline at end of file diff --git a/note/javascript/array/find-the-minimum-item-of-an-array-by-given-key.md b/note/javascript/array/find-the-minimum-item-of-an-array-by-given-key.md new file mode 100644 index 0000000..a3ddcc5 --- /dev/null +++ b/note/javascript/array/find-the-minimum-item-of-an-array-by-given-key.md @@ -0,0 +1,34 @@ +--- +title: How to find the minimum item of an array by given key in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to find the minimum item of an array by given key only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const minBy = (arr, key) => arr.reduce((a, b) => a[key] < b[key] ? a : b, {}); +``` + +### Example + +```js {.wrap} +const people = [ + { name: 'Bar', age: 24 }, + { name: 'Baz', age: 32 }, + { name: 'Foo', age: 42 }, + { name: 'Fuzz', age: 36 }, +]; +minBy(people, 'age'); // { name: 'Bar', age: 24 } +``` \ No newline at end of file diff --git a/note/javascript/array/find-the-minimum-item-of-an-array.md b/note/javascript/array/find-the-minimum-item-of-an-array.md new file mode 100644 index 0000000..01c3f6a --- /dev/null +++ b/note/javascript/array/find-the-minimum-item-of-an-array.md @@ -0,0 +1,22 @@ +--- +title: How to find the minimum item of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to find the minimum item of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const min = arr => Math.min(...arr); +``` \ No newline at end of file diff --git a/note/javascript/array/flatten-an-array.md b/note/javascript/array/flatten-an-array.md new file mode 100644 index 0000000..8f0c4f4 --- /dev/null +++ b/note/javascript/array/flatten-an-array.md @@ -0,0 +1,41 @@ +--- +title: How to flatten an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to flatten an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const flat = arr => [].concat.apply([], arr.map(a => Array.isArray(a) ? flat(a) : a)); +``` + +### Or + +```js {.wrap} +const flat = arr => arr.reduce((a, b) => Array.isArray(b) ? [...a, ...flat(b)] : [...a, b], []); +``` + +### Or + +```js {.wrap} +// See the browser compatibility at https://caniuse.com/#feat=array-flat +const flat = arr => arr.flat(); +``` + +### Example + +```js {.wrap} +flat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger'] +``` \ No newline at end of file diff --git a/note/javascript/array/get-all-arrays-of-consecutive-elements.md b/note/javascript/array/get-all-arrays-of-consecutive-elements.md new file mode 100644 index 0000000..df23ba3 --- /dev/null +++ b/note/javascript/array/get-all-arrays-of-consecutive-elements.md @@ -0,0 +1,30 @@ +--- +title: How to get all arrays of consecutive elements in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get all arrays of consecutive elements only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getConsecutiveArrays = (arr, size) => size > arr.length ? [] : arr.slice(size - 1).map((_, i) => arr.slice(i, size + i)); +``` + +### Example + +```js {.wrap} +getConsecutiveArrays([1, 2, 3, 4, 5], 2); // [[1, 2], [2, 3], [3, 4], [4, 5]] +getConsecutiveArrays([1, 2, 3, 4, 5], 3); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]] +getConsecutiveArrays([1, 2, 3, 4, 5], 6); // [] +``` \ No newline at end of file diff --git a/note/javascript/array/get-all-nth-items-of-an-array.md b/note/javascript/array/get-all-nth-items-of-an-array.md new file mode 100644 index 0000000..62f018d --- /dev/null +++ b/note/javascript/array/get-all-nth-items-of-an-array.md @@ -0,0 +1,29 @@ +--- +title: How to get all n-th items of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get all n-th items of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getNthItems = (arr, nth) => arr.filter((_, i) => i % nth === nth - 1); +``` + +### Example + +```js {.wrap} +getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 2); // [2, 4, 6, 8] +getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 3); // [3, 6, 9] +``` \ No newline at end of file diff --git a/note/javascript/array/get-all-subsets-of-an-array.md b/note/javascript/array/get-all-subsets-of-an-array.md new file mode 100644 index 0000000..6aeb20f --- /dev/null +++ b/note/javascript/array/get-all-subsets-of-an-array.md @@ -0,0 +1,29 @@ +--- +title: How to get all subsets of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get all subsets of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getSubsets = arr => arr.reduce((prev, curr) => prev.concat(prev.map(k => k.concat(curr))), [[]]); +``` + +### Example + +```js {.wrap} +getSubsets([1, 2]); // [[], [1], [2], [1, 2]] +getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] +``` \ No newline at end of file diff --git a/note/javascript/array/get-indices-of-a-value-in-an-array.md b/note/javascript/array/get-indices-of-a-value-in-an-array.md new file mode 100644 index 0000000..59ade46 --- /dev/null +++ b/note/javascript/array/get-indices-of-a-value-in-an-array.md @@ -0,0 +1,35 @@ +--- +title: How to get indices of a value in an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get indices of a value in an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const indices = (arr, value) => arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), []); +``` + +### Or + +```js {.wrap} +const indices = (arr, value) => arr.map((v, i) => v === value ? i : false).filter(Boolean); +``` + +### Example + +```js {.wrap} +indices(['h', 'e', 'l', 'l', 'o'], 'l'); // [2, 3] +indices(['h', 'e', 'l', 'l', 'o'], 'w'); // [] +``` \ No newline at end of file diff --git a/note/javascript/array/get-the-average-of-an-array.md b/note/javascript/array/get-the-average-of-an-array.md new file mode 100644 index 0000000..03846a6 --- /dev/null +++ b/note/javascript/array/get-the-average-of-an-array.md @@ -0,0 +1,22 @@ +--- +title: How to get the average of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get the average of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const average = arr => arr.reduce((a, b) => a + b, 0) / arr.length; +``` \ No newline at end of file diff --git a/note/javascript/array/get-the-intersection-of-arrays.md b/note/javascript/array/get-the-intersection-of-arrays.md new file mode 100644 index 0000000..52f3ed1 --- /dev/null +++ b/note/javascript/array/get-the-intersection-of-arrays.md @@ -0,0 +1,29 @@ +--- +title: How to get the intersection of arrays in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get the intersection of arrays only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getIntersection = (a, ...arr) => [...new Set(a)].filter(v => arr.every(b => b.includes(v))); +``` + +### Example + +```js {.wrap} +getIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3] +getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3] +``` diff --git a/note/javascript/array/get-the-rank-of-an-array-of-numbers.md b/note/javascript/array/get-the-rank-of-an-array-of-numbers.md new file mode 100644 index 0000000..63712bf --- /dev/null +++ b/note/javascript/array/get-the-rank-of-an-array-of-numbers.md @@ -0,0 +1,30 @@ +--- +title: How to get the rank of an array of numbers in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get the rank of an array of numbers only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const ranking = (arr) => arr.map((x, y, z) => z.filter(w => w > x).length + 1); +``` + +### Example + +```js {.wrap} +ranking([80, 65, 90, 50]); // [2, 3, 1, 4] +ranking([80, 80, 70, 50]); // [1, 1, 3, 4] +ranking([80, 80, 80, 50]); // [1, 1, 1, 4] +``` \ No newline at end of file diff --git a/note/javascript/array/get-the-sum-of-an-array-of-numbers.md b/note/javascript/array/get-the-sum-of-an-array-of-numbers.md new file mode 100644 index 0000000..fc1d85c --- /dev/null +++ b/note/javascript/array/get-the-sum-of-an-array-of-numbers.md @@ -0,0 +1,22 @@ +--- +title: How to get the sum of an array of numbers in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get the sum of an array of numbers only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const sum = arr => arr.reduce((a, b) => a + b, 0); +``` \ No newline at end of file diff --git a/note/javascript/array/get-the-unique-values-of-an-array.md b/note/javascript/array/get-the-unique-values-of-an-array.md new file mode 100644 index 0000000..e5ff060 --- /dev/null +++ b/note/javascript/array/get-the-unique-values-of-an-array.md @@ -0,0 +1,34 @@ +--- +title: How to get the unique values of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get the unique values of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const unique = arr => [...new Set(arr)]; +``` + +### Or + +```js {.wrap} +const unique = arr => arr.filter((el, i, array) => array.indexOf(el) === i); +``` + +### Or + +```js {.wrap} +const unique = arr => arr.reduce((acc, el) => acc.includes(el) ? acc : [...acc, el], []); +``` \ No newline at end of file diff --git a/note/javascript/array/get-union-of-arrays.md b/note/javascript/array/get-union-of-arrays.md new file mode 100644 index 0000000..9f557b3 --- /dev/null +++ b/note/javascript/array/get-union-of-arrays.md @@ -0,0 +1,28 @@ +--- +title: How to get union of arrays in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to get union of arrays only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const union = (...arr) => [...new Set(arr.flat())]; +``` + +### Example + +```js {.wrap} +union([1, 2], [2, 3], [3]); // [1, 2, 3] +``` \ No newline at end of file diff --git a/note/javascript/array/group-an-array-of-objects-by-a-key.md b/note/javascript/array/group-an-array-of-objects-by-a-key.md new file mode 100644 index 0000000..841327e --- /dev/null +++ b/note/javascript/array/group-an-array-of-objects-by-a-key.md @@ -0,0 +1,50 @@ +--- +title: How to group an array of objects by a key in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to group an array of objects by a key only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const groupBy = (arr, key) => arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {}); +``` + +### Example + +```js {.wrap} +groupBy([ + { branch: 'audi', model: 'q8', year: '2019' }, + { branch: 'audi', model: 'rs7', year: '2020' }, + { branch: 'ford', model: 'mustang', year: '2019' }, + { branch: 'ford', model: 'explorer', year: '2020' }, + { branch: 'bmw', model: 'x7', year: '2020' }, +], 'branch'); + +/* +{ + audi: [ + { branch: 'audi', model: 'q8', year: '2019' }, + { branch: 'audi', model: 'rs7', year: '2020' } + ], + bmw: [ + { branch: 'bmw', model: 'x7', year: '2020' } + ], + ford: [ + { branch: 'ford', model: 'mustang', year: '2019' }, + { branch: 'ford', model: 'explorer', year: '2020' } + ], +} +*/ +``` \ No newline at end of file diff --git a/note/javascript/array/merge-two-arrays.md b/note/javascript/array/merge-two-arrays.md new file mode 100644 index 0000000..6498c5c --- /dev/null +++ b/note/javascript/array/merge-two-arrays.md @@ -0,0 +1,38 @@ +--- +title: How to merge two arrays in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to merge two arrays only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Merge but don't remove the duplications +const merge = (a, b) => a.concat(b); +``` + +### Or + +```js {.wrap} +const merge = (a, b) => [...a, ...b]; + +// Merge and remove the duplications +const merge = [...new Set(a.concat(b))]; +``` + +### Or + +```js {.wrap} +const merge = [...new Set([...a, ...b])]; +``` \ No newline at end of file diff --git a/note/javascript/array/partition-an-array-based-on-a-condition.md b/note/javascript/array/partition-an-array-based-on-a-condition.md new file mode 100644 index 0000000..a2dd922 --- /dev/null +++ b/note/javascript/array/partition-an-array-based-on-a-condition.md @@ -0,0 +1,28 @@ +--- +title: How to partition an array based on a condition in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to partition an array based on a condition only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const partition = (arr, criteria) => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]); +``` + +### Example + +```js {.wrap} +partition([1, 2, 3, 4, 5], n => n % 2); // [[2, 4], [1, 3, 5]] +``` \ No newline at end of file diff --git a/note/javascript/array/remove-duplicate-values-in-an-array.md b/note/javascript/array/remove-duplicate-values-in-an-array.md new file mode 100644 index 0000000..7dad0bd --- /dev/null +++ b/note/javascript/array/remove-duplicate-values-in-an-array.md @@ -0,0 +1,28 @@ +--- +title: How to remove duplicate values in an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to remove duplicate values in an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const removeDuplicate = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); +``` + +### Example + +```js {.wrap} +removeDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); //  ['h', 'e', 'w', 'r', 'd'] +``` \ No newline at end of file diff --git a/note/javascript/array/remove-falsy-values-from-array.md b/note/javascript/array/remove-falsy-values-from-array.md new file mode 100644 index 0000000..69f3e70 --- /dev/null +++ b/note/javascript/array/remove-falsy-values-from-array.md @@ -0,0 +1,28 @@ +--- +title: How to remove falsy values from array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to remove falsy values from array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const removeFalsy = arr => arr.filter(Boolean); +``` + +### Example + +```js {.wrap} +removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]); // ['a string', true, 5, 'another string'] +``` \ No newline at end of file diff --git a/note/javascript/array/repeat-an-array.md b/note/javascript/array/repeat-an-array.md new file mode 100644 index 0000000..56b51ee --- /dev/null +++ b/note/javascript/array/repeat-an-array.md @@ -0,0 +1,50 @@ +--- +title: How to repeat an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to repeat an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const repeat = (arr, n) => [].concat(...Array(n).fill(arr)); +``` +Parameters `arr` is an array. + + + + +### Or + +```js {.wrap} +const repeat = (arr, n) => Array(n).fill(arr).flat(); +``` + +### Or + +```js {.wrap} +const repeat = (arr, n) => Array(arr.length * n).fill(0).map((_, i) => arr[i % arr.length]); +``` + +### Or + +```js {.wrap} +const repeat = (arr, n) => Array.from({ length: arr.length * n }, (_, i) => arr[i % arr.length]); +``` + +### Example + +```js {.wrap} +repeat([1, 2, 3], 3); // [1, 2, 3, 1, 2, 3, 1, 2, 3] +``` \ No newline at end of file diff --git a/note/javascript/array/shuffle-an-array.md b/note/javascript/array/shuffle-an-array.md new file mode 100644 index 0000000..8213092 --- /dev/null +++ b/note/javascript/array/shuffle-an-array.md @@ -0,0 +1,34 @@ +--- +title: How to shuffle an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to shuffle an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const shuffle = arr => arr.map(a => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map(a => a.value); +``` + +### Or + +```js {.wrap} +const shuffle = arr => arr.sort(() => .5 - Math.random()); +``` + +### Example + +```js {.wrap} +shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // [9, 1, 10, 6, 8, 5, 2, 3, 7, 4] +``` \ No newline at end of file diff --git a/note/javascript/array/sort-an-array-of-items-by-given-key.md b/note/javascript/array/sort-an-array-of-items-by-given-key.md new file mode 100644 index 0000000..f7ffbeb --- /dev/null +++ b/note/javascript/array/sort-an-array-of-items-by-given-key.md @@ -0,0 +1,42 @@ +--- +title: How to sort an array of items by given key in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to sort an array of items by given key only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const sortBy = (arr, k) => arr.concat().sort((a, b) => (a[k] > b[k]) ? 1 : ((a[k] < b[k]) ? -1 : 0)); +``` + +### Example + +```js {.wrap} +const people = [ + { name: 'Foo', age: 42 }, + { name: 'Bar', age: 24 }, + { name: 'Fuzz', age: 36 }, + { name: 'Baz', age: 32 }, +]; +sortBy(people, 'age'); + +// returns +// [ +// { name: 'Bar', age: 24 }, +// { name: 'Baz', age: 32 }, +// { name: 'Fuzz', age: 36 }, +// { name: 'Foo', age: 42 }, +// ] +``` \ No newline at end of file diff --git a/note/javascript/array/sort-an-array-of-numbers.md b/note/javascript/array/sort-an-array-of-numbers.md new file mode 100644 index 0000000..93a24d2 --- /dev/null +++ b/note/javascript/array/sort-an-array-of-numbers.md @@ -0,0 +1,28 @@ +--- +title: How to sort an array of numbers in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to sort an array of numbers only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const sort = arr => arr.sort((a, b) => a - b); +``` + +### Example + +```js {.wrap} +sort([1, 5, 2, 4, 3]); // [1, 2, 3, 4, 5] +``` \ No newline at end of file diff --git a/note/javascript/array/split-an-array-into-chunks.md b/note/javascript/array/split-an-array-into-chunks.md new file mode 100644 index 0000000..4d2b34a --- /dev/null +++ b/note/javascript/array/split-an-array-into-chunks.md @@ -0,0 +1,29 @@ +--- +title: How to split an array into chunks in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to split an array into chunks only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const chunk = (arr, size) => arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []); +``` + +### Example + +```js {.wrap} +chunk([1, 2, 3, 4, 5, 6, 7, 8], 3); // [[1, 2, 3], [4, 5, 6], [7, 8]] +chunk([1, 2, 3, 4, 5, 6, 7, 8], 4); // [[1, 2, 3, 4], [5, 6, 7, 8]] +``` \ No newline at end of file diff --git a/note/javascript/array/swap-the-rows-and-columns-of-a-matrix.md b/note/javascript/array/swap-the-rows-and-columns-of-a-matrix.md new file mode 100644 index 0000000..56b4d83 --- /dev/null +++ b/note/javascript/array/swap-the-rows-and-columns-of-a-matrix.md @@ -0,0 +1,44 @@ +--- +title: How to swap the rows and columns of a matrix in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to swap the rows and columns of a matrix only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const transpose = matrix => matrix[0].map((col, i) => matrix.map(row => row[i])); +``` + +### Or + +```js {.wrap} +const transpose = matrix => matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c])); +``` + +### Or + +```js {.wrap} +const transpose = matrix => matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), []); +``` + +### Example + +```js {.wrap} +transpose([ // [ + [1, 2, 3], // [1, 4, 7], + [4, 5, 6], // [2, 5, 8], + [7, 8, 9], // [3, 6, 9], +]); // ] +``` \ No newline at end of file diff --git a/note/javascript/array/swap-two-array-items.md b/note/javascript/array/swap-two-array-items.md new file mode 100644 index 0000000..b2e6686 --- /dev/null +++ b/note/javascript/array/swap-two-array-items.md @@ -0,0 +1,31 @@ +--- +title: How to swap two array items in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to swap two array items only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const swapItems = (a, i, j) => a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)] || a; +``` +Parameters `i` must be less than `j`. + + + +### Example + +```js {.wrap} +swapItems([1, 2, 3, 4, 5], 1, 4); // [1, 5, 3, 4, 2] +``` \ No newline at end of file diff --git a/note/javascript/array/unzip-an-array-of-arrays.md b/note/javascript/array/unzip-an-array-of-arrays.md new file mode 100644 index 0000000..9d6e962 --- /dev/null +++ b/note/javascript/array/unzip-an-array-of-arrays.md @@ -0,0 +1,36 @@ +--- +title: How to unzip an array of arrays in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to unzip an array of arrays only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const unzip = arr => arr.reduce((acc, c) => (c.forEach((v, i) => acc[i].push(v)), acc), Array.from({ length: Math.max(...arr.map(a => a.length)) }, (_) => [])); +``` + +### Example + +```js {.wrap} +unzip([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]); // [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]] + +/* + a 1 + b 2 + c 3 + d 4 + e 5 +*/ +``` \ No newline at end of file diff --git a/note/javascript/array/zip-multiple-arrays.md b/note/javascript/array/zip-multiple-arrays.md new file mode 100644 index 0000000..4d17ed9 --- /dev/null +++ b/note/javascript/array/zip-multiple-arrays.md @@ -0,0 +1,37 @@ +--- +title: How to zip multiple arrays in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Array +layout: note +--- + + + +In this Article we will go through how to zip multiple arrays only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const zip = (...arr) => Array.from({ length: Math.max(...arr.map(a => a.length)) }, (_, i) => arr.map(a => a[i])); +``` + +### Example + +```js {.wrap} +zip(['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]); // [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]] + +/* +Does it look like a zipper? + a 1 + b 2 + c 3 + d 4 + e 5 +*/ +``` \ No newline at end of file diff --git a/note/javascript/date-time/add-am-pm-suffix-to-an-hour.md b/note/javascript/date-time/add-am-pm-suffix-to-an-hour.md new file mode 100644 index 0000000..ff527e2 --- /dev/null +++ b/note/javascript/date-time/add-am-pm-suffix-to-an-hour.md @@ -0,0 +1,36 @@ +--- +title: How to add am pm suffix to an hour in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to add am pm suffix to an hour only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const suffixAmPm = h => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`; +``` +Parameters `h` is an hour number between 0 and 23. + + + + +### Example + +```js {.wrap} +suffixAmPm(0); // '12am' +suffixAmPm(5); // '5am' +suffixAmPm(12); // '12pm' +suffixAmPm(15); // '3pm' +suffixAmPm(23); // '11pm' +``` \ No newline at end of file diff --git a/note/javascript/date-time/calculate-the-number-of-difference-days-between-two-dates.md b/note/javascript/date-time/calculate-the-number-of-difference-days-between-two-dates.md new file mode 100644 index 0000000..2da3468 --- /dev/null +++ b/note/javascript/date-time/calculate-the-number-of-difference-days-between-two-dates.md @@ -0,0 +1,28 @@ +--- +title: How to calculate the number of difference days between two dates in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to calculate the number of difference days between two dates only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24)); +``` + +### Example + +```js {.wrap} +diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839 +``` \ No newline at end of file diff --git a/note/javascript/date-time/calculate-the-number-of-months-between-two-dates.md b/note/javascript/date-time/calculate-the-number-of-months-between-two-dates.md new file mode 100644 index 0000000..247d955 --- /dev/null +++ b/note/javascript/date-time/calculate-the-number-of-months-between-two-dates.md @@ -0,0 +1,28 @@ +--- +title: How to calculate the number of months between two dates in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to calculate the number of months between two dates only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const monthDiff = (startDate, endDate) => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth()); +``` + +### Example + +```js {.wrap} +monthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12 +``` diff --git a/note/javascript/date-time/compare-two-dates.md b/note/javascript/date-time/compare-two-dates.md new file mode 100644 index 0000000..af0f4a6 --- /dev/null +++ b/note/javascript/date-time/compare-two-dates.md @@ -0,0 +1,31 @@ +--- +title: How to compare two dates in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to compare two dates only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const compare = (a, b) => a.getTime() > b.getTime(); +``` +Parameters `a` and `b` are `Date` instances. + + + +### Example + +```js {.wrap} +compare(new Date('2020-03-30'), new Date('2020-01-01')); // true +``` \ No newline at end of file diff --git a/note/javascript/date-time/convert-a-date-to-yyyy-mm-dd-format.md b/note/javascript/date-time/convert-a-date-to-yyyy-mm-dd-format.md new file mode 100644 index 0000000..971635e --- /dev/null +++ b/note/javascript/date-time/convert-a-date-to-yyyy-mm-dd-format.md @@ -0,0 +1,32 @@ +--- +title: How to convert a date to yyyy-mm-dd format in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to convert a date to yyyy-mm-dd format only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const formatYmd = date => date.toISOString().slice(0, 10); +``` +Parameters `date` is a `Date` object. + + + + +### Example + +```js {.wrap} +formatYmd(new Date()); // 2020-05-06 +``` diff --git a/note/javascript/date-time/convert-seconds-to-hh-mm-ss-format.md b/note/javascript/date-time/convert-seconds-to-hh-mm-ss-format.md new file mode 100644 index 0000000..957e7b7 --- /dev/null +++ b/note/javascript/date-time/convert-seconds-to-hh-mm-ss-format.md @@ -0,0 +1,45 @@ +--- +title: How to convert seconds to hh:mm:ss format in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to convert seconds to hh:mm:ss format only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const formatSeconds = s => new Date(s * 1000).toISOString().substr(11, 8); +``` +Parameters `s` is number of seconds. + + + + +### Or + +```js {.wrap} +const formatSeconds = s => (new Date(s * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0]; +``` + +### Or + +```js {.wrap} +const formatSeconds = s => [parseInt(s / 60 / 60), parseInt(s / 60 % 60), parseInt(s % 60)].join(':').replace(/\b(\d)\b/g, '0$1'); +``` + +### Example + +```js {.wrap} +formatSeconds(200); // 00:03:20 +formatSeconds(500); // 00:08:20 +``` \ No newline at end of file diff --git a/note/javascript/date-time/extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.md b/note/javascript/date-time/extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.md new file mode 100644 index 0000000..4101dd1 --- /dev/null +++ b/note/javascript/date-time/extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.md @@ -0,0 +1,28 @@ +--- +title: How to extract year, month, day, hour, minute, second and millisecond from a date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to extract year, month, day, hour, minute, second and millisecond from a date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const extract = date => date.toISOString().split(/[^0-9]/).slice(0, -1); +``` +Parameters `date` is a `Date` object. + + +Parameters `extract` is an array of [year, month, day, hour, minute, second, millisecond]. + + diff --git a/note/javascript/date-time/format-a-date-for-the-given-locale.md b/note/javascript/date-time/format-a-date-for-the-given-locale.md new file mode 100644 index 0000000..e78672f --- /dev/null +++ b/note/javascript/date-time/format-a-date-for-the-given-locale.md @@ -0,0 +1,35 @@ +--- +title: How to format a date for the given locale in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to format a date for the given locale only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const format = (date, locale) => new Intl.DateTimeFormat(locale).format(date); +``` +Parameters `locale` is a locale (en-US, pt-BR, for example). + + +Parameters `date` is a `Date` object. + + + + +### Example + +```js {.wrap} +format(new Date(), 'pt-BR'); // 06/05/2020 +``` \ No newline at end of file diff --git a/note/javascript/date-time/get-the-current-quarter-of-a-date.md b/note/javascript/date-time/get-the-current-quarter-of-a-date.md new file mode 100644 index 0000000..d7d0771 --- /dev/null +++ b/note/javascript/date-time/get-the-current-quarter-of-a-date.md @@ -0,0 +1,22 @@ +--- +title: How to get the current quarter of a date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the current quarter of a date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getQuarter = (d = new Date()) => Math.ceil((d.getMonth() + 1) / 3); +``` \ No newline at end of file diff --git a/note/javascript/date-time/get-the-current-timestamp-in-seconds.md b/note/javascript/date-time/get-the-current-timestamp-in-seconds.md new file mode 100644 index 0000000..5eb1411 --- /dev/null +++ b/note/javascript/date-time/get-the-current-timestamp-in-seconds.md @@ -0,0 +1,22 @@ +--- +title: How to get the current timestamp in seconds in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the current timestamp in seconds only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const ts = () => Math.floor(new Date().getTime() / 1000); +``` \ No newline at end of file diff --git a/note/javascript/date-time/get-the-day-of-the-year-from-a-date.md b/note/javascript/date-time/get-the-day-of-the-year-from-a-date.md new file mode 100644 index 0000000..4ce7af3 --- /dev/null +++ b/note/javascript/date-time/get-the-day-of-the-year-from-a-date.md @@ -0,0 +1,32 @@ +--- +title: How to get the day of the year from a date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the day of the year from a date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const dayOfYear = date => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24)); +``` +Parameters `date` is a Date object. + + + + +### Example + +```js {.wrap} +dayOfYear(new Date(2020, 04, 16)); // 137 +``` \ No newline at end of file diff --git a/note/javascript/date-time/get-the-first-date-in-the-month-of-a-date.md b/note/javascript/date-time/get-the-first-date-in-the-month-of-a-date.md new file mode 100644 index 0000000..035d8c2 --- /dev/null +++ b/note/javascript/date-time/get-the-first-date-in-the-month-of-a-date.md @@ -0,0 +1,22 @@ +--- +title: How to get the first date in the month of a date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the first date in the month of a date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1); +``` \ No newline at end of file diff --git a/note/javascript/date-time/get-the-last-date-in-the-month-of-a-date.md b/note/javascript/date-time/get-the-last-date-in-the-month-of-a-date.md new file mode 100644 index 0000000..7b17dd7 --- /dev/null +++ b/note/javascript/date-time/get-the-last-date-in-the-month-of-a-date.md @@ -0,0 +1,22 @@ +--- +title: How to get the last date in the month of a date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the last date in the month of a date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 1, 0); +``` \ No newline at end of file diff --git a/note/javascript/date-time/get-the-month-name-of-a-date.md b/note/javascript/date-time/get-the-month-name-of-a-date.md new file mode 100644 index 0000000..0debaa8 --- /dev/null +++ b/note/javascript/date-time/get-the-month-name-of-a-date.md @@ -0,0 +1,25 @@ +--- +title: How to get the month name of a date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the month name of a date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getMonthName = date => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',' November', 'December'][date.getMonth()]; +``` +Parameters `date` is a Date object. + + diff --git a/note/javascript/date-time/get-the-number-of-days-in-given-month.md b/note/javascript/date-time/get-the-number-of-days-in-given-month.md new file mode 100644 index 0000000..04a109d --- /dev/null +++ b/note/javascript/date-time/get-the-number-of-days-in-given-month.md @@ -0,0 +1,25 @@ +--- +title: How to get the number of days in given month in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the number of days in given month only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const daysInMonth = (month, year) => new Date(year, month, 0).getDate(); +``` +Parameters `month` is zero-based index. + + diff --git a/note/javascript/date-time/get-the-timezone-string.md b/note/javascript/date-time/get-the-timezone-string.md new file mode 100644 index 0000000..6922b82 --- /dev/null +++ b/note/javascript/date-time/get-the-timezone-string.md @@ -0,0 +1,28 @@ +--- +title: How to get the timezone string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the timezone string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone; +``` + +### Example + +```js {.wrap} +getTimezone(); // 'Asia/Saigon' +``` \ No newline at end of file diff --git a/note/javascript/date-time/get-the-tomorrow-date.md b/note/javascript/date-time/get-the-tomorrow-date.md new file mode 100644 index 0000000..2014fca --- /dev/null +++ b/note/javascript/date-time/get-the-tomorrow-date.md @@ -0,0 +1,28 @@ +--- +title: How to get the tomorrow date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the tomorrow date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const tomorrow = (d => new Date(d.setDate(d.getDate() + 1)))(new Date); +``` + +### Or + +```js {.wrap} +const tomorrow = new Date((new Date()).valueOf() + 1000 * 60 * 60 * 24); +``` \ No newline at end of file diff --git a/note/javascript/date-time/get-the-total-number-of-days-in-a-year.md b/note/javascript/date-time/get-the-total-number-of-days-in-a-year.md new file mode 100644 index 0000000..c4d5a2d --- /dev/null +++ b/note/javascript/date-time/get-the-total-number-of-days-in-a-year.md @@ -0,0 +1,28 @@ +--- +title: How to get the total number of days in a year in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the total number of days in a year only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const numberOfDays = year => (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) ? 366 : 365; +``` + +### Or + +```js {.wrap} +const numberOfDays = year => new Date(year, 1, 29).getDate() === 29 ? 366 : 365; +``` \ No newline at end of file diff --git a/note/javascript/date-time/get-the-weekday-of-a-date.md b/note/javascript/date-time/get-the-weekday-of-a-date.md new file mode 100644 index 0000000..5ff2969 --- /dev/null +++ b/note/javascript/date-time/get-the-weekday-of-a-date.md @@ -0,0 +1,25 @@ +--- +title: How to get the weekday of a date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the weekday of a date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getWeekday = date => ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()]; +``` +Parameters `date` is a Date object. + + diff --git a/note/javascript/date-time/get-the-yesterday-date.md b/note/javascript/date-time/get-the-yesterday-date.md new file mode 100644 index 0000000..270c9cb --- /dev/null +++ b/note/javascript/date-time/get-the-yesterday-date.md @@ -0,0 +1,28 @@ +--- +title: How to get the yesterday date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to get the yesterday date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const yesterday = (d => new Date(d.setDate(d.getDate() - 1)))(new Date); +``` + +### Or + +```js {.wrap} +const yesterday = new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24); +``` \ No newline at end of file diff --git a/note/javascript/date-time/initialize-the-current-date-but-set-time-to-midnight.md b/note/javascript/date-time/initialize-the-current-date-but-set-time-to-midnight.md new file mode 100644 index 0000000..ae97f57 --- /dev/null +++ b/note/javascript/date-time/initialize-the-current-date-but-set-time-to-midnight.md @@ -0,0 +1,22 @@ +--- +title: How to initialize the current date but set time to midnight in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to initialize the current date but set time to midnight only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const midnightOfToday = () => new Date(new Date().setHours(0, 0, 0, 0)); +``` \ No newline at end of file diff --git a/note/javascript/date-time/sort-an-array-of-dates.md b/note/javascript/date-time/sort-an-array-of-dates.md new file mode 100644 index 0000000..d00c910 --- /dev/null +++ b/note/javascript/date-time/sort-an-array-of-dates.md @@ -0,0 +1,26 @@ +--- +title: How to sort an array of dates in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Date Time +layout: note +--- + + + +In this Article we will go through how to sort an array of dates only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const sortDescending = arr => arr.sort((a, b) => a.getTime() > b.getTime()); +const sortAscending = arr => arr.sort((a, b) => a.getTime() < b.getTime()); +``` +Parameters `arr` is an array of `Date` items. + + diff --git a/note/javascript/dom/check-if-an-element-is-a-descendant-of-another.md b/note/javascript/dom/check-if-an-element-is-a-descendant-of-another.md new file mode 100644 index 0000000..cac8f9e --- /dev/null +++ b/note/javascript/dom/check-if-an-element-is-a-descendant-of-another.md @@ -0,0 +1,22 @@ +--- +title: How to check if an element is a descendant of another in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to check if an element is a descendant of another only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isDescendant = (child, parent) => parent.contains(child); +``` \ No newline at end of file diff --git a/note/javascript/dom/check-if-an-element-is-focused.md b/note/javascript/dom/check-if-an-element-is-focused.md new file mode 100644 index 0000000..9d31cb6 --- /dev/null +++ b/note/javascript/dom/check-if-an-element-is-focused.md @@ -0,0 +1,22 @@ +--- +title: How to check if an element is focused in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to check if an element is focused only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const hasFocus = ele => (ele === document.activeElement); +``` \ No newline at end of file diff --git a/note/javascript/dom/check-if-the-touch-events-are-supported.md b/note/javascript/dom/check-if-the-touch-events-are-supported.md new file mode 100644 index 0000000..dca0a15 --- /dev/null +++ b/note/javascript/dom/check-if-the-touch-events-are-supported.md @@ -0,0 +1,22 @@ +--- +title: How to check if the touch events are supported in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to check if the touch events are supported only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const touchSupported = () => ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch); +``` \ No newline at end of file diff --git a/note/javascript/dom/check-if-user-scrolls-to-the-bottom-of-the-page.md b/note/javascript/dom/check-if-user-scrolls-to-the-bottom-of-the-page.md new file mode 100644 index 0000000..5d8ebcc --- /dev/null +++ b/note/javascript/dom/check-if-user-scrolls-to-the-bottom-of-the-page.md @@ -0,0 +1,22 @@ +--- +title: How to check if user scrolls to the bottom of the page in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to check if user scrolls to the bottom of the page only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight; +``` \ No newline at end of file diff --git a/note/javascript/dom/detect-internet-explorer-browser.md b/note/javascript/dom/detect-internet-explorer-browser.md new file mode 100644 index 0000000..ca74e0d --- /dev/null +++ b/note/javascript/dom/detect-internet-explorer-browser.md @@ -0,0 +1,20 @@ +--- +title: How to detect internet explorer browser in JavaScript +tags: + - JavaScript + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to detect internet explorer browser only using single line of code in JavaScript. +
+
+Let's define this short function: + +```js {.wrap} +const isIE = !!document.documentMode; +``` diff --git a/note/javascript/dom/detect-macos-browser.md b/note/javascript/dom/detect-macos-browser.md new file mode 100644 index 0000000..08e8001 --- /dev/null +++ b/note/javascript/dom/detect-macos-browser.md @@ -0,0 +1,20 @@ +--- +title: How to detect macos browser in JavaScript +tags: + - JavaScript + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to detect macos browser only using single line of code in JavaScript. +
+
+Let's define this short function: + +```js {.wrap} +const isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform); +``` \ No newline at end of file diff --git a/note/javascript/dom/get-all-siblings-of-an-element.md b/note/javascript/dom/get-all-siblings-of-an-element.md new file mode 100644 index 0000000..66ad631 --- /dev/null +++ b/note/javascript/dom/get-all-siblings-of-an-element.md @@ -0,0 +1,22 @@ +--- +title: How to get all siblings of an element in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to get all siblings of an element only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const siblings = ele => [].slice.call(ele.parentNode.children).filter((child) => (child !== ele)); +``` \ No newline at end of file diff --git a/note/javascript/dom/get-the-position-of-an-element-relative-to-the-document.md b/note/javascript/dom/get-the-position-of-an-element-relative-to-the-document.md new file mode 100644 index 0000000..c655ff3 --- /dev/null +++ b/note/javascript/dom/get-the-position-of-an-element-relative-to-the-document.md @@ -0,0 +1,28 @@ +--- +title: How to get the position of an element relative to the document in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to get the position of an element relative to the document only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getPosition = ele => (r = ele.getBoundingClientRect(), { left: r.left + window.scrollX, top: r.top + window.scrollY }); +``` + +### Example + +```js {.wrap} +getPosition(document.body); // { left: 0, top: 0 } +``` \ No newline at end of file diff --git a/note/javascript/dom/get-the-selected-text.md b/note/javascript/dom/get-the-selected-text.md new file mode 100644 index 0000000..9385667 --- /dev/null +++ b/note/javascript/dom/get-the-selected-text.md @@ -0,0 +1,22 @@ +--- +title: How to get the selected text in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to get the selected text only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getSelectedText = () => window.getSelection().toString(); +``` \ No newline at end of file diff --git a/note/javascript/dom/go-back-to-the-previous-page.md b/note/javascript/dom/go-back-to-the-previous-page.md new file mode 100644 index 0000000..ca48e3c --- /dev/null +++ b/note/javascript/dom/go-back-to-the-previous-page.md @@ -0,0 +1,28 @@ +--- +title: How to go back to the previous page in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to go back to the previous page only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +history.back(); +``` + +### Or + +```js {.wrap} +history.go(-1); +``` \ No newline at end of file diff --git a/note/javascript/dom/hide-an-element.md b/note/javascript/dom/hide-an-element.md new file mode 100644 index 0000000..75001f3 --- /dev/null +++ b/note/javascript/dom/hide-an-element.md @@ -0,0 +1,35 @@ +--- +title: How to hide an element in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to hide an element only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Pick the method that is suitable for your use case +const hide = ele => ele.style.display = 'none'; +``` + +### Or + +```js {.wrap} +const hide = ele => ele.style.visibility = 'hidden'; +``` + +### Or + +```js {.wrap} +const hide = ele => ele.hidden = true; +``` \ No newline at end of file diff --git a/note/javascript/dom/insert-an-element-after-other-one.md b/note/javascript/dom/insert-an-element-after-other-one.md new file mode 100644 index 0000000..f2194f7 --- /dev/null +++ b/note/javascript/dom/insert-an-element-after-other-one.md @@ -0,0 +1,28 @@ +--- +title: How to insert an element after other one in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to insert an element after other one only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling); +``` + +### Or + +```js {.wrap} +const insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele); +``` \ No newline at end of file diff --git a/note/javascript/dom/insert-an-element-before-other-one.md b/note/javascript/dom/insert-an-element-before-other-one.md new file mode 100644 index 0000000..ebcbb0c --- /dev/null +++ b/note/javascript/dom/insert-an-element-before-other-one.md @@ -0,0 +1,28 @@ +--- +title: How to insert an element before other one in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to insert an element before other one only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle); +``` + +### Or + +```js {.wrap} +const insertBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele); +``` \ No newline at end of file diff --git a/note/javascript/dom/insert-given-html-after-an-element.md b/note/javascript/dom/insert-given-html-after-an-element.md new file mode 100644 index 0000000..778f01e --- /dev/null +++ b/note/javascript/dom/insert-given-html-after-an-element.md @@ -0,0 +1,22 @@ +--- +title: How to insert given html after an element in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to insert given html after an element only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const insertHtmlAfter = (html, ele) => ele.insertAdjacentHTML('afterend', html); +``` \ No newline at end of file diff --git a/note/javascript/dom/insert-given-html-before-an-element.md b/note/javascript/dom/insert-given-html-before-an-element.md new file mode 100644 index 0000000..afe2dde --- /dev/null +++ b/note/javascript/dom/insert-given-html-before-an-element.md @@ -0,0 +1,22 @@ +--- +title: How to insert given html before an element in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to insert given html before an element only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const insertHtmlBefore = (html, ele) => ele.insertAdjacentHTML('beforebegin', html); +``` \ No newline at end of file diff --git a/note/javascript/dom/redirect-to-another-page.md b/note/javascript/dom/redirect-to-another-page.md new file mode 100644 index 0000000..9a95bd1 --- /dev/null +++ b/note/javascript/dom/redirect-to-another-page.md @@ -0,0 +1,22 @@ +--- +title: How to redirect to another page in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to redirect to another page only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const goTo = url => location.href = url; +``` \ No newline at end of file diff --git a/note/javascript/dom/reload-the-current-page.md b/note/javascript/dom/reload-the-current-page.md new file mode 100644 index 0000000..dbc2dcb --- /dev/null +++ b/note/javascript/dom/reload-the-current-page.md @@ -0,0 +1,28 @@ +--- +title: How to reload the current page in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to reload the current page only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const reload = () => location.reload(); +``` + +### Or + +```js {.wrap} +const reload = () => (location.href = location.href); +``` \ No newline at end of file diff --git a/note/javascript/dom/replace-an-element.md b/note/javascript/dom/replace-an-element.md new file mode 100644 index 0000000..d6f5bc5 --- /dev/null +++ b/note/javascript/dom/replace-an-element.md @@ -0,0 +1,22 @@ +--- +title: How to replace an element in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to replace an element only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const replace = (ele, newEle) => ele.parentNode.replaceChild(newEle, ele); +``` \ No newline at end of file diff --git a/note/javascript/dom/scroll-to-top-of-the-page.md b/note/javascript/dom/scroll-to-top-of-the-page.md new file mode 100644 index 0000000..121cb69 --- /dev/null +++ b/note/javascript/dom/scroll-to-top-of-the-page.md @@ -0,0 +1,22 @@ +--- +title: How to scroll to top of the page in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to scroll to top of the page only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const goToTop = () => window.scrollTo(0, 0); +``` \ No newline at end of file diff --git a/note/javascript/dom/serialize-form-data.md b/note/javascript/dom/serialize-form-data.md new file mode 100644 index 0000000..f81f677 --- /dev/null +++ b/note/javascript/dom/serialize-form-data.md @@ -0,0 +1,22 @@ +--- +title: How to serialize form data in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to serialize form data only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const serialize = formEle => Array.from(new FormData(formEle)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v}), {}); +``` \ No newline at end of file diff --git a/note/javascript/dom/show-an-element.md b/note/javascript/dom/show-an-element.md new file mode 100644 index 0000000..5a0ff7d --- /dev/null +++ b/note/javascript/dom/show-an-element.md @@ -0,0 +1,22 @@ +--- +title: How to show an element in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to show an element only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const show = ele => ele.style.display = ''; +``` \ No newline at end of file diff --git a/note/javascript/dom/strip-html-from-a-given-text.md b/note/javascript/dom/strip-html-from-a-given-text.md new file mode 100644 index 0000000..6dbd95b --- /dev/null +++ b/note/javascript/dom/strip-html-from-a-given-text.md @@ -0,0 +1,22 @@ +--- +title: How to strip html from a given text in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to strip html from a given text only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || ''; +``` \ No newline at end of file diff --git a/note/javascript/dom/toggle-an-element.md b/note/javascript/dom/toggle-an-element.md new file mode 100644 index 0000000..3370af0 --- /dev/null +++ b/note/javascript/dom/toggle-an-element.md @@ -0,0 +1,28 @@ +--- +title: How to toggle an element in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - DOM +layout: note +--- + + + +In this Article we will go through how to toggle an element only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toggle = ele => (ele.style.display = (ele.style.display === 'none') ? 'block' : 'none'); +``` + +### Or + +```js {.wrap} +const toggle = ele => ele.hidden = !ele.hidden; +``` \ No newline at end of file diff --git a/note/javascript/function/box-handler.md b/note/javascript/function/box-handler.md new file mode 100644 index 0000000..f1883de --- /dev/null +++ b/note/javascript/function/box-handler.md @@ -0,0 +1,38 @@ +--- +title: How to box handler in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to box handler only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const boxHandler = x => ({ next: f => boxHandler(f(x)), done: f => f(x) }); +``` + +### Example + +```js {.wrap} +const getPercentNumber = str => boxHandler(str).next(str => str.replace(/\%/, '')).next(str => parseFloat(str)).done(res => res * 0.01); + +getPercentNumber('50%'); // 0.5 + +// Example 2 +const getMoney = (price) => Number.parseFloat(price.replace(/\$/, '')); +const getPercent = (percent) => Number.parseFloat(percent.replace(/\%/)) * 0.01; + +const getDiscountPrice = (price, discount) => boxHandler(getMoney(price)).done(cents => boxHandler(getPercent(discount)).next(save => cents - (cents * save))).done(res => res); + +getDiscountPrice('$6.00', '20%'); // 4.8 +``` \ No newline at end of file diff --git a/note/javascript/function/check-if-a-value-is-a-function.md b/note/javascript/function/check-if-a-value-is-a-function.md new file mode 100644 index 0000000..709f51a --- /dev/null +++ b/note/javascript/function/check-if-a-value-is-a-function.md @@ -0,0 +1,30 @@ +--- +title: How to check if a value is a function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to check if a value is a function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isFunction = v => ['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(Object.prototype.toString.call(v)); +``` + +### Example + +```js {.wrap} +isFunction(function() {}); // true +isFunction(function*() {}); // true +isFunction(async function() {}); // true +``` \ No newline at end of file diff --git a/note/javascript/function/check-if-a-value-is-a-generator-function.md b/note/javascript/function/check-if-a-value-is-a-generator-function.md new file mode 100644 index 0000000..14408ce --- /dev/null +++ b/note/javascript/function/check-if-a-value-is-a-generator-function.md @@ -0,0 +1,29 @@ +--- +title: How to check if a value is a generator function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to check if a value is a generator function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isGeneratorFunction = v => Object.prototype.toString.call(v) === '[object GeneratorFunction]'; +``` + +### Example + +```js {.wrap} +isGeneratorFunction(function() {}); // false +isGeneratorFunction(function*() {}); // true +``` \ No newline at end of file diff --git a/note/javascript/function/check-if-a-value-is-an-async-function.md b/note/javascript/function/check-if-a-value-is-an-async-function.md new file mode 100644 index 0000000..8cfeafb --- /dev/null +++ b/note/javascript/function/check-if-a-value-is-an-async-function.md @@ -0,0 +1,30 @@ +--- +title: How to check if a value is an async function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to check if a value is an async function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isAsyncFunction = v => Object.prototype.toString.call(v) === '[object AsyncFunction]'; +``` + +### Example + +```js {.wrap} +isAsyncFunction(function() {}); // false +isAsyncFunction(function*() {}); // false +isAsyncFunction(async function() {}); // true +``` \ No newline at end of file diff --git a/note/javascript/function/compose-functions-from-left-to-right.md b/note/javascript/function/compose-functions-from-left-to-right.md new file mode 100644 index 0000000..8eeb5f2 --- /dev/null +++ b/note/javascript/function/compose-functions-from-left-to-right.md @@ -0,0 +1,36 @@ +--- +title: How to compose functions from left to right in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to compose functions from left to right only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Compose functions from left to right +const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x); +``` + +### Example + +```js {.wrap} +const lowercase = str => str.toLowerCase(); +const capitalize = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; +const reverse = str => str.split('').reverse().join(''); + +const fn = pipe(lowercase, capitalize, reverse); + +// We will execute `lowercase`, `capitalize` and `reverse` in order +fn('Hello World') === 'dlrow olleH'; +``` \ No newline at end of file diff --git a/note/javascript/function/compose-functions.md b/note/javascript/function/compose-functions.md new file mode 100644 index 0000000..6758c32 --- /dev/null +++ b/note/javascript/function/compose-functions.md @@ -0,0 +1,36 @@ +--- +title: How to compose functions in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to compose functions only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Compose functions from right to left +const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x); +``` + +### Example + +```js {.wrap} +const lowercase = str => str.toLowerCase(); +const capitalize = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; +const reverse = str => str.split('').reverse().join(''); + +const fn = compose(reverse, capitalize, lowercase); + +// We will execute `lowercase`, `capitalize` and `reverse` in order +fn('Hello World') === 'dlrow olleH'; +``` \ No newline at end of file diff --git a/note/javascript/function/create-a-function-that-accepts-a-single-argument.md b/note/javascript/function/create-a-function-that-accepts-a-single-argument.md new file mode 100644 index 0000000..d7538ac --- /dev/null +++ b/note/javascript/function/create-a-function-that-accepts-a-single-argument.md @@ -0,0 +1,28 @@ +--- +title: How to create a function that accepts a single argument in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to create a function that accepts a single argument only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const unary = fn => arg => fn(arg); +``` + +### Example + +```js {.wrap} +['1', '2', '3', '4', '5'].map(unary(parseInt)); // [1, 2, 3, 4, 5] +``` \ No newline at end of file diff --git a/note/javascript/function/create-an-empty-function.md b/note/javascript/function/create-an-empty-function.md new file mode 100644 index 0000000..1d2dcd1 --- /dev/null +++ b/note/javascript/function/create-an-empty-function.md @@ -0,0 +1,29 @@ +--- +title: How to create an empty function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to create an empty function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const noop = () => {}; +``` + +### Or + +```js {.wrap} +const noop = Function(); +// calling Function() might be detected as using eval by some security tools +``` diff --git a/note/javascript/function/curry-a-function.md b/note/javascript/function/curry-a-function.md new file mode 100644 index 0000000..110528c --- /dev/null +++ b/note/javascript/function/curry-a-function.md @@ -0,0 +1,34 @@ +--- +title: How to curry a function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to curry a function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const curry = (fn, ...args) => fn.length <= args.length ? fn(...args) : curry.bind(null, fn, ...args); +``` + +### Example + +```js {.wrap} +const sum = (a, b, c) => a + b + c; +curry(sum)(1)(2)(3); // 6 +curry(sum)(1, 2, 3); // 6 +curry(sum, 1)(2, 3); // 6 +curry(sum, 1)(2)(3); // 6 +curry(sum, 1, 2)(3); // 6 +curry(sum, 1, 2, 3); // 6 +``` \ No newline at end of file diff --git a/note/javascript/function/delay-the-evaluation-of-a-function.md b/note/javascript/function/delay-the-evaluation-of-a-function.md new file mode 100644 index 0000000..11d9143 --- /dev/null +++ b/note/javascript/function/delay-the-evaluation-of-a-function.md @@ -0,0 +1,33 @@ +--- +title: How to delay the evaluation of a function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to delay the evaluation of a function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// returns a new version of `fn` that returns values as lazy evaluable +const thunkfy = fn => (...args) => () => fn(...args); +``` + +### Example + +```js {.wrap} +const heavyComputation = x => doStuff(x); +const unnecessarySlow = manyThings.map(heavyComputation) + .find(result => result.criteria); +const probablyFaster = manyThings.map(thunkfy(heavyComputation)) + .find(thunk => thunk().criteria); +``` \ No newline at end of file diff --git a/note/javascript/function/execute-a-function-once.md b/note/javascript/function/execute-a-function-once.md new file mode 100644 index 0000000..b2354d4 --- /dev/null +++ b/note/javascript/function/execute-a-function-once.md @@ -0,0 +1,32 @@ +--- +title: How to execute a function once in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to execute a function once only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const once = fn => ((ran = false) => () => ran ? fn : (ran = !ran, fn = fn()))(); +``` + +### Example + +```js {.wrap} +let n = 0; +const incOnce = once(() => ++n); +incOnce(); // n = 1 +incOnce(); // n = 1 +incOnce(); // n = 1 +``` \ No newline at end of file diff --git a/note/javascript/function/flip-the-arguments-of-a-function.md b/note/javascript/function/flip-the-arguments-of-a-function.md new file mode 100644 index 0000000..aa8fb85 --- /dev/null +++ b/note/javascript/function/flip-the-arguments-of-a-function.md @@ -0,0 +1,39 @@ +--- +title: How to flip the arguments of a function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to flip the arguments of a function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Reverse the order of arguments +const flip = fn => (...args) => fn(...args.reverse()); + +// For binary functions +const flip = fn => (b, a) => fn(a, b); +``` + +### Or for curried functions + +```js {.wrap} +const flip = fn => b => a => fn(a)(b); +``` + +### Example + +```js {.wrap} +const isParent = (parent, child) => parent.children.includes(child); +const isChild = flip(isParent); +``` \ No newline at end of file diff --git a/note/javascript/function/identity-function.md b/note/javascript/function/identity-function.md new file mode 100644 index 0000000..67ae30d --- /dev/null +++ b/note/javascript/function/identity-function.md @@ -0,0 +1,22 @@ +--- +title: How to identity function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to identity function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const identity = x => x; +``` \ No newline at end of file diff --git a/note/javascript/function/logical-xor-operator.md b/note/javascript/function/logical-xor-operator.md new file mode 100644 index 0000000..ad2a27b --- /dev/null +++ b/note/javascript/function/logical-xor-operator.md @@ -0,0 +1,45 @@ +--- +title: How to logical xor operator in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to logical xor operator only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// returns `true` if one of the arguments is truthy and the other is falsy + +const xor = (a, b) => (a && !b) || (!a && b); +``` + +### Or + +```js {.wrap} +const xor = (a, b) => !(!a && !b) && !(a && b); +``` + +### Or + +```js {.wrap} +const xor = (a, b) => Boolean(!a ^ !b); +``` + +### Example + +```js {.wrap} +xor(true, true); // false +xor(false, false); // false +xor(true, false); // true +xor(false, true); // true +``` \ No newline at end of file diff --git a/note/javascript/function/memoize-a-function.md b/note/javascript/function/memoize-a-function.md new file mode 100644 index 0000000..fc6067b --- /dev/null +++ b/note/javascript/function/memoize-a-function.md @@ -0,0 +1,36 @@ +--- +title: How to memoize a function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to memoize a function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const memoize = fn => ((cache = {}) => arg => cache[arg] || (cache[arg] = fn(arg)))(); +``` + +### Example + +```js {.wrap} +// Calculate Fibonacci numbers +const fibo = memoize(n => n <= 2 ? 1 : fibo(n - 1) + fibo(n - 2)); + +fibo(1); // 1 +fibo(2); // 1 +fibo(3); // 2 +fibo(4); // 3 +fibo(5); // 5 +fibo(6); // 8 +``` \ No newline at end of file diff --git a/note/javascript/function/partially-apply-a-function.md b/note/javascript/function/partially-apply-a-function.md new file mode 100644 index 0000000..f35f9e7 --- /dev/null +++ b/note/javascript/function/partially-apply-a-function.md @@ -0,0 +1,30 @@ +--- +title: How to partially apply a function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to partially apply a function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const partial = (fn, ...a) => (...b) => fn(...a, ...b); +``` + +### Example + +```js {.wrap} +const sum = (x, y) => x + y; +const inc = partial(sum, 1); +inc(9); // 10 +``` \ No newline at end of file diff --git a/note/javascript/function/uncurry-a-function.md b/note/javascript/function/uncurry-a-function.md new file mode 100644 index 0000000..afba427 --- /dev/null +++ b/note/javascript/function/uncurry-a-function.md @@ -0,0 +1,38 @@ +--- +title: How to uncurry a function in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Function +layout: note +--- + + + +In this Article we will go through how to uncurry a function only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const uncurry = (fn, n = 1) => (...args) => (acc => args => args.reduce((x, y) => x(y), acc))(fn)(args.slice(0, n)); +``` +Parameters `fn` is a curried function. + + +Parameters `n` is the depth of parameters. + + + + +### Example + +```js {.wrap} +const sum = a => b => c => a + b + c; +uncurry(sum, 1)(1)(2)(3); // 6 +uncurry(sum, 2)(1, 2)(3); // 6 +uncurry(sum, 3)(1, 2, 3); // 6 +``` \ No newline at end of file diff --git a/note/javascript/math/calculate-the-angle-of-a-line-defined-by-two-points.md b/note/javascript/math/calculate-the-angle-of-a-line-defined-by-two-points.md new file mode 100644 index 0000000..b2ecbc8 --- /dev/null +++ b/note/javascript/math/calculate-the-angle-of-a-line-defined-by-two-points.md @@ -0,0 +1,26 @@ +--- +title: How to calculate the angle of a line defined by two points in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to calculate the angle of a line defined by two points only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// In radians +const radiansAngle = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x); + +// In degrees +const degreesAngle = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI; +``` \ No newline at end of file diff --git a/note/javascript/math/calculate-the-distance-between-two-points.md b/note/javascript/math/calculate-the-distance-between-two-points.md new file mode 100644 index 0000000..b2a12b8 --- /dev/null +++ b/note/javascript/math/calculate-the-distance-between-two-points.md @@ -0,0 +1,22 @@ +--- +title: How to calculate the distance between two points in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to calculate the distance between two points only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const distance = (p1, p2) => Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)); +``` \ No newline at end of file diff --git a/note/javascript/math/calculate-the-linear-interpolation-between-two-numbers.md b/note/javascript/math/calculate-the-linear-interpolation-between-two-numbers.md new file mode 100644 index 0000000..f23a2b1 --- /dev/null +++ b/note/javascript/math/calculate-the-linear-interpolation-between-two-numbers.md @@ -0,0 +1,22 @@ +--- +title: How to calculate the linear interpolation between two numbers in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to calculate the linear interpolation between two numbers only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const lerp = (a, b, amount) => (1 - amount) * a + amount * b; +``` \ No newline at end of file diff --git a/note/javascript/math/calculate-the-midpoint-between-two-points.md b/note/javascript/math/calculate-the-midpoint-between-two-points.md new file mode 100644 index 0000000..25b4be4 --- /dev/null +++ b/note/javascript/math/calculate-the-midpoint-between-two-points.md @@ -0,0 +1,22 @@ +--- +title: How to calculate the midpoint between two points in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to calculate the midpoint between two points only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const midpoint = (p1, p2) => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2]; +``` \ No newline at end of file diff --git a/note/javascript/math/check-if-a-point-is-inside-a-rectangle.md b/note/javascript/math/check-if-a-point-is-inside-a-rectangle.md new file mode 100644 index 0000000..dbdc3c2 --- /dev/null +++ b/note/javascript/math/check-if-a-point-is-inside-a-rectangle.md @@ -0,0 +1,22 @@ +--- +title: How to check if a point is inside a rectangle in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to check if a point is inside a rectangle only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isInside = (point, rect) => point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom; +``` \ No newline at end of file diff --git a/note/javascript/math/check-if-a-rectangle-contains-other-one.md b/note/javascript/math/check-if-a-rectangle-contains-other-one.md new file mode 100644 index 0000000..75e2a13 --- /dev/null +++ b/note/javascript/math/check-if-a-rectangle-contains-other-one.md @@ -0,0 +1,24 @@ +--- +title: How to check if a rectangle contains other one in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to check if a rectangle contains other one only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Returns true if `a` contains `b` +// (x1, y1) and (x2, y2) are top-left and bottom-right corners +const contains = (a, b) => (a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2); +``` \ No newline at end of file diff --git a/note/javascript/math/check-if-a-rectangle-overlaps-other-one.md b/note/javascript/math/check-if-a-rectangle-overlaps-other-one.md new file mode 100644 index 0000000..caa2da5 --- /dev/null +++ b/note/javascript/math/check-if-a-rectangle-overlaps-other-one.md @@ -0,0 +1,24 @@ +--- +title: How to check if a rectangle overlaps other one in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to check if a rectangle overlaps other one only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Returns true if `a` overlaps `b` +// (x1, y1) and (x2, y2) are top-left and bottom-right corners +const overlaps = (a, b) => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2); +``` \ No newline at end of file diff --git a/note/javascript/math/convert-degrees-to-radians.md b/note/javascript/math/convert-degrees-to-radians.md new file mode 100644 index 0000000..cc1a655 --- /dev/null +++ b/note/javascript/math/convert-degrees-to-radians.md @@ -0,0 +1,22 @@ +--- +title: How to convert degrees to radians in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to convert degrees to radians only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const degsToRads = deg => deg * Math.PI / 180.0; +``` \ No newline at end of file diff --git a/note/javascript/math/convert-radians-to-degrees.md b/note/javascript/math/convert-radians-to-degrees.md new file mode 100644 index 0000000..e4218de --- /dev/null +++ b/note/javascript/math/convert-radians-to-degrees.md @@ -0,0 +1,22 @@ +--- +title: How to convert radians to degrees in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to convert radians to degrees only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const radsToDegs = rad => rad * 180 / Math.PI; +``` \ No newline at end of file diff --git a/note/javascript/math/normalize-the-ratio-of-a-number-in-a-range.md b/note/javascript/math/normalize-the-ratio-of-a-number-in-a-range.md new file mode 100644 index 0000000..815094a --- /dev/null +++ b/note/javascript/math/normalize-the-ratio-of-a-number-in-a-range.md @@ -0,0 +1,22 @@ +--- +title: How to normalize the ratio of a number in a range in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to normalize the ratio of a number in a range only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const normalizeRatio = (value, min, max) => (value - min) / (max - min); +``` \ No newline at end of file diff --git a/note/javascript/math/round-a-number-to-the-nearest-multiple-of-a-given-value.md b/note/javascript/math/round-a-number-to-the-nearest-multiple-of-a-given-value.md new file mode 100644 index 0000000..630cd91 --- /dev/null +++ b/note/javascript/math/round-a-number-to-the-nearest-multiple-of-a-given-value.md @@ -0,0 +1,30 @@ +--- +title: How to round a number to the nearest multiple of a given value in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Math +layout: note +--- + + + +In this Article we will go through how to round a number to the nearest multiple of a given value only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const roundNearest = (value, nearest) => Math.round(value / nearest) * nearest; +``` + +### Example + +```js {.wrap} +roundNearest(100, 30); // 90 +roundNearest(200, 30); // 210 +roundNearest(200, 40); // 200 +``` \ No newline at end of file diff --git a/note/javascript/misc/check-if-the-code-is-running-in-node-js.md b/note/javascript/misc/check-if-the-code-is-running-in-node-js.md new file mode 100644 index 0000000..ac77bed --- /dev/null +++ b/note/javascript/misc/check-if-the-code-is-running-in-node-js.md @@ -0,0 +1,19 @@ +--- +title: How to check if the code is running in nodejs in JavaScript +tags: + - JavaScript + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to check if the code is running in nodejs only using single line of code in JavaScript. +
+
+Let's define this short function: + +```js {.wrap} +const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null; +``` \ No newline at end of file diff --git a/note/javascript/misc/check-if-the-code-is-running-in-the-browser.md b/note/javascript/misc/check-if-the-code-is-running-in-the-browser.md new file mode 100644 index 0000000..db4da16 --- /dev/null +++ b/note/javascript/misc/check-if-the-code-is-running-in-the-browser.md @@ -0,0 +1,19 @@ +--- +title: How to check if the code is running in the browser in JavaScript +tags: + - JavaScript + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to check if the code is running in the browser only using single line of code in JavaScript. +
+
+Let's define this short function: + +```js {.wrap} +const isBrowser = typeof window === 'object' && typeof document === 'object'; +``` \ No newline at end of file diff --git a/note/javascript/misc/clear-all-cookies.md b/note/javascript/misc/clear-all-cookies.md new file mode 100644 index 0000000..74e3638 --- /dev/null +++ b/note/javascript/misc/clear-all-cookies.md @@ -0,0 +1,27 @@ +--- +title: How to clear all cookies in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to clear all cookies only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const clearCookies = () => document.cookie.split(';').forEach(c => document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)); +``` + +### Example + +```js {.wrap} +clearCookies(); +``` diff --git a/note/javascript/misc/convert-3-digits-color-to-6-digits-color.md b/note/javascript/misc/convert-3-digits-color-to-6-digits-color.md new file mode 100644 index 0000000..e5456c3 --- /dev/null +++ b/note/javascript/misc/convert-3-digits-color-to-6-digits-color.md @@ -0,0 +1,29 @@ +--- +title: How to convert 3 digits color to 6 digits color in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to convert 3 digits color to 6 digits color only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toFullHexColor = color => `#${(color.startsWith('#') ? color.slice(1) : color).split('').map(c => `${c}${c}`).join('')}`; +``` + +### Example + +```js {.wrap} +toFullHexColor('123'); // '#112233' +toFullHexColor('#123'); // '#112233' +toFullHexColor('#abc'); // '#aabbcc' +``` \ No newline at end of file diff --git a/note/javascript/misc/convert-celsius-to-fahrenheit.md b/note/javascript/misc/convert-celsius-to-fahrenheit.md new file mode 100644 index 0000000..18adf08 --- /dev/null +++ b/note/javascript/misc/convert-celsius-to-fahrenheit.md @@ -0,0 +1,29 @@ +--- +title: How to convert celsius to fahrenheit in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to convert celsius to fahrenheit only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const celsiusToFahrenheit = celsius => celsius * 9/5 + 32; +``` + +### Example + +```js {.wrap} +celsiusToFahrenheit(15); // 59 +celsiusToFahrenheit(0); // 32 +celsiusToFahrenheit(-20); // -4 +``` \ No newline at end of file diff --git a/note/javascript/misc/convert-cookie-to-object.md b/note/javascript/misc/convert-cookie-to-object.md new file mode 100644 index 0000000..9a4dc88 --- /dev/null +++ b/note/javascript/misc/convert-cookie-to-object.md @@ -0,0 +1,21 @@ +--- +title: How to convert cookie to object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to convert cookie to object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const cookies = document.cookie.split(';').map(item => item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {}); +``` \ No newline at end of file diff --git a/note/javascript/misc/convert-fahrenheit-to-celsius.md b/note/javascript/misc/convert-fahrenheit-to-celsius.md new file mode 100644 index 0000000..5dd3370 --- /dev/null +++ b/note/javascript/misc/convert-fahrenheit-to-celsius.md @@ -0,0 +1,28 @@ +--- +title: How to convert fahrenheit to celsius in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to convert fahrenheit to celsius only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const fahrenheitToCelsius = fahrenheit => (fahrenheit - 32) * 5/9; +``` + +### Example + +```js {.wrap} +fahrenheitToCelsius(59); // 15 +fahrenheitToCelsius(32); // 0 +``` \ No newline at end of file diff --git a/note/javascript/misc/convert-hex-to-rgb.md b/note/javascript/misc/convert-hex-to-rgb.md new file mode 100644 index 0000000..ed0449e --- /dev/null +++ b/note/javascript/misc/convert-hex-to-rgb.md @@ -0,0 +1,28 @@ +--- +title: How to convert hex to rgb in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to convert hex to rgb only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const hexToRgb = hex => hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`).substring(1).match(/.{2}/g).map(x => parseInt(x, 16)); +``` + +### Example + +```js {.wrap} +hexToRgb('#00ffff'); // [0, 255, 255] +hexToRgb('#0ff'); // [0, 255, 255] +``` \ No newline at end of file diff --git a/note/javascript/misc/convert-rgb-color-to-hex.md b/note/javascript/misc/convert-rgb-color-to-hex.md new file mode 100644 index 0000000..3fa0448 --- /dev/null +++ b/note/javascript/misc/convert-rgb-color-to-hex.md @@ -0,0 +1,33 @@ +--- +title: How to convert rgb color to hex in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to convert rgb color to hex only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const rgbToHex = (red, green, blue) => `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`; +``` + +### Or + +```js {.wrap} +const rgbToHex = (red, green, blue) => `#${[red, green, blue].map(v => v.toString(16).padStart(2, '0')).join('')}`; +``` + +### Example + +```js {.wrap} +rgbToHex(0, 255, 255); // '#00ffff' +``` \ No newline at end of file diff --git a/note/javascript/misc/convert-url-parameters-to-object.md b/note/javascript/misc/convert-url-parameters-to-object.md new file mode 100644 index 0000000..20f452c --- /dev/null +++ b/note/javascript/misc/convert-url-parameters-to-object.md @@ -0,0 +1,32 @@ +--- +title: How to convert url parameters to object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to convert url parameters to object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getUrlParams = query => Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v}), {}); +``` + +### Example + +```js {.wrap} +getUrlParams(location.search); // Get the parameters of the current URL + +getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" } + +// Duplicate key +getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" } +``` \ No newline at end of file diff --git a/note/javascript/misc/decode-a-jwt-token.md b/note/javascript/misc/decode-a-jwt-token.md new file mode 100644 index 0000000..8571666 --- /dev/null +++ b/note/javascript/misc/decode-a-jwt-token.md @@ -0,0 +1,33 @@ +--- +title: How to decode a jwt token in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to decode a jwt token only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const decode = token => decodeURIComponent(atob(token.split('.')[1].replace('-', '+').replace('_', '/')).split('').map(c => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`).join('')); +``` + +### Example + +```js {.wrap} +decode(` + eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. + eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0I + joxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +`); + +// { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 } +``` \ No newline at end of file diff --git a/note/javascript/misc/detect-dark-mode.md b/note/javascript/misc/detect-dark-mode.md new file mode 100644 index 0000000..3198de3 --- /dev/null +++ b/note/javascript/misc/detect-dark-mode.md @@ -0,0 +1,19 @@ +--- +title: How to detect dark mode in JavaScript +tags: + - JavaScript + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to detect dark mode only using single line of code in JavaScript. +
+
+Let's define this short function: + +```js {.wrap} +const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; +``` \ No newline at end of file diff --git a/note/javascript/misc/easing-functions.md b/note/javascript/misc/easing-functions.md new file mode 100644 index 0000000..a5a859d --- /dev/null +++ b/note/javascript/misc/easing-functions.md @@ -0,0 +1,48 @@ +--- +title: How to easing functions in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to easing functions only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Some easing functions +// See https://gist.github.com/gre/1650294 and https://easings.net + +const linear = t => t; + +const easeInQuad = t => t * t; +const easeOutQuad = t => t * (2-t); +const easeInOutQuad = t => t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t; + +const easeInCubic = t => t * t * t; +const easeOutCubic = t => (--t) * t * t + 1; +const easeInOutCubic = t => t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1; + +const easeInQuart = t => t * t * t * t; +const easeOutQuart = t => 1 - (--t) * t * t * t; +const easeInOutQuart = t => t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t; + +const easeInQuint = t => t * t * t * t * t; +const easeOutQuint = t => 1 + (--t) * t * t * t * t; +const easeInOutQuint = t => t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t; + +const easeInSine = t => 1 + Math.sin(Math.PI / 2 * t - Math.PI / 2); +const easeOutSine = t => Math.sin(Math.PI / 2 * t); +const easeInOutSine = t => (1 + Math.sin(Math.PI * t - Math.PI / 2)) / 2; + +const easeInElastic = t => (.04 - .04 / t) * Math.sin(25 * t) + 1; +const easeOutElastic = t => .04 * t / (--t) * Math.sin(25 * t); +const easeInOutElastic = t => (t -= .5) < 0 ? (.02 + .01 / t) * Math.sin(50 * t) : (.02 - .01 / t) * Math.sin(50 * t) + 1; +``` \ No newline at end of file diff --git a/note/javascript/misc/emulate-a-dice-throw.md b/note/javascript/misc/emulate-a-dice-throw.md new file mode 100644 index 0000000..4a7150e --- /dev/null +++ b/note/javascript/misc/emulate-a-dice-throw.md @@ -0,0 +1,29 @@ +--- +title: How to emulate a dice throw in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to emulate a dice throw only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const throwdice = () => ~~(Math.random() * 6) + 1; +``` + +### Example + +```js {.wrap} +throwdice(); // 4 +throwdice(); // 1 +throwdice(); // 6 +``` \ No newline at end of file diff --git a/note/javascript/misc/encode-a-url.md b/note/javascript/misc/encode-a-url.md new file mode 100644 index 0000000..a0cc8dd --- /dev/null +++ b/note/javascript/misc/encode-a-url.md @@ -0,0 +1,24 @@ +--- +title: How to encode a url in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to encode a url only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const encode = url => encodeURIComponent(url).replace(/!/g, '%21').replace(/~/g, '%7E').replace(/\*/g, '%2A').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%20/g, '+'); +``` +Parameters `encodeURIComponent` doesn't encode -_.!~*'(). + + diff --git a/note/javascript/misc/generate-an-unique-and-increment-id.md b/note/javascript/misc/generate-an-unique-and-increment-id.md new file mode 100644 index 0000000..6f90738 --- /dev/null +++ b/note/javascript/misc/generate-an-unique-and-increment-id.md @@ -0,0 +1,30 @@ +--- +title: How to generate an unique and increment id in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to generate an unique and increment id only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const uid = (() => (id = 0, () => id++))(); +``` + +### Example + +```js {.wrap} +uid(); // 0 +uid(); // 1 +uid(); // 2 +uid(); // 3 +``` \ No newline at end of file diff --git a/note/javascript/misc/get-the-first-defined-and-non-null-argument.md b/note/javascript/misc/get-the-first-defined-and-non-null-argument.md new file mode 100644 index 0000000..73c43e5 --- /dev/null +++ b/note/javascript/misc/get-the-first-defined-and-non-null-argument.md @@ -0,0 +1,33 @@ +--- +title: How to get the first defined and non null argument in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to get the first defined and non null argument only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const coalesce = (...args) => args.find(item => item !== undefined && item !== null); +``` + +### Or + +```js {.wrap} +const coalesce = (...args) => args.find(item => ![undefined, null].includes(item)); +``` + +### Example + +```js {.wrap} +coalesce(undefined, null, 'helloworld', NaN); // 'helloworld' +``` \ No newline at end of file diff --git a/note/javascript/misc/get-the-value-of-a-cookie.md b/note/javascript/misc/get-the-value-of-a-cookie.md new file mode 100644 index 0000000..f792c06 --- /dev/null +++ b/note/javascript/misc/get-the-value-of-a-cookie.md @@ -0,0 +1,27 @@ +--- +title: How to get the value of a cookie in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to get the value of a cookie only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift(); +``` + +### Example + +```js {.wrap} +cookie('_ga'); // GA1.2.825309271.1581874719 +``` \ No newline at end of file diff --git a/note/javascript/misc/get-the-value-of-a-param-from-a-url.md b/note/javascript/misc/get-the-value-of-a-param-from-a-url.md new file mode 100644 index 0000000..2b746dd --- /dev/null +++ b/note/javascript/misc/get-the-value-of-a-param-from-a-url.md @@ -0,0 +1,27 @@ +--- +title: How to get the value of a param from a url in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to get the value of a param from a url only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param); +``` + +### Example + +```js {.wrap} +getParam('http://domain.com?message=hello', 'message'); // 'hello' +``` \ No newline at end of file diff --git a/note/javascript/misc/get-type-of-a-variable-in-string.md b/note/javascript/misc/get-type-of-a-variable-in-string.md new file mode 100644 index 0000000..718926f --- /dev/null +++ b/note/javascript/misc/get-type-of-a-variable-in-string.md @@ -0,0 +1,42 @@ +--- +title: How to get type of a variable in string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to get type of a variable in string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getTypeOf = obj => Object.prototype.toString.call(obj).match(/\[object (.*)\]/)[1]; +``` + +### Example + +```js {.wrap} +getTypeOf('hello world'); // String +getTypeOf(1000); // Number +getTypeOf(Infinity); // Number +getTypeOf(true); // Boolean +getTypeOf(Symbol()); // Symbol +getTypeOf(null); // Null +getTypeOf(undefined); // Undefined +getTypeOf({}); // Object +getTypeOf([]); // Array +getTypeOf(/[a-z]/g); // RegExp +getTypeOf(new Date(2021)); // Date +getTypeOf(new Error()); // Error +getTypeOf(function() {}); // Function +getTypeOf((a, b) => a + b); // Function +getTypeOf(async () => {}); // AsyncFunction +getTypeOf(document); // HTMLDocument +``` \ No newline at end of file diff --git a/note/javascript/misc/redirect-the-page-to-https-if-it-is-in-http.md b/note/javascript/misc/redirect-the-page-to-https-if-it-is-in-http.md new file mode 100644 index 0000000..7c447fa --- /dev/null +++ b/note/javascript/misc/redirect-the-page-to-https-if-it-is-in-http.md @@ -0,0 +1,27 @@ +--- +title: How to redirect the page to https if it is in http in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to redirect the page to https if it is in http only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const redirectHttps = () => (location.protocol === 'https:') ? {} : location.replace(`https://${location.href.split('//')[1]}`); +``` + +### Or + +```js {.wrap} +const redirectHttps = () => (location.protocol === 'https:') ? {} : (location.protocol = 'https:'); +``` \ No newline at end of file diff --git a/note/javascript/misc/run-promises-in-sequence.md b/note/javascript/misc/run-promises-in-sequence.md new file mode 100644 index 0000000..6d21b53 --- /dev/null +++ b/note/javascript/misc/run-promises-in-sequence.md @@ -0,0 +1,33 @@ +--- +title: How to run promises in sequence in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to run promises in sequence only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const run = promises => promises.reduce((p, c) => p.then(rp => c.then(rc => [...rp, rc])), Promise.resolve([])); +``` +Parameters `promises` is an array of `Promise`. + + + + +### Example + +```js {.wrap} +run(promises).then((results) => { + // `results` is an array of promise results in the same order +}); +``` \ No newline at end of file diff --git a/note/javascript/misc/swap-two-variables.md b/note/javascript/misc/swap-two-variables.md new file mode 100644 index 0000000..035d42c --- /dev/null +++ b/note/javascript/misc/swap-two-variables.md @@ -0,0 +1,42 @@ +--- +title: How to swap two variables in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to swap two variables only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +[a, b] = [b, a]; +``` + +### Or + +```js {.wrap} +a = [b, b = a][0]; +``` + +### Or + +```js {.wrap} +a = (x => x)(b, b = a); +``` + +### Or + +```js {.wrap} +// (only works with numbers) +a = b + (b = a, 0); + +a = b * (b = a, 1); +``` \ No newline at end of file diff --git a/note/javascript/misc/wait-for-an-amount-of-time.md b/note/javascript/misc/wait-for-an-amount-of-time.md new file mode 100644 index 0000000..964078d --- /dev/null +++ b/note/javascript/misc/wait-for-an-amount-of-time.md @@ -0,0 +1,21 @@ +--- +title: How to wait for an amount of time in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js +layout: note +--- + + + +In this Article we will go through how to wait for an amount of time only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); +``` \ No newline at end of file diff --git a/note/javascript/number/add-an-ordinal-suffix-to-a-number.md b/note/javascript/number/add-an-ordinal-suffix-to-a-number.md new file mode 100644 index 0000000..79b0c05 --- /dev/null +++ b/note/javascript/number/add-an-ordinal-suffix-to-a-number.md @@ -0,0 +1,55 @@ +--- +title: How to add an ordinal suffix to a number in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to add an ordinal suffix to a number only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const addOrdinal = n => `${n}${['st', 'nd', 'rd'][((n + 90) % 100 - 10) % 10 - 1] || 'th'}`; +``` +Parameters `n` is a position number. + + + + +### Or + +```js {.wrap} +const addOrdinal = n => `${n}${[, 'st', 'nd', 'rd'][/1?.$/.exec(n)] || 'th'}`; +``` + +### Or + +```js {.wrap} +const addOrdinal = n => `${n}${[, 'st', 'nd', 'rd'][n % 100 >> 3^1 && n % 10] || 'th'}`; +``` + +### Or + +```js {.wrap} +const addOrdinal = n => `${n}${{one: 'st', two: 'nd', few: 'rd', other: 'th'}[new Intl.PluralRules('en', { type: 'ordinal' }).select(n)]}`; +``` + +### Example + +```js {.wrap} +addOrdinal(1); // '1st' +addOrdinal(2); // '2nd' +addOrdinal(3); // '3rd' +addOrdinal(11); // '11th' +addOrdinal(12); // '13th' +addOrdinal(13); // '13th' +``` \ No newline at end of file diff --git a/note/javascript/number/calculate-fibonacci-numbers.md b/note/javascript/number/calculate-fibonacci-numbers.md new file mode 100644 index 0000000..b819095 --- /dev/null +++ b/note/javascript/number/calculate-fibonacci-numbers.md @@ -0,0 +1,33 @@ +--- +title: How to calculate fibonacci numbers in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to calculate fibonacci numbers only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const fibo = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo))); +``` + +### Example + +```js {.wrap} +fibo(1); // 1 +fibo(2); // 1 +fibo(3); // 2 +fibo(4); // 3 +fibo(5); // 5 +fibo(6); // 8 +``` \ No newline at end of file diff --git a/note/javascript/number/calculate-the-average-of-arguments.md b/note/javascript/number/calculate-the-average-of-arguments.md new file mode 100644 index 0000000..4f91701 --- /dev/null +++ b/note/javascript/number/calculate-the-average-of-arguments.md @@ -0,0 +1,28 @@ +--- +title: How to calculate the average of arguments in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to calculate the average of arguments only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const average = (...args) => args.reduce((a, b) => a + b) / args.length; +``` + +### Example + +```js {.wrap} +average(1, 2, 3, 4); // 2.5 +``` \ No newline at end of file diff --git a/note/javascript/number/calculate-the-division-of-arguments.md b/note/javascript/number/calculate-the-division-of-arguments.md new file mode 100644 index 0000000..be47d86 --- /dev/null +++ b/note/javascript/number/calculate-the-division-of-arguments.md @@ -0,0 +1,28 @@ +--- +title: How to calculate the division of arguments in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to calculate the division of arguments only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const division = (...args) => args.reduce((a, b) => a / b); +``` + +### Example + +```js {.wrap} +division(1, 2, 3, 4); // 0.04166666666666666 +``` \ No newline at end of file diff --git a/note/javascript/number/calculate-the-factorial-of-a-number.md b/note/javascript/number/calculate-the-factorial-of-a-number.md new file mode 100644 index 0000000..3d788a9 --- /dev/null +++ b/note/javascript/number/calculate-the-factorial-of-a-number.md @@ -0,0 +1,32 @@ +--- +title: How to calculate the factorial of a number in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to calculate the factorial of a number only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const factorial = n => n <= 1 ? 1 : n * factorial(n - 1); +``` + +### Example + +```js {.wrap} +factorial(2); // 2 +factorial(3); // 6 +factorial(4); // 24 +factorial(5); // 120 +factorial(6); // 720 +``` \ No newline at end of file diff --git a/note/javascript/number/calculate-the-mod-of-collection-index.md b/note/javascript/number/calculate-the-mod-of-collection-index.md new file mode 100644 index 0000000..3f194e6 --- /dev/null +++ b/note/javascript/number/calculate-the-mod-of-collection-index.md @@ -0,0 +1,30 @@ +--- +title: How to calculate the mod of collection index in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to calculate the mod of collection index only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const mod = (a, b) => ((a % b) + b) % b; +``` + +### Example + +```js {.wrap} +mod(-1, 5); // 4 +mod(3, 5); // 3 +mod(6, 5); // 1 +``` \ No newline at end of file diff --git a/note/javascript/number/calculate-the-remainder-of-division-of-arguments.md b/note/javascript/number/calculate-the-remainder-of-division-of-arguments.md new file mode 100644 index 0000000..e2a1f72 --- /dev/null +++ b/note/javascript/number/calculate-the-remainder-of-division-of-arguments.md @@ -0,0 +1,28 @@ +--- +title: How to calculate the remainder of division of arguments in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to calculate the remainder of division of arguments only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const remainder = (...args) => args.reduce((a, b) => a % b); +``` + +### Example + +```js {.wrap} +remainder(1, 2, 3, 4); // 1 +``` \ No newline at end of file diff --git a/note/javascript/number/calculate-the-sum-of-arguments.md b/note/javascript/number/calculate-the-sum-of-arguments.md new file mode 100644 index 0000000..621b9fa --- /dev/null +++ b/note/javascript/number/calculate-the-sum-of-arguments.md @@ -0,0 +1,28 @@ +--- +title: How to calculate the sum of arguments in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to calculate the sum of arguments only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const sum = (...args) => args.reduce((a, b) => a + b); +``` + +### Example + +```js {.wrap} +sum(1, 2, 3, 4); // 10 +``` \ No newline at end of file diff --git a/note/javascript/number/clamp-a-number-between-two-values.md b/note/javascript/number/clamp-a-number-between-two-values.md new file mode 100644 index 0000000..e1ef0e7 --- /dev/null +++ b/note/javascript/number/clamp-a-number-between-two-values.md @@ -0,0 +1,28 @@ +--- +title: How to clamp a number between two values in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to clamp a number between two values only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const clamp = (val, min = 0, max = 1) => Math.max(min, Math.min(max, val)); +``` + +### Example + +```js {.wrap} +clamp(199, 10, 25); // 25 +``` \ No newline at end of file diff --git a/note/javascript/number/compute-the-greatest-common-divisor-between-two-numbers.md b/note/javascript/number/compute-the-greatest-common-divisor-between-two-numbers.md new file mode 100644 index 0000000..61e7d59 --- /dev/null +++ b/note/javascript/number/compute-the-greatest-common-divisor-between-two-numbers.md @@ -0,0 +1,28 @@ +--- +title: How to compute the greatest common divisor between two numbers in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to compute the greatest common divisor between two numbers only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const gcd = (a, b) => b === 0 ? a : gcd(b, a % b); +``` + +### Example + +```js {.wrap} +gcd(10, 15); // 5 +``` \ No newline at end of file diff --git a/note/javascript/number/convert-a-number-to-equivalent-characters.md b/note/javascript/number/convert-a-number-to-equivalent-characters.md new file mode 100644 index 0000000..7059ef7 --- /dev/null +++ b/note/javascript/number/convert-a-number-to-equivalent-characters.md @@ -0,0 +1,38 @@ +--- +title: How to convert a number to equivalent characters in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to convert a number to equivalent characters only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toChars = n => `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`; +``` + +### Example + +```js {.wrap} +toChars(0); // A +toChars(1); // B +toChars(25); // Z + +toChars(26); // AA +toChars(27); // AB +toChars(51); // AZ + +toChars(701); // ZZ +toChars(702); // AAA +toChars(703); // AAB +``` \ No newline at end of file diff --git a/note/javascript/number/convert-a-string-to-number.md b/note/javascript/number/convert-a-string-to-number.md new file mode 100644 index 0000000..8209ef1 --- /dev/null +++ b/note/javascript/number/convert-a-string-to-number.md @@ -0,0 +1,28 @@ +--- +title: How to convert a string to number in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to convert a string to number only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toNumber = str => +str; +``` + +### Example + +```js {.wrap} +toNumber('42'); // 42 +``` \ No newline at end of file diff --git a/note/javascript/number/convert-decimal-to-binary-recursively.md b/note/javascript/number/convert-decimal-to-binary-recursively.md new file mode 100644 index 0000000..1ab466c --- /dev/null +++ b/note/javascript/number/convert-decimal-to-binary-recursively.md @@ -0,0 +1,28 @@ +--- +title: How to convert decimal to binary recursively in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to convert decimal to binary recursively only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const decToBi = num => num === 0 ? 0 : num % 2 + 10 * decToBi(~~(num / 2)); +``` + +### Example + +```js {.wrap} +decToBi(10); //1010 +``` diff --git a/note/javascript/number/get-the-arrays-of-digits-from-a-number.md b/note/javascript/number/get-the-arrays-of-digits-from-a-number.md new file mode 100644 index 0000000..695730d --- /dev/null +++ b/note/javascript/number/get-the-arrays-of-digits-from-a-number.md @@ -0,0 +1,34 @@ +--- +title: How to get the arrays of digits from a number in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to get the arrays of digits from a number only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const digitize = n => `${n}`.split('').map(v => parseInt(v, 10)); +``` + +### Or + +```js {.wrap} +const digitize = n => [...`${n}`].map(v => parseInt(v, 10)); +``` + +### Example + +```js {.wrap} +digitize(123); // [1, 2, 3] +``` \ No newline at end of file diff --git a/note/javascript/number/multiply-arguments.md b/note/javascript/number/multiply-arguments.md new file mode 100644 index 0000000..6e27a69 --- /dev/null +++ b/note/javascript/number/multiply-arguments.md @@ -0,0 +1,28 @@ +--- +title: How to multiply arguments in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to multiply arguments only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const mul = (...args) => args.reduce((a, b) => a * b); +``` + +### Example + +```js {.wrap} +mul(1, 2, 3, 4); // 24 +``` \ No newline at end of file diff --git a/note/javascript/number/prefix-an-integer-with-zeros.md b/note/javascript/number/prefix-an-integer-with-zeros.md new file mode 100644 index 0000000..0025dbe --- /dev/null +++ b/note/javascript/number/prefix-an-integer-with-zeros.md @@ -0,0 +1,40 @@ +--- +title: How to prefix an integer with zeros in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to prefix an integer with zeros only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const prefixWithZeros = (number, length) => (number / Math.pow(10, length)).toFixed(length).substr(2); +``` + +### Or + +```js {.wrap} +const prefixWithZeros = (number, length) => `${Array(length).join('0')}${number}`.slice(-length); +``` + +### Or + +```js {.wrap} +const prefixWithZeros = (number, length) => String(number).padStart(length, '0'); +``` + +### Example + +```js {.wrap} +prefixWithZeros(42, 5); // '00042' +``` \ No newline at end of file diff --git a/note/javascript/number/round-a-number-to-a-given-number-of-digits.md b/note/javascript/number/round-a-number-to-a-given-number-of-digits.md new file mode 100644 index 0000000..86e3849 --- /dev/null +++ b/note/javascript/number/round-a-number-to-a-given-number-of-digits.md @@ -0,0 +1,29 @@ +--- +title: How to round a number to a given number of digits in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to round a number to a given number of digits only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); +``` + +### Example + +```js {.wrap} +round(1.234567, 3); // 1.235 +round(1.234567, 4); // 1.2346 +``` \ No newline at end of file diff --git a/note/javascript/number/subtract-arguments.md b/note/javascript/number/subtract-arguments.md new file mode 100644 index 0000000..7065e23 --- /dev/null +++ b/note/javascript/number/subtract-arguments.md @@ -0,0 +1,28 @@ +--- +title: How to subtract arguments in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to subtract arguments only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const subtract = (...args) => args.reduce((a, b) => a - b); +``` + +### Example + +```js {.wrap} +subtract(1, 2, 3, 4); // -8 +``` \ No newline at end of file diff --git a/note/javascript/number/truncate-a-number-at-decimal.md b/note/javascript/number/truncate-a-number-at-decimal.md new file mode 100644 index 0000000..7b8c6aa --- /dev/null +++ b/note/javascript/number/truncate-a-number-at-decimal.md @@ -0,0 +1,29 @@ +--- +title: How to truncate a number at decimal in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to truncate a number at decimal only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const truncate = n => ~~n; +``` + +### Example + +```js {.wrap} +truncate(25.198726354); // 25 +truncate(-25.198726354); // -25 +``` \ No newline at end of file diff --git a/note/javascript/number/truncate-a-number-to-a-given-number-of-decimal-places-without-rounding.md b/note/javascript/number/truncate-a-number-to-a-given-number-of-decimal-places-without-rounding.md new file mode 100644 index 0000000..8fc5236 --- /dev/null +++ b/note/javascript/number/truncate-a-number-to-a-given-number-of-decimal-places-without-rounding.md @@ -0,0 +1,39 @@ +--- +title: How to truncate a number to a given number of decimal places without rounding in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Number +layout: note +--- + + + +In this Article we will go through how to truncate a number to a given number of decimal places without rounding only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\\d+(?:\.\\d{0,${fixed}})?`))[0]; +``` + +### Or + +```js {.wrap} +const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed); +``` + +### Example + +```js {.wrap} +toFixed(25.198726354, 1); // 25.1 +toFixed(25.198726354, 2); // 25.19 +toFixed(25.198726354, 3); // 25.198 +toFixed(25.198726354, 4); // 25.1987 +toFixed(25.198726354, 5); // 25.19872 +toFixed(25.198726354, 6); // 25.198726 +``` \ No newline at end of file diff --git a/note/javascript/object/check-if-multiple-objects-are-equal.md b/note/javascript/object/check-if-multiple-objects-are-equal.md new file mode 100644 index 0000000..f2f8e8b --- /dev/null +++ b/note/javascript/object/check-if-multiple-objects-are-equal.md @@ -0,0 +1,29 @@ +--- +title: How to check if multiple objects are equal in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to check if multiple objects are equal only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0])); +``` + +### Example + +```js {.wrap} +isEqual({ foo: 'bar' }, { foo: 'bar' }); // true +isEqual({ foo: 'bar' }, { bar: 'foo' }); // false +``` \ No newline at end of file diff --git a/note/javascript/object/create-an-empty-map-that-does-not-have-properties.md b/note/javascript/object/create-an-empty-map-that-does-not-have-properties.md new file mode 100644 index 0000000..6db6102 --- /dev/null +++ b/note/javascript/object/create-an-empty-map-that-does-not-have-properties.md @@ -0,0 +1,26 @@ +--- +title: How to create an empty map that does not have properties in JavaScript +tags: + - JavaScript + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to create an empty map that does not have properties only using single line of code in JavaScript. +
+
+Let's define this short function: + +The following `map` has `__proto__` property +```js {.wrap} +const map = Object.create(null); +``` + +The following `map` doesn't have any properties +```js {.wrap} +const map = {}; +``` \ No newline at end of file diff --git a/note/javascript/object/create-an-object-from-the-pairs-of-key-and-value.md b/note/javascript/object/create-an-object-from-the-pairs-of-key-and-value.md new file mode 100644 index 0000000..8d9a64f --- /dev/null +++ b/note/javascript/object/create-an-object-from-the-pairs-of-key-and-value.md @@ -0,0 +1,34 @@ +--- +title: How to create an object from the pairs of key and value in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to create an object from the pairs of key and value only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toObj = arr => Object.fromEntries(arr) +``` + +### Or + +```js {.wrap} +const toObj = arr => arr.reduce((a, c) => ((a[c[0]] = c[1]), a), {}); +``` + +### Example + +```js {.wrap} +toObj([['a', 1], ['b', 2], ['c', 3]]); // { a: 1, b: 2, c: 3 } +``` \ No newline at end of file diff --git a/note/javascript/object/extract-values-of-a-property-from-an-array-of-objects.md b/note/javascript/object/extract-values-of-a-property-from-an-array-of-objects.md new file mode 100644 index 0000000..f8ad8c8 --- /dev/null +++ b/note/javascript/object/extract-values-of-a-property-from-an-array-of-objects.md @@ -0,0 +1,32 @@ +--- +title: How to extract values of a property from an array of objects in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to extract values of a property from an array of objects only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const pluck = (objs, property) => objs.map(obj => obj[property]); +``` + +### Example + +```js {.wrap} +pluck([ + { name: 'John', age: 20 }, + { name: 'Smith', age: 25 }, + { name: 'Peter', age: 30 }, +], 'name'); // ['John', 'Smith', 'Peter'] +``` \ No newline at end of file diff --git a/note/javascript/object/get-the-value-at-given-path-of-an-object.md b/note/javascript/object/get-the-value-at-given-path-of-an-object.md new file mode 100644 index 0000000..c84d36d --- /dev/null +++ b/note/javascript/object/get-the-value-at-given-path-of-an-object.md @@ -0,0 +1,28 @@ +--- +title: How to get the value at given path of an object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to get the value at given path of an object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getValue = (path, obj) => path.split('.').reduce((acc, c) => acc && acc[c], obj); +``` + +### Example + +```js {.wrap} +getValue('a.b', { a: { b: 'Hello World' } }); // 'Hello World'; +``` \ No newline at end of file diff --git a/note/javascript/object/immutably-rename-object-keys.md b/note/javascript/object/immutably-rename-object-keys.md new file mode 100644 index 0000000..7061396 --- /dev/null +++ b/note/javascript/object/immutably-rename-object-keys.md @@ -0,0 +1,30 @@ +--- +title: How to immutably rename object keys in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to immutably rename object keys only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const renameKeys = (keysMap, obj) => Object.keys(obj).reduce((acc, key) => ({ ...acc, ...{ [keysMap[key] || key]: obj[key] }}), {}); +``` + +### Example + +```js {.wrap} +const obj = { a: 1, b: 2, c: 3 }; +const keysMap = { a: 'd', b: 'e', c: 'f' }; +renameKeys(keysMap, obj); // { d: 1, e: 2, f: 3 } +``` \ No newline at end of file diff --git a/note/javascript/object/invert-keys-and-values-of-an-object.md b/note/javascript/object/invert-keys-and-values-of-an-object.md new file mode 100644 index 0000000..100e295 --- /dev/null +++ b/note/javascript/object/invert-keys-and-values-of-an-object.md @@ -0,0 +1,34 @@ +--- +title: How to invert keys and values of an object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to invert keys and values of an object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const invert = obj => Object.keys(obj).reduce((res, k) => Object.assign(res, {[obj[k]]: k}), {}); +``` + +### Or + +```js {.wrap} +const invert = obj => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k])); +``` + +### Example + +```js {.wrap} +invert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' } +``` \ No newline at end of file diff --git a/note/javascript/object/omit-a-subset-of-properties-from-an-object.md b/note/javascript/object/omit-a-subset-of-properties-from-an-object.md new file mode 100644 index 0000000..4ee3d4a --- /dev/null +++ b/note/javascript/object/omit-a-subset-of-properties-from-an-object.md @@ -0,0 +1,28 @@ +--- +title: How to omit a subset of properties from an object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to omit a subset of properties from an object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const omit = (obj, keys) => Object.keys(obj).filter(k => !keys.includes(k)).reduce((res, k) => Object.assign(res, {[k]: obj[k]}), {}); +``` + +### Example + +```js {.wrap} +omit({a: '1', b: '2', c: '3'}, ['a', 'b']); // { c: '3' } +``` \ No newline at end of file diff --git a/note/javascript/object/pick-a-subset-of-properties-of-an-object.md b/note/javascript/object/pick-a-subset-of-properties-of-an-object.md new file mode 100644 index 0000000..7bc941c --- /dev/null +++ b/note/javascript/object/pick-a-subset-of-properties-of-an-object.md @@ -0,0 +1,28 @@ +--- +title: How to pick a subset of properties of an object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to pick a subset of properties of an object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const pick = (obj, keys) => Object.keys(obj).filter(k => keys.includes(k)).reduce((res, k) => Object.assign(res, {[k]: obj[k]}), {}); +``` + +### Example + +```js {.wrap} +pick({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { a: '1', b: '2' } +``` \ No newline at end of file diff --git a/note/javascript/object/remove-all-null-and-undefined-properties-from-an-object.md b/note/javascript/object/remove-all-null-and-undefined-properties-from-an-object.md new file mode 100644 index 0000000..ae1e448 --- /dev/null +++ b/note/javascript/object/remove-all-null-and-undefined-properties-from-an-object.md @@ -0,0 +1,44 @@ +--- +title: How to remove all null and undefined properties from an object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to remove all null and undefined properties from an object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const removeNullUndefined = obj => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : (a[k] = v, a)), {}); +``` + +### Or + +```js {.wrap} +const removeNullUndefined = obj => Object.entries(obj).filter(([_, v]) => v != null).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}); +``` + +### Or + +```js {.wrap} +const removeNullUndefined = obj => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)); +``` + +### Example + +```js {.wrap} +removeNullUndefined({ + foo: null, + bar: undefined, + fuzz: 42, +}); // { fuzz: 42 } +``` \ No newline at end of file diff --git a/note/javascript/object/shallow-copy-an-object.md b/note/javascript/object/shallow-copy-an-object.md new file mode 100644 index 0000000..21b545d --- /dev/null +++ b/note/javascript/object/shallow-copy-an-object.md @@ -0,0 +1,28 @@ +--- +title: How to shallow copy an object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to shallow copy an object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const shallowCopy = obj => Object.assign({}, obj); +``` + +### or + +```js {.wrap} +const shallowCopy = obj => {...obj}; +``` \ No newline at end of file diff --git a/note/javascript/object/sort-an-object-by-its-properties.md b/note/javascript/object/sort-an-object-by-its-properties.md new file mode 100644 index 0000000..f740020 --- /dev/null +++ b/note/javascript/object/sort-an-object-by-its-properties.md @@ -0,0 +1,44 @@ +--- +title: How to sort an object by its properties in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Object +layout: note +--- + + + +In this Article we will go through how to sort an object by its properties only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const sort = obj => Object.keys(obj).sort().reduce((p, c) => (p[c] = obj[c], p), {}); +``` + +### Example + +```js {.wrap} +const colors = { + white: '#ffffff', + black: '#000000', + red: '#ff0000', + green: '#008000', + blue: '#0000ff', +}; +sort(colors); +/* +{ + black: '#000000', + blue: '#0000ff', + green: '#008000', + red: '#ff0000', + white: '#ffffff', +} +*/ +``` \ No newline at end of file diff --git a/note/javascript/random/generate-a-random-boolean.md b/note/javascript/random/generate-a-random-boolean.md new file mode 100644 index 0000000..08604af --- /dev/null +++ b/note/javascript/random/generate-a-random-boolean.md @@ -0,0 +1,22 @@ +--- +title: How to generate a random boolean in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random boolean only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomBoolean = () => Math.random() >= 0.5; +``` \ No newline at end of file diff --git a/note/javascript/random/generate-a-random-floating-point-number-in-given-range.md b/note/javascript/random/generate-a-random-floating-point-number-in-given-range.md new file mode 100644 index 0000000..ee445d2 --- /dev/null +++ b/note/javascript/random/generate-a-random-floating-point-number-in-given-range.md @@ -0,0 +1,22 @@ +--- +title: How to generate a random floating point number in given range in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random floating point number in given range only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomFloat = (min, max) => Math.random() * (max - min) + min; +``` \ No newline at end of file diff --git a/note/javascript/random/generate-a-random-hex-color.md b/note/javascript/random/generate-a-random-hex-color.md new file mode 100644 index 0000000..74ca744 --- /dev/null +++ b/note/javascript/random/generate-a-random-hex-color.md @@ -0,0 +1,28 @@ +--- +title: How to generate a random hex color in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random hex color only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`; +``` + +### Or + +```js {.wrap} +const randomColor = () => `#${(~~(Math.random()*(1<<24))).toString(16)}`; +``` \ No newline at end of file diff --git a/note/javascript/random/generate-a-random-integer-in-given-range.md b/note/javascript/random/generate-a-random-integer-in-given-range.md new file mode 100644 index 0000000..ec226f7 --- /dev/null +++ b/note/javascript/random/generate-a-random-integer-in-given-range.md @@ -0,0 +1,22 @@ +--- +title: How to generate a random integer in given range in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random integer in given range only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; +``` \ No newline at end of file diff --git a/note/javascript/random/generate-a-random-ip-address.md b/note/javascript/random/generate-a-random-ip-address.md new file mode 100644 index 0000000..c982ad8 --- /dev/null +++ b/note/javascript/random/generate-a-random-ip-address.md @@ -0,0 +1,28 @@ +--- +title: How to generate a random ip address in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random ip address only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomIp = () => Array(4).fill(0).map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)).join('.'); +``` + +### Example + +```js {.wrap} +randomIp(); // 175.89.174.131 +``` \ No newline at end of file diff --git a/note/javascript/random/generate-a-random-sign.md b/note/javascript/random/generate-a-random-sign.md new file mode 100644 index 0000000..f5dd8ab --- /dev/null +++ b/note/javascript/random/generate-a-random-sign.md @@ -0,0 +1,22 @@ +--- +title: How to generate a random sign in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random sign only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomSign = () => Math.random() >= 0.5 ? 1 : -1; +``` \ No newline at end of file diff --git a/note/javascript/random/generate-a-random-string-from-given-characters.md b/note/javascript/random/generate-a-random-string-from-given-characters.md new file mode 100644 index 0000000..20256a3 --- /dev/null +++ b/note/javascript/random/generate-a-random-string-from-given-characters.md @@ -0,0 +1,28 @@ +--- +title: How to generate a random string from given characters in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random string from given characters only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const generateString = (length, chars) => Array(length).fill('').map((v) => chars[Math.floor(Math.random() * chars.length)]).join(''); +``` + +### Example + +```js {.wrap} +generateString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); +``` \ No newline at end of file diff --git a/note/javascript/random/generate-a-random-string-using-node-crypto-module.md b/note/javascript/random/generate-a-random-string-using-node-crypto-module.md new file mode 100644 index 0000000..fae951d --- /dev/null +++ b/note/javascript/random/generate-a-random-string-using-node-crypto-module.md @@ -0,0 +1,22 @@ +--- +title: How to generate a random string using node crypto module in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random string using node crypto module only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomStr = () => require('crypto').randomBytes(32).toString('hex'); +``` diff --git a/note/javascript/random/generate-a-random-string-with-given-length.md b/note/javascript/random/generate-a-random-string-with-given-length.md new file mode 100644 index 0000000..e04485e --- /dev/null +++ b/note/javascript/random/generate-a-random-string-with-given-length.md @@ -0,0 +1,22 @@ +--- +title: How to generate a random string with given length in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random string with given length only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const generateString = length => Array(length).fill('').map((v) => Math.random().toString(36).charAt(2)).join(''); +``` \ No newline at end of file diff --git a/note/javascript/random/generate-a-random-uuid.md b/note/javascript/random/generate-a-random-uuid.md new file mode 100644 index 0000000..088156b --- /dev/null +++ b/note/javascript/random/generate-a-random-uuid.md @@ -0,0 +1,22 @@ +--- +title: How to generate a random uuid in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate a random uuid only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const uuid = (a) => a ? (a ^ Math.random() * 16 >> a / 4).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid); +``` \ No newline at end of file diff --git a/note/javascript/random/generate-an-array-of-random-integers-in-a-given-range.md b/note/javascript/random/generate-an-array-of-random-integers-in-a-given-range.md new file mode 100644 index 0000000..86227e0 --- /dev/null +++ b/note/javascript/random/generate-an-array-of-random-integers-in-a-given-range.md @@ -0,0 +1,28 @@ +--- +title: How to generate an array of random integers in a given range in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to generate an array of random integers in a given range only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomArrayInRange = (min, max, n) => Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); +``` + +### Example + +```js {.wrap} +randomArrayInRange(1, 100, 10); // [11, 82, 41, 35, 76, 83, 43, 15, 60, 54] +``` \ No newline at end of file diff --git a/note/javascript/random/get-a-random-item-and-remove-it-from-an-array.md b/note/javascript/random/get-a-random-item-and-remove-it-from-an-array.md new file mode 100644 index 0000000..3296c3c --- /dev/null +++ b/note/javascript/random/get-a-random-item-and-remove-it-from-an-array.md @@ -0,0 +1,30 @@ +--- +title: How to get a random item and remove it from an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to get a random item and remove it from an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomItem = arr => arr.splice((Math.random() * arr.length) | 0, 1); +``` + +### Example + +```js {.wrap} +const arr = [1, 3, 5, 7, 9]; +randomItem(arr); // 7 + // arr = [1, 3, 5, 9] +``` \ No newline at end of file diff --git a/note/javascript/random/get-a-random-item-from-an-array.md b/note/javascript/random/get-a-random-item-from-an-array.md new file mode 100644 index 0000000..7da2a5a --- /dev/null +++ b/note/javascript/random/get-a-random-item-from-an-array.md @@ -0,0 +1,22 @@ +--- +title: How to get a random item from an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to get a random item from an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomItem = arr => arr[(Math.random() * arr.length) | 0]; +``` diff --git a/note/javascript/random/get-random-items-of-an-array.md b/note/javascript/random/get-random-items-of-an-array.md new file mode 100644 index 0000000..717393a --- /dev/null +++ b/note/javascript/random/get-random-items-of-an-array.md @@ -0,0 +1,29 @@ +--- +title: How to get random items of an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to get random items of an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomItems = (arr, count) => arr.concat().reduce((p, _, __, arr) => (p[0] < count) ? [p[0] + 1, p[1].concat(arr.splice(Math.random() * arr.length | 0, 1))] : p, [0, []])[1]; +``` + +### Example + +```js {.wrap} +randomItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // [4, 8, 5] +randomItems(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 4); // ['e', 'c', 'h', 'j'] +``` \ No newline at end of file diff --git a/note/javascript/random/pick-a-random-property-of-an-object.md b/note/javascript/random/pick-a-random-property-of-an-object.md new file mode 100644 index 0000000..b7a41ae --- /dev/null +++ b/note/javascript/random/pick-a-random-property-of-an-object.md @@ -0,0 +1,73 @@ +--- +title: How to pick a random property of an object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to pick a random property of an object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomProp = obj => Object.keys(obj)[(Math.random() * Object.keys(obj).length) | 0]; +``` + +### Example + +```js {.wrap} +const colors = { + aqua: '#00ffff', + azure: '#f0ffff', + beige: '#f5f5dc', + black: '#000000', + blue: '#0000ff', + brown: '#a52a2a', + cyan: '#00ffff', + darkblue: '#00008b', + darkcyan: '#008b8b', + darkgrey: '#a9a9a9', + darkgreen: '#006400', + darkkhaki: '#bdb76b', + darkmagenta: '#8b008b', + darkolivegreen: '#556b2f', + darkorange: '#ff8c00', + darkorchid: '#9932cc', + darkred: '#8b0000', + darksalmon: '#e9967a', + darkviolet: '#9400d3', + fuchsia: '#ff00ff', + gold: '#ffd700', + green: '#008000', + indigo: '#4b0082', + khaki: '#f0e68c', + lightblue: '#add8e6', + lightcyan: '#e0ffff', + lightgreen: '#90ee90', + lightgrey: '#d3d3d3', + lightpink: '#ffb6c1', + lightyellow: '#ffffe0', + lime: '#00ff00', + magenta: '#ff00ff', + maroon: '#800000', + navy: '#000080', + olive: '#808000', + orange: '#ffa500', + pink: '#ffc0cb', + purple: '#800080', + violet: '#800080', + red: '#ff0000', + silver: '#c0c0c0', + white: '#ffffff', + yellow: '#ffff00', +}; +randomProp(colors); // 'red' +``` \ No newline at end of file diff --git a/note/javascript/random/pick-random-lines-from-a-text-document.md b/note/javascript/random/pick-random-lines-from-a-text-document.md new file mode 100644 index 0000000..db45f89 --- /dev/null +++ b/note/javascript/random/pick-random-lines-from-a-text-document.md @@ -0,0 +1,34 @@ +--- +title: How to pick random lines from a text document in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Random +layout: note +--- + + + +In this Article we will go through how to pick random lines from a text document only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const randomLines = (str, count) => str.split(/\r?\n/).reduce((p, _, __, arr) => (p[0] < count) ? [p[0] + 1, p[1].concat(arr.splice(Math.random() * arr.length | 0, 1))] : p, [0, []])[1]; +``` + +### Example + +```js {.wrap} +randomLines(`one +two +three +four +five`, 2); + +// ['one', 'four'] +``` \ No newline at end of file diff --git a/note/javascript/string/capitalize-a-string.md b/note/javascript/string/capitalize-a-string.md new file mode 100644 index 0000000..ee91470 --- /dev/null +++ b/note/javascript/string/capitalize-a-string.md @@ -0,0 +1,34 @@ +--- +title: How to capitalize a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to capitalize a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const capitalize = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; +``` + +### Or + +```js {.wrap} +const capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`; +``` + +### Example + +```js {.wrap} +capitalize('hello world'); // 'Hello world' +``` \ No newline at end of file diff --git a/note/javascript/string/check-if-a-path-is-relative.md b/note/javascript/string/check-if-a-path-is-relative.md new file mode 100644 index 0000000..39b80cf --- /dev/null +++ b/note/javascript/string/check-if-a-path-is-relative.md @@ -0,0 +1,31 @@ +--- +title: How to check if a path is relative in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to check if a path is relative only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isRelative = path => !/^([a-z]+:)?[\\/]/i.test(path); +``` + +### Example + +```js {.wrap} +isRelative('/foo/bar/baz'); // false +isRelative('C:\\foo\\bar\\baz'); // false +isRelative('foo/bar/baz.txt'); // true +isRelative('foo.md'); // true +``` \ No newline at end of file diff --git a/note/javascript/string/check-if-a-string-consists-of-a-repeated-character-sequence.md b/note/javascript/string/check-if-a-string-consists-of-a-repeated-character-sequence.md new file mode 100644 index 0000000..53c32a3 --- /dev/null +++ b/note/javascript/string/check-if-a-string-consists-of-a-repeated-character-sequence.md @@ -0,0 +1,31 @@ +--- +title: How to check if a string consists of a repeated character sequence in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to check if a string consists of a repeated character sequence only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const consistsRepeatedSubstring = str => `${str}${str}`.indexOf(str, 1) !== str.length; +``` + +### Example + +```js {.wrap} +consistsRepeatedSubstring('aa'); // true +consistsRepeatedSubstring('aaa'); // true +consistsRepeatedSubstring('ababab'); // true +consistsRepeatedSubstring('abc'); // false +``` \ No newline at end of file diff --git a/note/javascript/string/check-if-a-string-is-a-palindrome.md b/note/javascript/string/check-if-a-string-is-a-palindrome.md new file mode 100644 index 0000000..656bbff --- /dev/null +++ b/note/javascript/string/check-if-a-string-is-a-palindrome.md @@ -0,0 +1,29 @@ +--- +title: How to check if a string is a palindrome in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to check if a string is a palindrome only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isPalindrome = str => str === str.split('').reverse().join(''); +``` + +### Example + +```js {.wrap} +isPalindrome('abc'); // false +isPalindrom('abcba'); // true +``` \ No newline at end of file diff --git a/note/javascript/string/check-if-a-url-is-absolute.md b/note/javascript/string/check-if-a-url-is-absolute.md new file mode 100644 index 0000000..3fa8001 --- /dev/null +++ b/note/javascript/string/check-if-a-url-is-absolute.md @@ -0,0 +1,31 @@ +--- +title: How to check if a url is absolute in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to check if a url is absolute only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isAbsoluteUrl = url => /^[a-z][a-z0-9+.-]*:/.test(url); +``` + +### Example + +```js {.wrap} +isAbsoluteUrl('https://1loc.dev'); // true +isAbsoluteUrl('https://1loc.dev/foo/bar'); // true +isAbsoluteUrl('1loc.dev'); // false +isAbsoluteUrl('//1loc.dev'); // false +``` \ No newline at end of file diff --git a/note/javascript/string/check-if-two-strings-are-anagram.md b/note/javascript/string/check-if-two-strings-are-anagram.md new file mode 100644 index 0000000..f646f3e --- /dev/null +++ b/note/javascript/string/check-if-two-strings-are-anagram.md @@ -0,0 +1,30 @@ +--- +title: How to check if two strings are anagram in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to check if two strings are anagram only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const areAnagram = (str1, str2) => str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join(''); +``` + +### Example + +```js {.wrap} +areAnagram('listen', 'silent'); // true +areAnagram('they see', 'the eyes'); // true +areAnagram('node', 'deno'); // true +``` \ No newline at end of file diff --git a/note/javascript/string/convert-a-letter-to-associate-emoji.md b/note/javascript/string/convert-a-letter-to-associate-emoji.md new file mode 100644 index 0000000..a2d9dbe --- /dev/null +++ b/note/javascript/string/convert-a-letter-to-associate-emoji.md @@ -0,0 +1,29 @@ +--- +title: How to convert a letter to associate emoji in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to convert a letter to associate emoji only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const letterToEmoji = c => String.fromCodePoint(c.toLowerCase().charCodeAt() + 127365); +``` + +### Example + +```js {.wrap} +letterToEmoji('a'); // 🇦 +letterToEmoji('b'); // 🇧 +``` \ No newline at end of file diff --git a/note/javascript/string/convert-a-string-to-camel-case.md b/note/javascript/string/convert-a-string-to-camel-case.md new file mode 100644 index 0000000..46bee63 --- /dev/null +++ b/note/javascript/string/convert-a-string-to-camel-case.md @@ -0,0 +1,31 @@ +--- +title: How to convert a string to camelcase in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to convert a string to camelcase only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toCamelCase = str => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : ''); +``` + +### Example + +```js {.wrap} +toCamelCase('background-color'); // backgroundColor +toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb +toCamelCase('_hello_world'); // HelloWorld +toCamelCase('hello_world'); // helloWorld +``` \ No newline at end of file diff --git a/note/javascript/string/convert-a-string-to-pascal-case.md b/note/javascript/string/convert-a-string-to-pascal-case.md new file mode 100644 index 0000000..c40749a --- /dev/null +++ b/note/javascript/string/convert-a-string-to-pascal-case.md @@ -0,0 +1,30 @@ +--- +title: How to convert a string to pascalcase in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to convert a string to pascalcase only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toPascalCase = str => (str.match(/[a-zA-Z0-9]+/g) || []).map(w => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join(''); +``` + +### Example + +```js {.wrap} +toPascalCase('hello world'); // 'HelloWorld' +toPascalCase('hello.world'); // 'HelloWorld' +toPascalCase('foo_bar-baz'); // FooBarBaz +``` \ No newline at end of file diff --git a/note/javascript/string/convert-a-string-to-url-slug.md b/note/javascript/string/convert-a-string-to-url-slug.md new file mode 100644 index 0000000..a7c6ebc --- /dev/null +++ b/note/javascript/string/convert-a-string-to-url-slug.md @@ -0,0 +1,28 @@ +--- +title: How to convert a string to url slug in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to convert a string to url slug only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const slugify = string => string.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, ''); +``` + +### Example + +```js {.wrap} +slugify('Chapter One: Once upon a time...'); // 'chapter-one-once-upon-a-time' +``` \ No newline at end of file diff --git a/note/javascript/string/convert-a-windows-file-path-to-unix-path.md b/note/javascript/string/convert-a-windows-file-path-to-unix-path.md new file mode 100644 index 0000000..81bc100 --- /dev/null +++ b/note/javascript/string/convert-a-windows-file-path-to-unix-path.md @@ -0,0 +1,29 @@ +--- +title: How to convert a windows file path to unix path in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to convert a windows file path to unix path only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const toUnixPath = path => path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, ''); +``` + +### Example + +```js {.wrap} +toUnixPath('./foo/bar/baz'); // foo/bar/baz +toUnixPath('C:\\foo\\bar\\baz'); // /foo/bar/baz +``` \ No newline at end of file diff --git a/note/javascript/string/convert-camel-case-to-kebab-case-and-vice-versa.md b/note/javascript/string/convert-camel-case-to-kebab-case-and-vice-versa.md new file mode 100644 index 0000000..35f992e --- /dev/null +++ b/note/javascript/string/convert-camel-case-to-kebab-case-and-vice-versa.md @@ -0,0 +1,31 @@ +--- +title: How to convert camelcase to kebab-case and vice versa in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to convert camelcase to kebab-case and vice versa only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const kebabToCamel = str => str.replace(/-./g, m => m.toUpperCase()[1]); + +const camelToKebab = str => str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase(); +``` + +### Example + +```js {.wrap} +kebabToCamel('background-color'); // 'backgroundColor' +camelToKebab('backgroundColor'); // 'background-color' +``` \ No newline at end of file diff --git a/note/javascript/string/convert-snake-case-to-camel-case.md b/note/javascript/string/convert-snake-case-to-camel-case.md new file mode 100644 index 0000000..9244db5 --- /dev/null +++ b/note/javascript/string/convert-snake-case-to-camel-case.md @@ -0,0 +1,28 @@ +--- +title: How to convert snake_case to camelcase in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to convert snake_case to camelcase only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const snakeToCamel = str => str.toLowerCase().replace(/(_\w)/g, m => m.toUpperCase().substr(1)); +``` + +### Example + +```js {.wrap} +snakeToCamel('HELLO_world'); // 'helloWorld' +``` \ No newline at end of file diff --git a/note/javascript/string/convert-the-name-of-an-excel-column-to-number.md b/note/javascript/string/convert-the-name-of-an-excel-column-to-number.md new file mode 100644 index 0000000..bb03031 --- /dev/null +++ b/note/javascript/string/convert-the-name-of-an-excel-column-to-number.md @@ -0,0 +1,39 @@ +--- +title: How to convert the name of an excel column to number in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to convert the name of an excel column to number only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const getIndex = col => col.split('').reduce((prev, next) => prev * 26 + parseInt(next, 36) - 9, 0); +``` + +### Example + +```js {.wrap} +getIndex('A'); // 1 +getIndex('B'); // 2 +getIndex('C'); // 3 +getIndex('Z'); // 26 + +getIndex('AA'); // 27 +getIndex('AB'); // 28 +getIndex('AC'); // 29 +getIndex('AZ'); // 52 + +getIndex('AAA'); // 703 +getIndex('AAB'); // 704 +``` \ No newline at end of file diff --git a/note/javascript/string/count-the-number-of-words-in-a-string.md b/note/javascript/string/count-the-number-of-words-in-a-string.md new file mode 100644 index 0000000..6628fdf --- /dev/null +++ b/note/javascript/string/count-the-number-of-words-in-a-string.md @@ -0,0 +1,30 @@ +--- +title: How to count the number of words in a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to count the number of words in a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const countWords = str => str.trim().split(/\s+/).length; +``` + +### Example + +```js {.wrap} +countWords('Hello World'); // 2 +countWords('Hello World'); // 2 +countWords(' Hello World '); // 2 +``` \ No newline at end of file diff --git a/note/javascript/string/count-the-occurrences-of-a-character-in-a-string.md b/note/javascript/string/count-the-occurrences-of-a-character-in-a-string.md new file mode 100644 index 0000000..0a70c72 --- /dev/null +++ b/note/javascript/string/count-the-occurrences-of-a-character-in-a-string.md @@ -0,0 +1,46 @@ +--- +title: How to count the occurrences of a character in a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to count the occurrences of a character in a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const countOccurrences = (str, char) => [...str].reduce((a, v) => (v === char ? a + 1 : a), 0); +``` + +### Or + +```js {.wrap} +const countOccurrences = (str, char) => str.split('').reduce((a, v) => (v === char ? a + 1 : a), 0); +``` + +### Or + +```js {.wrap} +const countOccurrences = (str, char) => [...str].filter(item => item === char).length; +``` + +### Or + +```js {.wrap} +const countOccurrences = (str, char) => str.split('').filter(item => item === char).length; +``` + +### Example + +```js {.wrap} +countOccurrences('a.b.c.d.e', '.'); // 4 +``` \ No newline at end of file diff --git a/note/javascript/string/decapitalize-a-string.md b/note/javascript/string/decapitalize-a-string.md new file mode 100644 index 0000000..e9bae13 --- /dev/null +++ b/note/javascript/string/decapitalize-a-string.md @@ -0,0 +1,34 @@ +--- +title: How to decapitalize a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to decapitalize a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const decapitalize = str => `${str.charAt(0).toLowerCase()}${str.slice(1)}`; +``` + +### Or + +```js {.wrap} +const decapitalize = ([first, ...rest]) => `${first.toLowerCase()}${rest.join('')}`; +``` + +### Example + +```js {.wrap} +decapitalize('Hello world'); // 'hello world' +``` \ No newline at end of file diff --git a/note/javascript/string/escape-html-special-characters.md b/note/javascript/string/escape-html-special-characters.md new file mode 100644 index 0000000..8aadf5c --- /dev/null +++ b/note/javascript/string/escape-html-special-characters.md @@ -0,0 +1,28 @@ +--- +title: How to escape html special characters in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to escape html special characters only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const escape = str => str.replace(/&/g, '&').replace(//g, '>').replace(/'/g, ''').replace(/"/g, '"'); +``` + +### Or + +```js {.wrap} +const escape = str => str.replace(/[&<>"']/g, m => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[m]); +``` \ No newline at end of file diff --git a/note/javascript/string/generate-a-hash-of-a-string.md b/note/javascript/string/generate-a-hash-of-a-string.md new file mode 100644 index 0000000..317c445 --- /dev/null +++ b/note/javascript/string/generate-a-hash-of-a-string.md @@ -0,0 +1,34 @@ +--- +title: How to generate a hash of a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to generate a hash of a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const hash = str => str.split('').reduce((prev, curr) => Math.imul(31, prev) + curr.charCodeAt(0) | 0, 0); +``` + +### Or + +```js {.wrap} +const hash = str => str.split('').reduce((prev, curr) => (((prev << 5) - prev) + curr.charCodeAt(0)) | 0, 0); +``` + +### Example + +```js {.wrap} +hash('hello'); // 99162322 +``` \ No newline at end of file diff --git a/note/javascript/string/get-the-base-url-without-any-parameters.md b/note/javascript/string/get-the-base-url-without-any-parameters.md new file mode 100644 index 0000000..5632d26 --- /dev/null +++ b/note/javascript/string/get-the-base-url-without-any-parameters.md @@ -0,0 +1,35 @@ +--- +title: How to get the base url without any parameters in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to get the base url without any parameters only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const baseUrl = url => url.indexOf('?') === -1 ? url : url.slice(0, url.indexOf('?')); +``` + +### Or + +```js {.wrap} +// Note that `includes` isn't supported in IE 11 +const baseUrl = url => url.includes('?') ? url.slice(0, url.indexOf('?')) : url; +``` + +### Example + +```js {.wrap} +baseUrl('https://domain.com/path/sub/path?foo=bar&hello=world'); // 'https://domain.com/path/sub/path' +``` \ No newline at end of file diff --git a/note/javascript/string/get-the-file-extension-from-a-file-name.md b/note/javascript/string/get-the-file-extension-from-a-file-name.md new file mode 100644 index 0000000..f0391b9 --- /dev/null +++ b/note/javascript/string/get-the-file-extension-from-a-file-name.md @@ -0,0 +1,22 @@ +--- +title: How to get the file extension from a file name in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to get the file extension from a file name only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const ext = fileName => fileName.split('.').pop(); +``` \ No newline at end of file diff --git a/note/javascript/string/get-the-file-name-from-a-url.md b/note/javascript/string/get-the-file-name-from-a-url.md new file mode 100644 index 0000000..feb8224 --- /dev/null +++ b/note/javascript/string/get-the-file-name-from-a-url.md @@ -0,0 +1,28 @@ +--- +title: How to get the file name from a url in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to get the file name from a url only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const fileName = url => url.substring(url.lastIndexOf('/') + 1); +``` + +### Example + +```js {.wrap} +fileName('http://domain.com/path/to/document.pdf'); // 'document.pdf' +``` \ No newline at end of file diff --git a/note/javascript/string/get-the-length-of-a-string-in-bytes.md b/note/javascript/string/get-the-length-of-a-string-in-bytes.md new file mode 100644 index 0000000..7ea9922 --- /dev/null +++ b/note/javascript/string/get-the-length-of-a-string-in-bytes.md @@ -0,0 +1,29 @@ +--- +title: How to get the length of a string in bytes in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to get the length of a string in bytes only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const bytes = str => new Blob([str]).size; +``` + +### Example + +```js {.wrap} +bytes('hello world'); // 11 +bytes('🎉'); // 4 +``` \ No newline at end of file diff --git a/note/javascript/string/get-the-number-of-a-character-in-a-string.md b/note/javascript/string/get-the-number-of-a-character-in-a-string.md new file mode 100644 index 0000000..a81b8ea --- /dev/null +++ b/note/javascript/string/get-the-number-of-a-character-in-a-string.md @@ -0,0 +1,35 @@ +--- +title: How to get the number of a character in a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to get the number of a character in a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const characterCount = (str, char) => str.split(char).length - 1; +``` + +### Or + +```js {.wrap} +const characterCount = (str, char) => str.replace((new RegExp(String.raw`[^${char}]`, 'g')), '').length; +``` + +### Example + +```js {.wrap} +characterCount('192.168.1.1', '.'); // 3 +characterCount('star wars', 's'); // 2 +``` \ No newline at end of file diff --git a/note/javascript/string/make-the-first-character-of-a-string-lowercase.md b/note/javascript/string/make-the-first-character-of-a-string-lowercase.md new file mode 100644 index 0000000..e338ee5 --- /dev/null +++ b/note/javascript/string/make-the-first-character-of-a-string-lowercase.md @@ -0,0 +1,28 @@ +--- +title: How to make the first character of a string lowercase in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to make the first character of a string lowercase only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const lowercaseFirst = str => `${str.charAt(0).toLowerCase()}${str.slice(1)}`; +``` + +### Example + +```js {.wrap} +lowercaseFirst('Hello World'); // 'hello World' +``` \ No newline at end of file diff --git a/note/javascript/string/normalize-file-path-slashes.md b/note/javascript/string/normalize-file-path-slashes.md new file mode 100644 index 0000000..32082d0 --- /dev/null +++ b/note/javascript/string/normalize-file-path-slashes.md @@ -0,0 +1,29 @@ +--- +title: How to normalize file path slashes in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to normalize file path slashes only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const normalizePath = path => path.replace(/[\\/]+/g, '/'); +``` + +### Example + +```js {.wrap} +normalizePath('\\foo\\bar\\baz\\'); // /foo/bar/baz/ +normalizePath('.//foo//bar///////baz/'); // ./foo/bar/baz/ +``` \ No newline at end of file diff --git a/note/javascript/string/prepend-a-line-number-to-each-line-of-a-text-document.md b/note/javascript/string/prepend-a-line-number-to-each-line-of-a-text-document.md new file mode 100644 index 0000000..f3b0d33 --- /dev/null +++ b/note/javascript/string/prepend-a-line-number-to-each-line-of-a-text-document.md @@ -0,0 +1,39 @@ +--- +title: How to prepend a line number to each line of a text document in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to prepend a line number to each line of a text document only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const prependNumbers = str => str.split(/\r?\n/).map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`).join('\n'); +``` + +### Example + +```js {.wrap} +prependNumbers(`one +two +three +four`); + +/* Output */ +/* +1 one +2 two +3 three +4 four +*/ +``` \ No newline at end of file diff --git a/note/javascript/string/remove-duplicate-lines-of-a-text-document.md b/note/javascript/string/remove-duplicate-lines-of-a-text-document.md new file mode 100644 index 0000000..f3daff5 --- /dev/null +++ b/note/javascript/string/remove-duplicate-lines-of-a-text-document.md @@ -0,0 +1,41 @@ +--- +title: How to remove duplicate lines of a text document in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to remove duplicate lines of a text document only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const removeDuplicateLines = str => Array.from(new Set(str.split(/\r?\n/))).join('\n'); +``` + +### Example + +```js {.wrap} +removeDuplicateLines(`one +three +two +three +one +four`); + +/* Output */ +/* +one +three +two +four +*/ +``` \ No newline at end of file diff --git a/note/javascript/string/remove-empty-lines-of-a-text-document.md b/note/javascript/string/remove-empty-lines-of-a-text-document.md new file mode 100644 index 0000000..c9a02a1 --- /dev/null +++ b/note/javascript/string/remove-empty-lines-of-a-text-document.md @@ -0,0 +1,41 @@ +--- +title: How to remove empty lines of a text document in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to remove empty lines of a text document only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const removeEmptyLines = str => str.split(/\r?\n/).filter(line => line.trim() !== '').join('\n'); +``` + +### Example + +```js {.wrap} +removeEmptyLines(`red + +green +blue + +yellow`); + +/* Output */ +/* +red +green +blue +yellow +*/ +``` \ No newline at end of file diff --git a/note/javascript/string/remove-spaces-from-a-string.md b/note/javascript/string/remove-spaces-from-a-string.md new file mode 100644 index 0000000..61585de --- /dev/null +++ b/note/javascript/string/remove-spaces-from-a-string.md @@ -0,0 +1,28 @@ +--- +title: How to remove spaces from a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to remove spaces from a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const removeSpaces = str => str.replace(/\s/g, ''); +``` + +### Example + +```js {.wrap} +removeSpaces('hel lo wor ld'); // 'helloworld' +``` \ No newline at end of file diff --git a/note/javascript/string/repeat-a-string.md b/note/javascript/string/repeat-a-string.md new file mode 100644 index 0000000..45ff788 --- /dev/null +++ b/note/javascript/string/repeat-a-string.md @@ -0,0 +1,28 @@ +--- +title: How to repeat a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to repeat a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes); +``` + +### Or + +```js {.wrap} +const repeat = (str, numberOfTimes) => Array(numberOfTimes + 1).join(str); +``` diff --git a/note/javascript/string/replace-all-line-breaks-with-br-elements.md b/note/javascript/string/replace-all-line-breaks-with-br-elements.md new file mode 100644 index 0000000..846f02a --- /dev/null +++ b/note/javascript/string/replace-all-line-breaks-with-br-elements.md @@ -0,0 +1,25 @@ +--- +title: How to replace all line breaks with br elements in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to replace all line breaks with br elements only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const nl2br = str => str.replace(new RegExp('\r?\n', 'g'), '
'); + +// In React +str.split('\n').map((item, index) => {item}
) +``` \ No newline at end of file diff --git a/note/javascript/string/replace-all-tab-characters-with-spaces.md b/note/javascript/string/replace-all-tab-characters-with-spaces.md new file mode 100644 index 0000000..0bcf586 --- /dev/null +++ b/note/javascript/string/replace-all-tab-characters-with-spaces.md @@ -0,0 +1,22 @@ +--- +title: How to replace all tab characters with spaces in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to replace all tab characters with spaces only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const replace = (str, numSpaces = 4) => str.replaceAll('\t', ' '.repeat(numSpaces)); +``` \ No newline at end of file diff --git a/note/javascript/string/replace-multiple-spaces-with-a-single-space.md b/note/javascript/string/replace-multiple-spaces-with-a-single-space.md new file mode 100644 index 0000000..ea63a68 --- /dev/null +++ b/note/javascript/string/replace-multiple-spaces-with-a-single-space.md @@ -0,0 +1,32 @@ +--- +title: How to replace multiple spaces with a single space in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to replace multiple spaces with a single space only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Replace spaces, tabs and new line characters +const replaceSpaces = str => str.replace(/\s\s+/g, ' '); + +// Only replace spaces +const replaceOnlySpaces = str => str.replace(/ +/g, ' '); +``` + +### Example + +```js {.wrap} +replaceSpaces('this\n is \ta \rmessage'); // 'this is a message' +``` \ No newline at end of file diff --git a/note/javascript/string/replace-the-first-given-number-of-characters-of-a-string-with-another-character.md b/note/javascript/string/replace-the-first-given-number-of-characters-of-a-string-with-another-character.md new file mode 100644 index 0000000..bfc9dbd --- /dev/null +++ b/note/javascript/string/replace-the-first-given-number-of-characters-of-a-string-with-another-character.md @@ -0,0 +1,28 @@ +--- +title: How to replace the first given number of characters of a string with another character in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to replace the first given number of characters of a string with another character only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const mask = (str, num, mask) => `${str}`.slice(num).padStart(`${str}`.length, mask); +``` + +### Example + +```js {.wrap} +mask(1234567890, 3, '*'); // ***4567890 +``` \ No newline at end of file diff --git a/note/javascript/string/reverse-a-string.md b/note/javascript/string/reverse-a-string.md new file mode 100644 index 0000000..b6c91cf --- /dev/null +++ b/note/javascript/string/reverse-a-string.md @@ -0,0 +1,46 @@ +--- +title: How to reverse a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to reverse a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const reverse = str => str.split('').reverse().join(''); +``` + +### Or + +```js {.wrap} +const reverse = str => [...str].reverse().join(''); +``` + +### Or + +```js {.wrap} +const reverse = str => str.split('').reduce((rev, char)=> `${char}${rev}`, ''); +``` + +### Or + +```js {.wrap} +const reverse = str => (str === '') ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`; +``` + +### Example + +```js {.wrap} +reverse('hello world'); // 'dlrow olleh' +``` \ No newline at end of file diff --git a/note/javascript/string/reverse-the-order-of-lines-of-a-text.md b/note/javascript/string/reverse-the-order-of-lines-of-a-text.md new file mode 100644 index 0000000..3cfb6dc --- /dev/null +++ b/note/javascript/string/reverse-the-order-of-lines-of-a-text.md @@ -0,0 +1,37 @@ +--- +title: How to reverse the order of lines of a text in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to reverse the order of lines of a text only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const reverseLines = str => str.split(/\r?\n/).reverse().join('\n'); +``` + +### Example + +```js {.wrap} +reverseLines(`one +two +three`); + +/* Output */ +/* +three +two +one +*/ +``` \ No newline at end of file diff --git a/note/javascript/string/sort-lines-of-a-text-document-in-the-alphabetical-order.md b/note/javascript/string/sort-lines-of-a-text-document-in-the-alphabetical-order.md new file mode 100644 index 0000000..2f38475 --- /dev/null +++ b/note/javascript/string/sort-lines-of-a-text-document-in-the-alphabetical-order.md @@ -0,0 +1,54 @@ +--- +title: How to sort lines of a text document in the alphabetical order in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to sort lines of a text document in the alphabetical order only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const sortLines = str => str.split(/\r?\n/).sort().join('\n'); + +// Reverse the order +const reverseSortedLines = str => str.split(/\r?\n/).sort().reverse().join('\n'); +``` + +### Example + +```js {.wrap} +sortLines(`Thaddeus Mullen +Kareem Marshall +Ferdinand Valentine +Hasad Lindsay +Mufutau Berg +Knox Tyson +Kasimir Fletcher +Colton Sharp +Adrian Rosales +Theodore Rogers`); + +/* Output */ +/* +Adrian Rosales +Colton Sharp +Ferdinand Valentine +Hasad Lindsay +Kareem Marshall +Kasimir Fletcher +Knox Tyson +Mufutau Berg +Thaddeus Mullen +Theodore Rogers +*/ +``` \ No newline at end of file diff --git a/note/javascript/string/sort-the-characters-of-a-string-in-the-alphabetical-order.md b/note/javascript/string/sort-the-characters-of-a-string-in-the-alphabetical-order.md new file mode 100644 index 0000000..6ac3620 --- /dev/null +++ b/note/javascript/string/sort-the-characters-of-a-string-in-the-alphabetical-order.md @@ -0,0 +1,28 @@ +--- +title: How to sort the characters of a string in the alphabetical order in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to sort the characters of a string in the alphabetical order only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const sort = str => str.split('').sort((a, b) => a.localeCompare(b)).join(''); +``` + +### Example + +```js {.wrap} +sort('hello world'); // dehllloorw +``` \ No newline at end of file diff --git a/note/javascript/string/strip-ansi-codes-from-a-string.md b/note/javascript/string/strip-ansi-codes-from-a-string.md new file mode 100644 index 0000000..c00f076 --- /dev/null +++ b/note/javascript/string/strip-ansi-codes-from-a-string.md @@ -0,0 +1,29 @@ +--- +title: How to strip ansi codes from a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to strip ansi codes from a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const stripAnsiCodes = str => str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); +``` + +### Example + +```js {.wrap} +stripAnsiCodes('\u001B[4mcake\u001B[0m'); // 'cake' +stripAnsiCodes('\u001B[0m\u001B[4m\u001B[42m\u001B[31mfoo\u001B[39m\u001B[49m\u001B[24mfoo\u001B[0m'); // 'foofoo' +``` \ No newline at end of file diff --git a/note/javascript/string/swap-case-of-characters-in-a-string.md b/note/javascript/string/swap-case-of-characters-in-a-string.md new file mode 100644 index 0000000..d1d418e --- /dev/null +++ b/note/javascript/string/swap-case-of-characters-in-a-string.md @@ -0,0 +1,28 @@ +--- +title: How to swap case of characters in a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to swap case of characters in a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const swapCase = str => str.split('').map(c => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase())).join(''); +``` + +### Example + +```js {.wrap} +swapCase('Hello World'); // 'hELLO wORLD' +``` \ No newline at end of file diff --git a/note/javascript/string/trim-slashes-at-the-beginning-and-the-end-of-a-string.md b/note/javascript/string/trim-slashes-at-the-beginning-and-the-end-of-a-string.md new file mode 100644 index 0000000..492b215 --- /dev/null +++ b/note/javascript/string/trim-slashes-at-the-beginning-and-the-end-of-a-string.md @@ -0,0 +1,34 @@ +--- +title: How to trim slashes at the beginning and the end of a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to trim slashes at the beginning and the end of a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const trimSlashes = str => str.replace(/^\/+|\/+$/g, ''); +``` + +### Or + +```js {.wrap} +const trimSlashes = str => str.split('/').filter(Boolean).join('/'); +``` + +### Example + +```js {.wrap} +trimSlashes('//hello/world///'); // hello/world +``` \ No newline at end of file diff --git a/note/javascript/string/trim-some-character.md b/note/javascript/string/trim-some-character.md new file mode 100644 index 0000000..1129295 --- /dev/null +++ b/note/javascript/string/trim-some-character.md @@ -0,0 +1,30 @@ +--- +title: How to trim some character in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to trim some character only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const trim = (str, char) => str.split(char).filter(Boolean).join(); +``` + +### Example + +```js {.wrap} +trim('/hello world//', '/'); // hello world +trim('"hello world"', '"'); // hello world +trim(' hello world ', ' '); // hello world +``` \ No newline at end of file diff --git a/note/javascript/string/trim-the-file-extension-from-a-file-name.md b/note/javascript/string/trim-the-file-extension-from-a-file-name.md new file mode 100644 index 0000000..641b452 --- /dev/null +++ b/note/javascript/string/trim-the-file-extension-from-a-file-name.md @@ -0,0 +1,30 @@ +--- +title: How to trim the file extension from a file name in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to trim the file extension from a file name only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const trimExt = fileName => fileName.indexOf('.') === -1 ? fileName : fileName.split('.').slice(0, -1).join('.'); +``` + +### Example + +```js {.wrap} +trimExt('document'); // document +trimExt('document.pdf'); // document +trimExt('document.2020.pdf'); // document.2020 +``` \ No newline at end of file diff --git a/note/javascript/string/truncate-a-string-at-full-words.md b/note/javascript/string/truncate-a-string-at-full-words.md new file mode 100644 index 0000000..5eb8567 --- /dev/null +++ b/note/javascript/string/truncate-a-string-at-full-words.md @@ -0,0 +1,28 @@ +--- +title: How to truncate a string at full words in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to truncate a string at full words only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const truncate = (str, max, suffix) => str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`; +``` + +### Example + +```js {.wrap} +truncate('This is a long message', 20, '...'); // 'This is a long...' +``` \ No newline at end of file diff --git a/note/javascript/string/unescape-html-special-characters.md b/note/javascript/string/unescape-html-special-characters.md new file mode 100644 index 0000000..98af719 --- /dev/null +++ b/note/javascript/string/unescape-html-special-characters.md @@ -0,0 +1,22 @@ +--- +title: How to unescape html special characters in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to unescape html special characters only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const unescape = str => str.replace(/&/g , '&').replace(/</g , '<').replace(/>/g , '>').replace(/�*39;/g , "'").replace(/"/g, '"'); +``` \ No newline at end of file diff --git a/note/javascript/string/uppercase-the-first-character-of-each-word-in-a-string.md b/note/javascript/string/uppercase-the-first-character-of-each-word-in-a-string.md new file mode 100644 index 0000000..06fc23a --- /dev/null +++ b/note/javascript/string/uppercase-the-first-character-of-each-word-in-a-string.md @@ -0,0 +1,34 @@ +--- +title: How to uppercase the first character of each word in a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - String +layout: note +--- + + + +In this Article we will go through how to uppercase the first character of each word in a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const uppercaseWords = str => str.split(' ').map(w => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join(' '); +``` + +### Or + +```js {.wrap} +const uppercaseWords = str => str.replace(/^(.)|\s+(.)/g, c => c.toUpperCase()); +``` + +### Example + +```js {.wrap} +uppercaseWords('hello world'); // 'Hello World' +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-date-is-a-weekday.md b/note/javascript/validator/check-if-a-date-is-a-weekday.md new file mode 100644 index 0000000..efaab12 --- /dev/null +++ b/note/javascript/validator/check-if-a-date-is-a-weekday.md @@ -0,0 +1,25 @@ +--- +title: How to check if a date is a weekday in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a date is a weekday only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isWeekday = (date = new Date()) => date.getDay() % 6 !== 0; +``` +Parameters `date` is a Date object. + + diff --git a/note/javascript/validator/check-if-a-date-is-a-weekend.md b/note/javascript/validator/check-if-a-date-is-a-weekend.md new file mode 100644 index 0000000..3a5afc5 --- /dev/null +++ b/note/javascript/validator/check-if-a-date-is-a-weekend.md @@ -0,0 +1,25 @@ +--- +title: How to check if a date is a weekend in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a date is a weekend only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isWeekend = (date = new Date()) => date.getDay() % 6 === 0; +``` +Parameters `date` is a Date object. + + diff --git a/note/javascript/validator/check-if-a-date-is-between-two-dates.md b/note/javascript/validator/check-if-a-date-is-between-two-dates.md new file mode 100644 index 0000000..3739ec8 --- /dev/null +++ b/note/javascript/validator/check-if-a-date-is-between-two-dates.md @@ -0,0 +1,25 @@ +--- +title: How to check if a date is between two dates in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a date is between two dates only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isBetween = (date, min, max) => (date.getTime() >= min.getTime() && date.getTime() <= max.getTime()); +``` +Parameters `min`, `max` and `date` are `Date` instances. + + diff --git a/note/javascript/validator/check-if-a-date-is-today.md b/note/javascript/validator/check-if-a-date-is-today.md new file mode 100644 index 0000000..959ae2d --- /dev/null +++ b/note/javascript/validator/check-if-a-date-is-today.md @@ -0,0 +1,25 @@ +--- +title: How to check if a date is today in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a date is today only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10); +``` +Parameters `date` is a Date object. + + diff --git a/note/javascript/validator/check-if-a-date-occurs-in-the-current-year.md b/note/javascript/validator/check-if-a-date-occurs-in-the-current-year.md new file mode 100644 index 0000000..7cce483 --- /dev/null +++ b/note/javascript/validator/check-if-a-date-occurs-in-the-current-year.md @@ -0,0 +1,25 @@ +--- +title: How to check if a date occurs in the current year in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a date occurs in the current year only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isCurrentYear = (date) => date.getUTCFullYear() === new Date().getUTCFullYear(); +``` +Parameters `date` is a Date object. + + diff --git a/note/javascript/validator/check-if-a-flat-array-has-duplicate-values.md b/note/javascript/validator/check-if-a-flat-array-has-duplicate-values.md new file mode 100644 index 0000000..f74ac21 --- /dev/null +++ b/note/javascript/validator/check-if-a-flat-array-has-duplicate-values.md @@ -0,0 +1,29 @@ +--- +title: How to check if a flat array has duplicate values in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a flat array has duplicate values only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const hasDuplicateValues = arr => new Set(arr).size !== arr.length; +``` + +### Example + +```js {.wrap} +hasDuplicateValues(['h', 'e', 'l', 'l', 'o']); // true +hasDuplicateValues(['w', 'o', 'r', 'd']); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-given-integer-is-a-prime-number.md b/note/javascript/validator/check-if-a-given-integer-is-a-prime-number.md new file mode 100644 index 0000000..a6722fd --- /dev/null +++ b/note/javascript/validator/check-if-a-given-integer-is-a-prime-number.md @@ -0,0 +1,22 @@ +--- +title: How to check if a given integer is a prime number in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a given integer is a prime number only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isPrime = num => (num > 1) && Array(Math.floor(Math.sqrt(num)) - 1).fill(0).map((_, i) => i + 2).every(i => num % i !== 0); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-number-is-a-power-of-2.md b/note/javascript/validator/check-if-a-number-is-a-power-of-2.md new file mode 100644 index 0000000..343cbdd --- /dev/null +++ b/note/javascript/validator/check-if-a-number-is-a-power-of-2.md @@ -0,0 +1,29 @@ +--- +title: How to check if a number is a power of 2 in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a number is a power of 2 only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isPowerOfTwo = number => (number & (number - 1)) === 0; +``` + +### Example + +```js {.wrap} +isPowerOfTwo(256); // true +isPowerOfTwo(129); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-number-is-even.md b/note/javascript/validator/check-if-a-number-is-even.md new file mode 100644 index 0000000..0364cfb --- /dev/null +++ b/note/javascript/validator/check-if-a-number-is-even.md @@ -0,0 +1,47 @@ +--- +title: How to check if a number is even in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a number is even only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isEven = number => number % 2 === 0; +``` + +### Or + +```js {.wrap} +const isEven = number => (number & 1) === 0; +``` + +### Or + +```js {.wrap} +const isEven = number => !(number & 1); +``` + +### Or + +```js {.wrap} +const isEven = number => Number.isInteger(number / 2); +``` + +### Example + +```js {.wrap} +isEven(1); // false +isEven(2); // true +``` diff --git a/note/javascript/validator/check-if-a-number-is-in-a-given-range.md b/note/javascript/validator/check-if-a-number-is-in-a-given-range.md new file mode 100644 index 0000000..d18756c --- /dev/null +++ b/note/javascript/validator/check-if-a-number-is-in-a-given-range.md @@ -0,0 +1,31 @@ +--- +title: How to check if a number is in a given range in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a number is in a given range only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const inRange = (num, a, b, threshold = 0) => (Math.min(a, b) - threshold <= num && num <= Math.max(a, b) + threshold); +``` + +### Example + +```js {.wrap} +inRange(10, 5, 15); // true +inRange(10, 5, 6); // false +inRange(10, 15, 5); // true +inRange(-10, -5, -15); // true +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-number-is-negative.md b/note/javascript/validator/check-if-a-number-is-negative.md new file mode 100644 index 0000000..c68a10f --- /dev/null +++ b/note/javascript/validator/check-if-a-number-is-negative.md @@ -0,0 +1,35 @@ +--- +title: How to check if a number is negative in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a number is negative only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isNegative = number => Math.sign(number) === -1; +``` + +### Or + +```js {.wrap} +const isNegative = number => number < 0; +``` + +### Example + +```js {.wrap} +isNegative(-3); // true +isNegative(8); // false +``` diff --git a/note/javascript/validator/check-if-a-number-is-odd.md b/note/javascript/validator/check-if-a-number-is-odd.md new file mode 100644 index 0000000..01ea1e0 --- /dev/null +++ b/note/javascript/validator/check-if-a-number-is-odd.md @@ -0,0 +1,41 @@ +--- +title: How to check if a number is odd in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a number is odd only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isOdd = number => number % 2 !== 0; +``` + +### Or + +```js {.wrap} +const isOdd = number => !!(number & 1); +``` + +### Or + +```js {.wrap} +const isOdd = number => !Number.isInteger(number / 2); +``` + +### Example + +```js {.wrap} +isOdd(1); // true +isOdd(2); // false +``` diff --git a/note/javascript/validator/check-if-a-number-is-positive.md b/note/javascript/validator/check-if-a-number-is-positive.md new file mode 100644 index 0000000..8c70c57 --- /dev/null +++ b/note/javascript/validator/check-if-a-number-is-positive.md @@ -0,0 +1,29 @@ +--- +title: How to check if a number is positive in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a number is positive only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isPositive = number => Math.sign(number) === 1; +``` + +### Example + +```js {.wrap} +isPositive(3); // true +isPositive(-8); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-contains-lower-case-characters.md b/note/javascript/validator/check-if-a-string-contains-lower-case-characters.md new file mode 100644 index 0000000..a5c363c --- /dev/null +++ b/note/javascript/validator/check-if-a-string-contains-lower-case-characters.md @@ -0,0 +1,29 @@ +--- +title: How to check if a string contains lower case characters in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string contains lower case characters only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const containsLowerCase = str => str !== str.toUpperCase(); +``` + +### Example + +```js {.wrap} +containsLowerCase('Hello World'); // true +containsLowerCase('HELLO WORLD'); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-contains-only-ascii-characters.md b/note/javascript/validator/check-if-a-string-contains-only-ascii-characters.md new file mode 100644 index 0000000..d5e51c9 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-contains-only-ascii-characters.md @@ -0,0 +1,22 @@ +--- +title: How to check if a string contains only ascii characters in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string contains only ascii characters only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isAscii = str => /^[\x00-\x7F]+$/.test(str); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-contains-only-digits.md b/note/javascript/validator/check-if-a-string-contains-only-digits.md new file mode 100644 index 0000000..d50267a --- /dev/null +++ b/note/javascript/validator/check-if-a-string-contains-only-digits.md @@ -0,0 +1,35 @@ +--- +title: How to check if a string contains only digits in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string contains only digits only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isNumeric = str => !/[^0-9]/.test(str); +``` + +### Example + +```js {.wrap} +isNumeric(2); // true +isNumeric('23'); // true +isNumeric('00123'); // true + +isNumeric('1.23'); // false +isNumeric('-Infinity'); // false +isNumeric('Infinity'); // false +isNumeric('NaN'); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-contains-only-letters-and-numbers.md b/note/javascript/validator/check-if-a-string-contains-only-letters-and-numbers.md new file mode 100644 index 0000000..e499273 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-contains-only-letters-and-numbers.md @@ -0,0 +1,32 @@ +--- +title: How to check if a string contains only letters and numbers in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string contains only letters and numbers only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isAlphanumeric = str => /^[0-9A-Z]+$/i.test(str); +``` + +### Example + +```js {.wrap} +isAlphanumeric('helloworld'); // true +isAlphanumeric('HelloWorld'); // true +isAlphanumeric('hello world'); // false +isAlphanumeric('hello123'); // true +isAlphanumeric('hello 123'); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-contains-only-letters.md b/note/javascript/validator/check-if-a-string-contains-only-letters.md new file mode 100644 index 0000000..ede06aa --- /dev/null +++ b/note/javascript/validator/check-if-a-string-contains-only-letters.md @@ -0,0 +1,31 @@ +--- +title: How to check if a string contains only letters in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string contains only letters only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isAlpha = str => /^[A-Z]+$/i.test(str); +``` + +### Example + +```js {.wrap} +isAlpha('helloworld'); // true +isAlpha('HelloWorld'); // true +isAlpha('hello world'); // false +isAlpha('0123456789'); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-contains-upper-case-characters.md b/note/javascript/validator/check-if-a-string-contains-upper-case-characters.md new file mode 100644 index 0000000..7ce2448 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-contains-upper-case-characters.md @@ -0,0 +1,29 @@ +--- +title: How to check if a string contains upper case characters in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string contains upper case characters only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const containsUpperCase = str => str !== str.toLowerCase(); +``` + +### Example + +```js {.wrap} +containsUpperCase('Hello World'); // true +containsUpperCase('hello world'); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-contains-whitespace.md b/note/javascript/validator/check-if-a-string-contains-whitespace.md new file mode 100644 index 0000000..d90c816 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-contains-whitespace.md @@ -0,0 +1,28 @@ +--- +title: How to check if a string contains whitespace in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string contains whitespace only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const containsWhitespace = str => str => /\s/.test(str); +``` + +### Example + +```js {.wrap} +containsWhitespace('hello world'); // true +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-is-a-hexadecimal-color.md b/note/javascript/validator/check-if-a-string-is-a-hexadecimal-color.md new file mode 100644 index 0000000..ddf6d14 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-is-a-hexadecimal-color.md @@ -0,0 +1,31 @@ +--- +title: How to check if a string is a hexadecimal color in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string is a hexadecimal color only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isHexColor = color => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color); +``` + +### Example + +```js {.wrap} +isHexColor('#012'); // true +isHexColor('#A1B2C3'); // true +isHexColor('012'); // false +isHexColor('#GHIJKL'); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-is-a-hexadecimal-number.md b/note/javascript/validator/check-if-a-string-is-a-hexadecimal-number.md new file mode 100644 index 0000000..c3d09b0 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-is-a-hexadecimal-number.md @@ -0,0 +1,36 @@ +--- +title: How to check if a string is a hexadecimal number in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string is a hexadecimal number only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isHexadecimal = str => /^[A-F0-9]+$/i.test(str); +``` + +### Or + +```js {.wrap} +const isHexadecimal = str => str.split('').every(c => '0123456789ABCDEFabcdef'.indexOf(c) !== -1); +``` + +### Example + +```js {.wrap} +isHexadecimal('123'); // true +isHexadecimal('A1B2C3'); // true +isHexadecimal('#123'); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-is-a-mongo-db-object-id.md b/note/javascript/validator/check-if-a-string-is-a-mongo-db-object-id.md new file mode 100644 index 0000000..e0386a4 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-is-a-mongo-db-object-id.md @@ -0,0 +1,28 @@ +--- +title: How to check if a string is a mongodb objectid in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string is a mongodb objectid only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isMongoId = str => str.length === 24 && /^[A-F0-9]+$/i.test(str); +``` + +### Or + +```js {.wrap} +const isMongoId = str => str.length === 24 && str.split('').every(c => '0123456789ABCDEFabcdef'.indexOf(c) !== -1); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-is-an-octal-number.md b/note/javascript/validator/check-if-a-string-is-an-octal-number.md new file mode 100644 index 0000000..ea010c9 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-is-an-octal-number.md @@ -0,0 +1,22 @@ +--- +title: How to check if a string is an octal number in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string is an octal number only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isOctal = str => /^(0o)?[0-7]+$/i.test(str); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-is-lower-case.md b/note/javascript/validator/check-if-a-string-is-lower-case.md new file mode 100644 index 0000000..7e3cab1 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-is-lower-case.md @@ -0,0 +1,22 @@ +--- +title: How to check if a string is lower case in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string is lower case only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isLowerCase = str => str === str.toLowerCase(); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-string-is-upper-case.md b/note/javascript/validator/check-if-a-string-is-upper-case.md new file mode 100644 index 0000000..7316db4 --- /dev/null +++ b/note/javascript/validator/check-if-a-string-is-upper-case.md @@ -0,0 +1,22 @@ +--- +title: How to check if a string is upper case in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a string is upper case only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isUpperCase = str => str === str.toUpperCase(); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-a-business-identifier-code.md b/note/javascript/validator/check-if-a-value-is-a-business-identifier-code.md new file mode 100644 index 0000000..9eb7867 --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-a-business-identifier-code.md @@ -0,0 +1,22 @@ +--- +title: How to check if a value is a business identifier code in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is a business identifier code only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isBIC = value => /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-a-number.md b/note/javascript/validator/check-if-a-value-is-a-number.md new file mode 100644 index 0000000..f520492 --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-a-number.md @@ -0,0 +1,22 @@ +--- +title: How to check if a value is a number in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is a number only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isNumber = value => !isNaN(parseFloat(value)) && isFinite(value); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-a-plain-object.md b/note/javascript/validator/check-if-a-value-is-a-plain-object.md new file mode 100644 index 0000000..42e2a4d --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-a-plain-object.md @@ -0,0 +1,35 @@ +--- +title: How to check if a value is a plain object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is a plain object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isPlainObject = v => (!!v && typeof v === 'object' && (v.__proto__ === null || v.__proto__ === Object.prototype)); +``` + +### Example + +```js {.wrap} +isPlainObject(null); // false +isPlainObject('hello world'); // false +isPlainObject([]); // false +isPlainObject(Object.create(null)); // false +isPlainObject(function() {}); // false + +isPlainObject({}); // true +isPlainObject({ a: '1', b: '2' }); // true +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-a-regular-expression.md b/note/javascript/validator/check-if-a-value-is-a-regular-expression.md new file mode 100644 index 0000000..2c80209 --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-a-regular-expression.md @@ -0,0 +1,22 @@ +--- +title: How to check if a value is a regular expression in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is a regular expression only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isRegExp = value => Object.prototype.toString.call(value) === '[object RegExp]'; +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-a-string.md b/note/javascript/validator/check-if-a-value-is-a-string.md new file mode 100644 index 0000000..bec6e03 --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-a-string.md @@ -0,0 +1,30 @@ +--- +title: How to check if a value is a string in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is a string only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isString = value => Object.prototype.toString.call(value) === '[object String]'; +``` + +### Example + +```js {.wrap} +isString('hello world'); // true +isString(new String('hello world')); // true +isString(10); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-an-object.md b/note/javascript/validator/check-if-a-value-is-an-object.md new file mode 100644 index 0000000..6023196 --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-an-object.md @@ -0,0 +1,32 @@ +--- +title: How to check if a value is an object in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is an object only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isObject = v => (v !== null && typeof v === 'object'); +``` + +### Example + +```js {.wrap} +isObject(null); // false +isObject('hello world'); // false + +isObject({}); // true +isObject([]); // true +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-base32-encoded.md b/note/javascript/validator/check-if-a-value-is-base32-encoded.md new file mode 100644 index 0000000..5c98abb --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-base32-encoded.md @@ -0,0 +1,22 @@ +--- +title: How to check if a value is base32 encoded in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is base32 encoded only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isBase32 = value => value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-base58-encoded.md b/note/javascript/validator/check-if-a-value-is-base58-encoded.md new file mode 100644 index 0000000..3d2f179 --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-base58-encoded.md @@ -0,0 +1,23 @@ +--- +title: How to check if a value is base58 encoded in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is base58 encoded only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// It doesn't accept the I, O, l characters +const isBase58 = value => /^[A-HJ-NP-Za-km-z1-9]*$/.test(value); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-base64-encoded.md b/note/javascript/validator/check-if-a-value-is-base64-encoded.md new file mode 100644 index 0000000..677f00c --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-base64-encoded.md @@ -0,0 +1,22 @@ +--- +title: How to check if a value is base64 encoded in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is base64 encoded only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isBase64 = value => /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-value-is-nil.md b/note/javascript/validator/check-if-a-value-is-nil.md new file mode 100644 index 0000000..dbda842 --- /dev/null +++ b/note/javascript/validator/check-if-a-value-is-nil.md @@ -0,0 +1,22 @@ +--- +title: How to check if a value is nil in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a value is nil only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isNil = (value) => value == null; +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-a-year-is-leap-year.md b/note/javascript/validator/check-if-a-year-is-leap-year.md new file mode 100644 index 0000000..0f49a21 --- /dev/null +++ b/note/javascript/validator/check-if-a-year-is-leap-year.md @@ -0,0 +1,29 @@ +--- +title: How to check if a year is leap year in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if a year is leap year only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isLeapYear = year => (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); +``` + +### Or + +```js {.wrap} +// Get the number of days in February +const isLeapYear = year => new Date(year, 1, 29).getDate() === 29; +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-all-array-elements-are-equal-to-a-given-value.md b/note/javascript/validator/check-if-all-array-elements-are-equal-to-a-given-value.md new file mode 100644 index 0000000..775d7f4 --- /dev/null +++ b/note/javascript/validator/check-if-all-array-elements-are-equal-to-a-given-value.md @@ -0,0 +1,37 @@ +--- +title: How to check if all array elements are equal to a given value in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if all array elements are equal to a given value only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isEqual = (arr, value) => arr.every(item => item === value); +``` + +### Or + +```js {.wrap} +// Ends earlier for false arrays +const isEqual = (arr, value) => !arr.some(item => item !== value); +``` + +### Example + +```js {.wrap} +isEqual(['foo', 'foo'], 'foo'); // true +isEqual(['foo', 'bar'], 'foo'); // false +isEqual(['bar', 'bar'], 'foo'); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-all-items-in-an-array-are-equal.md b/note/javascript/validator/check-if-all-items-in-an-array-are-equal.md new file mode 100644 index 0000000..2fdecd0 --- /dev/null +++ b/note/javascript/validator/check-if-all-items-in-an-array-are-equal.md @@ -0,0 +1,35 @@ +--- +title: How to check if all items in an array are equal in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if all items in an array are equal only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const areEqual = arr => arr.length > 0 && arr.every(item => item === arr[0]); +``` + +### Or + +```js {.wrap} +const areEqual = arr => new Set(arr).size === 1; +``` + +### Example + +```js {.wrap} +areEqual([1, 2, 3, 4]); // false +areEqual(['hello', 'hello', 'hello']); // true +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-an-array-contains-a-value-matching-some-criterias.md b/note/javascript/validator/check-if-an-array-contains-a-value-matching-some-criterias.md new file mode 100644 index 0000000..7a88737 --- /dev/null +++ b/note/javascript/validator/check-if-an-array-contains-a-value-matching-some-criterias.md @@ -0,0 +1,42 @@ +--- +title: How to check if an array contains a value matching some criterias in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if an array contains a value matching some criterias only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const contains = (arr, criteria) => arr.some(v => criteria(v)); +``` + +### Or + +```js {.wrap} +const contains = (arr, criteria) => arr.some(criteria); +``` + +### Or + +```js {.wrap} +const contains = (arr,criteria) => arr.filter(criteria).length > 0; +``` + +### Example + +```js {.wrap} +contains([10, 20, 30], v => v > 25 ); // true +contains([10, 20, 30], v => v > 100 || v < 15 ); // true +contains([10, 20, 30], v => v > 100 ); // false +``` diff --git a/note/javascript/validator/check-if-an-array-is-not-empty.md b/note/javascript/validator/check-if-an-array-is-not-empty.md new file mode 100644 index 0000000..33251a9 --- /dev/null +++ b/note/javascript/validator/check-if-an-array-is-not-empty.md @@ -0,0 +1,29 @@ +--- +title: How to check if an array is not empty in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if an array is not empty only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isNotEmpty = arr => Array.isArray(arr) && Object.keys(arr).length > 0; +``` + +### Example + +```js {.wrap} +isNotEmpty([]); // false +isNotEmpty([1, 2, 3]); // true +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-an-array-is-subset-of-other-array.md b/note/javascript/validator/check-if-an-array-is-subset-of-other-array.md new file mode 100644 index 0000000..fad8989 --- /dev/null +++ b/note/javascript/validator/check-if-an-array-is-subset-of-other-array.md @@ -0,0 +1,37 @@ +--- +title: How to check if an array is subset of other array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if an array is subset of other array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +// Check if `b` is subset of `a` +const isSubset = (a, b) => (new Set(b)).size === (new Set(b.concat(a))).size; +``` + +### Or + +```js {.wrap} +const isSubset = (a, b) => b.join("|").includes(a.join("|")); +``` + +### Example + +```js {.wrap} +isSubset([1, 2], [1, 2, 3, 4]); // true +isSubset([1, 2, 5], [1, 2, 3, 4]); // false +isSubset([6], [1, 2, 3, 4]); // false +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-an-object-is-a-promise.md b/note/javascript/validator/check-if-an-object-is-a-promise.md new file mode 100644 index 0000000..bbe9a46 --- /dev/null +++ b/note/javascript/validator/check-if-an-object-is-a-promise.md @@ -0,0 +1,22 @@ +--- +title: How to check if an object is a promise in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if an object is a promise only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isPromise = obj => !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-an-object-is-an-array.md b/note/javascript/validator/check-if-an-object-is-an-array.md new file mode 100644 index 0000000..d47acb1 --- /dev/null +++ b/note/javascript/validator/check-if-an-object-is-an-array.md @@ -0,0 +1,22 @@ +--- +title: How to check if an object is an array in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if an object is an array only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isArray = obj => Array.isArray(obj); +``` \ No newline at end of file diff --git a/note/javascript/validator/check-if-an-object-is-empty.md b/note/javascript/validator/check-if-an-object-is-empty.md new file mode 100644 index 0000000..f0b22ff --- /dev/null +++ b/note/javascript/validator/check-if-an-object-is-empty.md @@ -0,0 +1,28 @@ +--- +title: How to check if an object is empty in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to check if an object is empty only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object; +``` + +### Or for enumerable property names only + +```js {.wrap} +const isEmpty = obj => JSON.stringify(obj) === '{}'; +``` \ No newline at end of file diff --git a/note/javascript/validator/validate-a-gregorian-date.md b/note/javascript/validator/validate-a-gregorian-date.md new file mode 100644 index 0000000..01fcaf2 --- /dev/null +++ b/note/javascript/validator/validate-a-gregorian-date.md @@ -0,0 +1,31 @@ +--- +title: How to validate a gregorian date in JavaScript +tags: + - JavaScript + - ES6 + - one-line + - js + - Validator +layout: note +--- + + + +In this Article we will go through how to validate a gregorian date only using single line of code in JavaScript. +This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`. +
+
+Let's define this short function: + +```js {.wrap} +const isValidDate = (m, d, y) => 0 <= m && m <= 11 && 0 < y && y < 32768 && 0 < d && d <= (new Date(y, m, 0)).getDate(); +``` +Parameters `m`: the month (zero-based index). + + +Parameters `d`: the day. + + +Parameters `y`: the year. + +