update snippets 0-All

This commit is contained in:
Stefan Feješ
2017-12-25 14:49:52 +01:00
committed by Agamemnon Zorbas
parent 6bedb8fba4
commit 0c129cdd02
33 changed files with 166 additions and 74 deletions

View File

@ -9,5 +9,8 @@ const UUIDGenerator = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(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'
```

View File

@ -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.
```js
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
// round(1.005, 2) -> 1.01
const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
```
```js
round(1.005, 2) // 1.01
```

View File

@ -6,6 +6,9 @@ Use `Array.reduce()` to create a promise chain, where each promise returns the n
```js
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
```

View File

@ -7,5 +7,8 @@ This method also works with strings.
```js
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
// sample([3, 7, 9, 11]) -> 9
```
```js
sample([3, 7, 9, 11]) -> 9
```

View File

@ -13,5 +13,8 @@ const scrollToTop = () => {
window.scrollTo(0, c - c / 8);
}
};
// scrollToTop()
```
```js
scrollToTop()
```

View File

@ -7,7 +7,9 @@ If the property does not exists returns `undefined`.
```js
const select = (from, selector) =>
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'
```

View File

@ -6,9 +6,10 @@ Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of th
```js
const shallowClone = obj => Object.assign({}, obj);
/*
```
```js
const a = { x: true, y: 1 };
const b = shallowClone(a);
a === b -> false
*/
```

View File

@ -13,7 +13,10 @@ const shuffle = ([...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]
```

View File

@ -6,5 +6,8 @@ Use `filter()` to remove values that are not part of `values`, determined using
```js
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]
```

View File

@ -6,11 +6,12 @@ Delay executing part of an `async` function, by putting it to sleep, returning a
```js
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
/*
```
```js
async function sleepyWork() {
console.log('I\'m going to sleep for 1 second.');
await sleep(1000);
console.log('I woke up after 1 second.');
}
*/
```

View File

@ -7,5 +7,8 @@ Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`,
```js
const sortCharactersInString = str =>
str.split('').sort((a, b) => a.localeCompare(b)).join('');
// sortCharactersInString('cabbage') -> 'aabbceg'
```
```js
sortCharactersInString('cabbage') -> 'aabbceg'
```

View File

@ -13,5 +13,8 @@ const speechSynthesis = message => {
msg.voice = window.speechSynthesis.getVoices()[0];
window.speechSynthesis.speak(msg);
};
// speechSynthesis('Hello, World') -> plays the message
```
```js
speechSynthesis('Hello, World') -> // plays the message
```

View File

@ -6,9 +6,10 @@ Use closures and the spread operator (`...`) to map the array of arguments to th
```js
const spreadOver = fn => argsArr => fn(...argsArr);
/*
```
```js
const arrayMax = spreadOver(Math.max)
arrayMax([1,2,3]) // -> 3
arrayMax([1,2,4]) // -> 4
*/
```
arrayMax([1,2,3]) -> 3
arrayMax([1,2,4]) -> 4
```

View File

@ -14,6 +14,9 @@ const standardDeviation = (arr, usePopulation = false) => {
.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)
```

View File

@ -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 sA = new Set(a), sB = new Set(b);
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]
```

View File

@ -6,6 +6,9 @@ Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise, retur
```js
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]
```

View File

@ -6,6 +6,9 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from
```js
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) -> []
```

View File

@ -6,6 +6,9 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from
```js
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]
```

View File

@ -9,6 +9,9 @@ const timeTaken = callback => {
console.time('timeTaken'); const r = callback();
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
```

View File

@ -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)
.map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
.join('');
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'
// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'
return s.slice(0,1).toLowerCase() + s.slice(1)
}
```
```js
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'
```

View File

@ -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.
```js
const toDecimalMark = num => num.toLocaleString('en-US');
// toDecimalMark(12305030388.9087) -> "12,305,030,388.9087"
const toDecimalMark = num => num.toLocaleString("en-US");
```
```js
toDecimalMark(12305030388.9087) // "12,305,030,388.9087"
```

View File

@ -7,5 +7,8 @@ Throws an error if the passed time cannot be converted to a date.
```js
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'
```

View File

@ -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)
.map(x => x.toLowerCase())
.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'
// 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"
```
```js
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'
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"
```

View File

@ -13,5 +13,8 @@ const toOrdinalSuffix = num => {
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];
};
// toOrdinalSuffix("123") -> "123rd"
```
```js
toOrdinalSuffix("123") -> "123rd"
```

View File

@ -11,10 +11,13 @@ const toSnakeCase = str => {
.map(x => x.toLowerCase())
.join('_');
};
// toSnakeCase("camelCase") -> 'camel_case'
// toSnakeCase("some text") -> 'some_text'
// 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_small_things"
// toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html"
```
```js
toSnakeCase("camelCase") -> 'camel_case'
toSnakeCase("some text") -> 'some_text'
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"
```

View File

@ -8,5 +8,8 @@ Return the string truncated to the desired length, with `...` appended to the en
```js
const truncateString = (str, num) =>
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
// truncateString('boomerang', 7) -> 'boom...'
```
```js
truncateString('boomerang', 7) -> 'boom...'
```

View File

@ -3,8 +3,11 @@
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.
```js
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
```

View File

@ -6,5 +6,8 @@ Create a `Set` with all values of `a` and `b` and convert to an array.
```js
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]
```

View File

@ -8,5 +8,8 @@ Use `Number()` to check if the coercion holds.
```js
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
// validateNumber('10') -> true
```
```js
validateNumber('10') -> true
```

View File

@ -8,5 +8,8 @@ _(For a snippet that mutates the original array see [`pull`](#pull))_
```js
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]
```

View File

@ -7,6 +7,9 @@ Omit the second argument to use the default regex.
```js
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"]
```

View File

@ -10,9 +10,12 @@ If lengths of the argument-arrays vary, `undefined` is used where no value could
const zip = (...arrays) => {
const maxLength = Math.max(...arrays.map(x => x.length));
return Array.from({length: maxLength}).map((_, 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]]
return Array.from({length: arrays.length}, (_, k) => arrays[k][i]);
})
}
```
```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]]
```

View File

@ -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()`.
```js
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}
const zipObject = ( props, values ) => props.reduce( ( obj, prop, index ) => ( obj[prop] = values[index], obj ), {} )
```
```js
zipObject(['a','b','c'], [1,2]) // {a: 1, b: 2, c: undefined}
zipObject(['a','b'], [1,2,3]) // {a: 1, b: 2}
```