update snippets 0-All
This commit is contained in:
committed by
Agamemnon Zorbas
parent
6bedb8fba4
commit
0c129cdd02
@ -9,5 +9,8 @@ const UUIDGenerator = () =>
|
|||||||
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
|
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
|
||||||
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
||||||
);
|
);
|
||||||
// UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `Math.round()` and template literals to round the number to the specified nu
|
|||||||
Omit the second argument, `decimals` to round to an integer.
|
Omit the second argument, `decimals` to round to an integer.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
|
const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
|
||||||
// round(1.005, 2) -> 1.01
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
round(1.005, 2) // 1.01
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `Array.reduce()` to create a promise chain, where each promise returns the n
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
||||||
// const delay = (d) => new Promise(r => setTimeout(r, d))
|
```
|
||||||
// runPromisesInSeries([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
|
|
||||||
|
```js
|
||||||
|
const delay = (d) => new Promise(r => setTimeout(r, d))
|
||||||
|
runPromisesInSeries([() => delay(1000), () => delay(2000)]) -> //executes each promise sequentially, taking a total of 3 seconds to complete
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ This method also works with strings.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
|
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
|
||||||
// sample([3, 7, 9, 11]) -> 9
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
sample([3, 7, 9, 11]) -> 9
|
||||||
```
|
```
|
||||||
|
|||||||
@ -13,5 +13,8 @@ const scrollToTop = () => {
|
|||||||
window.scrollTo(0, c - c / 8);
|
window.scrollTo(0, c - c / 8);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// scrollToTop()
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
scrollToTop()
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,7 +7,9 @@ If the property does not exists returns `undefined`.
|
|||||||
```js
|
```js
|
||||||
const select = (from, selector) =>
|
const select = (from, selector) =>
|
||||||
selector.split('.').reduce((prev, cur) => prev && prev[cur], from);
|
selector.split('.').reduce((prev, cur) => prev && prev[cur], from);
|
||||||
|
```
|
||||||
// const obj = {selector: {to: {val: 'val to select'}}};
|
|
||||||
// select(obj, 'selector.to.val'); -> 'val to select'
|
```js
|
||||||
|
const obj = {selector: {to: {val: 'val to select'}}};
|
||||||
|
select(obj, 'selector.to.val'); -> 'val to select'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,9 +6,10 @@ Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of th
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const shallowClone = obj => Object.assign({}, obj);
|
const shallowClone = obj => Object.assign({}, obj);
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
const a = { x: true, y: 1 };
|
const a = { x: true, y: 1 };
|
||||||
const b = shallowClone(a);
|
const b = shallowClone(a);
|
||||||
a === b -> false
|
a === b -> false
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -13,7 +13,10 @@ const shuffle = ([...arr]) => {
|
|||||||
}
|
}
|
||||||
return arr;
|
return arr;
|
||||||
};
|
};
|
||||||
// const foo = [1,2,3]
|
```
|
||||||
// shuffle(foo) -> [2,3,1]
|
|
||||||
// console.log(foo) -> [1,2,3]
|
```js
|
||||||
|
const foo = [1,2,3]
|
||||||
|
shuffle(foo) // [2,3,1]
|
||||||
|
console.log(foo) // [1,2,3]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `filter()` to remove values that are not part of `values`, determined using
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const similarity = (arr, values) => arr.filter(v => values.includes(v));
|
const similarity = (arr, values) => arr.filter(v => values.includes(v));
|
||||||
// similarity([1,2,3], [1,2,4]) -> [1,2]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
similarity([1,2,3], [1,2,4]) -> [1,2]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,11 +6,12 @@ Delay executing part of an `async` function, by putting it to sleep, returning a
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
async function sleepyWork() {
|
async function sleepyWork() {
|
||||||
console.log('I\'m going to sleep for 1 second.');
|
console.log('I\'m going to sleep for 1 second.');
|
||||||
await sleep(1000);
|
await sleep(1000);
|
||||||
console.log('I woke up after 1 second.');
|
console.log('I woke up after 1 second.');
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`,
|
|||||||
```js
|
```js
|
||||||
const sortCharactersInString = str =>
|
const sortCharactersInString = str =>
|
||||||
str.split('').sort((a, b) => a.localeCompare(b)).join('');
|
str.split('').sort((a, b) => a.localeCompare(b)).join('');
|
||||||
// sortCharactersInString('cabbage') -> 'aabbceg'
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
sortCharactersInString('cabbage') -> 'aabbceg'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -13,5 +13,8 @@ const speechSynthesis = message => {
|
|||||||
msg.voice = window.speechSynthesis.getVoices()[0];
|
msg.voice = window.speechSynthesis.getVoices()[0];
|
||||||
window.speechSynthesis.speak(msg);
|
window.speechSynthesis.speak(msg);
|
||||||
};
|
};
|
||||||
// speechSynthesis('Hello, World') -> plays the message
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
speechSynthesis('Hello, World') -> // plays the message
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,9 +6,10 @@ Use closures and the spread operator (`...`) to map the array of arguments to th
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const spreadOver = fn => argsArr => fn(...argsArr);
|
const spreadOver = fn => argsArr => fn(...argsArr);
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
const arrayMax = spreadOver(Math.max)
|
const arrayMax = spreadOver(Math.max)
|
||||||
arrayMax([1,2,3]) // -> 3
|
arrayMax([1,2,3]) -> 3
|
||||||
arrayMax([1,2,4]) // -> 4
|
arrayMax([1,2,4]) -> 4
|
||||||
*/
|
```
|
||||||
```
|
|
||||||
|
|||||||
@ -14,6 +14,9 @@ const standardDeviation = (arr, usePopulation = false) => {
|
|||||||
.reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1))
|
.reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1))
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
// standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample)
|
```
|
||||||
// standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population)
|
|
||||||
|
```js
|
||||||
|
standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample)
|
||||||
|
standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population)
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,6 +8,9 @@ Create a `Set` from each array, then use `Array.filter()` on each of them to onl
|
|||||||
const symmetricDifference = (a, b) => {
|
const symmetricDifference = (a, b) => {
|
||||||
const sA = new Set(a), sB = new Set(b);
|
const sA = new Set(a), sB = new Set(b);
|
||||||
return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
|
return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
|
||||||
};
|
}
|
||||||
// symmetricDifference([1,2,3], [1,2,4]) -> [3,4]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
symmetricDifference([1,2,3], [1,2,4]) -> [3,4]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise, retur
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
|
const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
|
||||||
// tail([1,2,3]) -> [2,3]
|
```
|
||||||
// tail([1]) -> [1]
|
|
||||||
|
```js
|
||||||
|
tail([1,2,3]) -> [2,3]
|
||||||
|
tail([1]) -> [1]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const take = (arr, n = 1) => arr.slice(0, n);
|
const take = (arr, n = 1) => arr.slice(0, n);
|
||||||
// take([1, 2, 3], 5) -> [1, 2, 3]
|
```
|
||||||
// take([1, 2, 3], 0) -> []
|
|
||||||
|
```js
|
||||||
|
take([1, 2, 3], 5) -> [1, 2, 3]
|
||||||
|
take([1, 2, 3], 0) -> []
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
|
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
|
||||||
// takeRight([1, 2, 3], 2) -> [ 2, 3 ]
|
```
|
||||||
// takeRight([1, 2, 3]) -> [3]
|
|
||||||
|
```js
|
||||||
|
takeRight([1, 2, 3], 2) -> [ 2, 3 ]
|
||||||
|
takeRight([1, 2, 3]) -> [3]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -9,6 +9,9 @@ const timeTaken = callback => {
|
|||||||
console.time('timeTaken'); const r = callback();
|
console.time('timeTaken'); const r = callback();
|
||||||
console.timeEnd('timeTaken'); return r;
|
console.timeEnd('timeTaken'); return r;
|
||||||
};
|
};
|
||||||
// timeTaken(() => Math.pow(2, 10)) -> 1024
|
```
|
||||||
// (logged): timeTaken: 0.02099609375ms
|
|
||||||
|
```js
|
||||||
|
timeTaken(() => Math.pow(2, 10)) -> 1024
|
||||||
|
(logged): timeTaken: 0.02099609375ms
|
||||||
```
|
```
|
||||||
|
|||||||
@ -10,10 +10,13 @@ const toCamelCase = str => {
|
|||||||
let s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
|
let s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
|
||||||
.map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
|
.map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
|
||||||
.join('');
|
.join('');
|
||||||
return s.slice(0, 1).toLowerCase() + s.slice(1);
|
return s.slice(0,1).toLowerCase() + s.slice(1)
|
||||||
};
|
}
|
||||||
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
|
```
|
||||||
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
|
|
||||||
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
|
```js
|
||||||
// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'
|
toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
|
||||||
|
toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
|
||||||
|
toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
|
||||||
|
toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,6 +3,9 @@
|
|||||||
Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form. It makes a comma separated string from a number.
|
Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form. It makes a comma separated string from a number.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const toDecimalMark = num => num.toLocaleString('en-US');
|
const toDecimalMark = num => num.toLocaleString("en-US");
|
||||||
// toDecimalMark(12305030388.9087) -> "12,305,030,388.9087"
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
toDecimalMark(12305030388.9087) // "12,305,030,388.9087"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Throws an error if the passed time cannot be converted to a date.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const toEnglishDate = (time) => { try { return new Date(time).toISOString().split('T')[0].replace(/-/g, '/'); } catch (e) {} };
|
const toEnglishDate = (time) => { try { return new Date(time).toISOString().split('T')[0].replace(/-/g, '/'); } catch (e) {} };
|
||||||
// toEnglishDate('09/21/2010') -> '21/09/2010'
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
toEnglishDate('09/21/2010') // '21/09/2010'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -10,9 +10,12 @@ const toKebabCase = str =>
|
|||||||
str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
|
str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
|
||||||
.map(x => x.toLowerCase())
|
.map(x => x.toLowerCase())
|
||||||
.join('-');
|
.join('-');
|
||||||
// toKebabCase("camelCase") -> 'camel-case'
|
```
|
||||||
// toKebabCase("some text") -> 'some-text'
|
|
||||||
// toKebabCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some-mixed-string-with-spaces-underscores-and-hyphens'
|
```js
|
||||||
// toKebabCase("AllThe-small Things") -> "all-the-small-things"
|
toKebabCase("camelCase") -> 'camel-case'
|
||||||
// toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"
|
toKebabCase("some text") -> 'some-text'
|
||||||
|
toKebabCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some-mixed-string-with-spaces-underscores-and-hyphens'
|
||||||
|
toKebabCase("AllThe-small Things") -> "all-the-small-things"
|
||||||
|
toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -13,5 +13,8 @@ const toOrdinalSuffix = num => {
|
|||||||
tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
|
tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
|
||||||
return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) ? int + ordinals[digits[0] - 1] : int + ordinals[3];
|
return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) ? int + ordinals[digits[0] - 1] : int + ordinals[3];
|
||||||
};
|
};
|
||||||
// toOrdinalSuffix("123") -> "123rd"
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
toOrdinalSuffix("123") -> "123rd"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -11,10 +11,13 @@ const toSnakeCase = str => {
|
|||||||
.map(x => x.toLowerCase())
|
.map(x => x.toLowerCase())
|
||||||
.join('_');
|
.join('_');
|
||||||
};
|
};
|
||||||
// toSnakeCase("camelCase") -> 'camel_case'
|
```
|
||||||
// toSnakeCase("some text") -> 'some_text'
|
|
||||||
// toSnakeCase("some-javascript-property") -> 'some_javascript_property'
|
```js
|
||||||
// toSnakeCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some_mixed_string_with_spaces_underscores_and_hyphens'
|
toSnakeCase("camelCase") -> 'camel_case'
|
||||||
// toSnakeCase("AllThe-small Things") -> "all_the_small_things"
|
toSnakeCase("some text") -> 'some_text'
|
||||||
// toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html"
|
toSnakeCase("some-javascript-property") -> 'some_javascript_property'
|
||||||
|
toSnakeCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some_mixed_string_with_spaces_underscores_and_hyphens'
|
||||||
|
toSnakeCase("AllThe-small Things") -> "all_the_smal_things"
|
||||||
|
toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,5 +8,8 @@ Return the string truncated to the desired length, with `...` appended to the en
|
|||||||
```js
|
```js
|
||||||
const truncateString = (str, num) =>
|
const truncateString = (str, num) =>
|
||||||
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
|
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
|
||||||
// truncateString('boomerang', 7) -> 'boom...'
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
truncateString('boomerang', 7) -> 'boom...'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,8 +3,11 @@
|
|||||||
Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).
|
Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).
|
||||||
|
|
||||||
Use `Array.every()` to check if each passed object has the specified property and if it returns a truthy value.
|
Use `Array.every()` to check if each passed object has the specified property and if it returns a truthy value.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const truthCheckCollection = (collection, pre) => (collection.every(obj => obj[pre]));
|
const truthCheckCollection = (collection, pre) => (collection.every(obj => obj[pre]));
|
||||||
// truthCheckCollection([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}], "sex") -> true
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
truthCheckCollection([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}], "sex") -> true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Create a `Set` with all values of `a` and `b` and convert to an array.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const union = (a, b) => Array.from(new Set([...a, ...b]));
|
const union = (a, b) => Array.from(new Set([...a, ...b]));
|
||||||
// union([1,2,3], [4,3,2]) -> [1,2,3,4]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
union([1,2,3], [4,3,2]) -> [1,2,3,4]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,5 +8,8 @@ Use `Number()` to check if the coercion holds.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
|
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
|
||||||
// validateNumber('10') -> true
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
validateNumber('10') -> true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,5 +8,8 @@ _(For a snippet that mutates the original array see [`pull`](#pull))_
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const without = (arr, ...args) => arr.filter(v => !args.includes(v));
|
const without = (arr, ...args) => arr.filter(v => !args.includes(v));
|
||||||
// without([2, 1, 2, 3], 1, 2) -> [3]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
without([2, 1, 2, 3], 1, 2) -> [3]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,6 +7,9 @@ Omit the second argument to use the default regex.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
|
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
|
||||||
// words("I love javaScript!!") -> ["I", "love", "javaScript"]
|
```
|
||||||
// words("python, javaScript & coffee") -> ["python", "javaScript", "coffee"]
|
|
||||||
|
```js
|
||||||
|
words("I love javaScript!!") -> ["I", "love", "javaScript"]
|
||||||
|
words("python, javaScript & coffee") -> ["python", "javaScript", "coffee"]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -10,9 +10,12 @@ If lengths of the argument-arrays vary, `undefined` is used where no value could
|
|||||||
const zip = (...arrays) => {
|
const zip = (...arrays) => {
|
||||||
const maxLength = Math.max(...arrays.map(x => x.length));
|
const maxLength = Math.max(...arrays.map(x => x.length));
|
||||||
return Array.from({length: maxLength}).map((_, i) => {
|
return Array.from({length: maxLength}).map((_, i) => {
|
||||||
return Array.from({length: arrays.length}, (_, k) => arrays[k][i]);
|
return Array.from({length: arrays.length}, (_, k) => arrays[k][i]);
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
// zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]]
|
```
|
||||||
// zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]]
|
|
||||||
|
```js
|
||||||
|
zip(['a', 'b'], [1, 2], [true, false]); // [['a', 1, true], ['b', 2, false]]
|
||||||
|
zip(['a'], [1, 2], [true, false]); // [['a', 1, true], [undefined, 2, false]]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,7 +5,10 @@ Given an array of valid property identifiers and an array of values, return an o
|
|||||||
Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.reduce()`.
|
Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.reduce()`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const zipObject = (props, values) => props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {});
|
const zipObject = ( props, values ) => props.reduce( ( obj, prop, index ) => ( obj[prop] = values[index], obj ), {} )
|
||||||
// zipObject(['a','b','c'], [1,2]) -> {a: 1, b: 2, c: undefined}
|
```
|
||||||
// zipObject(['a','b'], [1,2,3]) -> {a: 1, b: 2}
|
|
||||||
|
```js
|
||||||
|
zipObject(['a','b','c'], [1,2]) // {a: 1, b: 2, c: undefined}
|
||||||
|
zipObject(['a','b'], [1,2,3]) // {a: 1, b: 2}
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user