Updated examples

Removed duplicate and unnecessary examples.
This commit is contained in:
Angelos Chalaris
2018-01-04 14:22:56 +02:00
parent 9341f0aaaa
commit 8281457945
45 changed files with 52 additions and 104 deletions

View File

@ -20,10 +20,6 @@ chainAsync([
},
next => {
console.log('1 second');
setTimeout(next, 1000);
},
next => {
console.log('2 seconds');
}
]);
```

View File

@ -12,5 +12,4 @@ const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.
```js
clampNumber(2, 3, 5); // 3
clampNumber(1, -1, -5); // -1
clampNumber(3, 2, 4); // 3
```

View File

@ -10,5 +10,4 @@ const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1);
```js
collatz(8); // 4
collatz(5); // 16
```

View File

@ -14,6 +14,6 @@ defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
// Example B:
document.querySelector('#someElement').innerHTML = 'Hello';
longRunningFunction(); // the browser will not update the HTML until this has finished
defer(longRunningFunction); // the browser will update the HTML then run the function
longRunningFunction(); //Browser will not update the HTML until this has finished
defer(longRunningFunction); // Browser will update the HTML then run the function
```

View File

@ -12,6 +12,5 @@ const detectDeviceType = () =>
```
```js
detectDeviceType(); // "Mobile"
detectDeviceType(); // "Desktop"
detectDeviceType(); // "Mobile" or "Desktop"
```

View File

@ -20,6 +20,6 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
```js
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
elementIsVisibleInViewport(el); // false // (not fully visible)
elementIsVisibleInViewport(el, true); // true // (partially visible)
elementIsVisibleInViewport(el); // false - (not fully visible)
elementIsVisibleInViewport(el, true); // true - (partially visible)
```

View File

@ -18,7 +18,5 @@ const elo = ([a, b], kFactor = 32) => {
```js
elo([1200, 1200]); // [1216, 1184]
elo([1000, 2000]); // [1031.8991261061358, 1968.1008738938642]
elo([1500, 1000]); // [1501.7036868864648, 998.2963131135352]
elo([1200, 1200], 64); // [1232, 1168]
```

View File

@ -25,7 +25,6 @@ const formatDuration = ms => {
```
```js
formatDuration(1001); // "1 second, 1 millisecond"
formatDuration(343250555); // "3 days, 23 hours, 20 minutes, 50 seconds, 555 milliseconds"
formatDuration(34325055574); // "397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds"
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
```

View File

@ -1,9 +1,9 @@
### geometricProgression
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`.
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`.
Returns an error if `step` equals `1`.
Use `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.map()` to fill with the desired values in a range.
Use `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.map()` to fill with the desired values in a range.
Omit the second argument, `start`, to use a default value of `1`.
Omit the third argument, `step`, to use a default value of `2`.
@ -16,7 +16,6 @@ const geometricProgression = (end, start = 1, step = 2) =>
```js
geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
geometricProgression(256, 3); //[3, 6, 12, 24, 48, 96, 192]
geometricProgression(256, 1, 4); //[1, 4, 16, 64, 256]
geometricProgression(256, 2, 1); //Gives error
geometricProgression(256, 3); // [3, 6, 12, 24, 48, 96, 192]
geometricProgression(256, 1, 4); // [1, 4, 16, 64, 256]
```

View File

@ -10,5 +10,5 @@ const getType = v =>
```
```js
getType(new Set([1, 2, 3])); // "set"
getType(new Set([1, 2, 3])); // 'Set'
```

View File

@ -13,7 +13,6 @@ const hasFlags = (...flags) =>
```js
// node myScript.js -s --test --cool=true
hasFlags('-s'); // true
hasFlags('test', 'cool=true'); // true
hasFlags('--test', 'cool=true', '-s'); // true
hasFlags('special'); // false
```

View File

@ -1,6 +1,6 @@
### howManyTimes
Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.
Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.
Works for both negative and positive integers.
If `divisor` is `-1` or `1` return `Infinity`.
@ -22,11 +22,8 @@ const howManyTimes = (num, divisor) => {
```
```js
howManyTimes(100, 2); //2
howManyTimes(100, -2); //2
howManyTimes(100, 2.5); //2
howManyTimes(100, 3); //0
howManyTimes(100, 0); //0
howManyTimes(100, 1); //Infinity
howManyTimes(100, -1); //Infinity
howManyTimes(100, 2); // 2
howManyTimes(100, 2.5); // 2
howManyTimes(100, 0); // 0
howManyTimes(100, -1); // Infinity
```

View File

@ -5,7 +5,7 @@ Initializes an array containing the numbers in the specified range where `start`
Use `Array(Math.ceil((end+1-start)/step)` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range.
You can omit `start` to use a default value of `0`.
You can omit `step` to use a default value of `1`.
```js
const initializeArrayWithRange = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start);
@ -14,5 +14,5 @@ const initializeArrayWithRange = (end, start = 0, step = 1) =>
```js
initializeArrayWithRange(5); // [0,1,2,3,4,5]
initializeArrayWithRange(7, 3); // [3,4,5,6,7]
initializeArrayWithRange(9, 0, 2); //[0,2,4,6,8]
initializeArrayWithRange(9, 0, 2); // [0,2,4,6,8]
```

View File

@ -13,6 +13,5 @@ const isArmstrongNumber = digits =>
```js
isArmstrongNumber(1634); // true
isArmstrongNumber(371); // true
isArmstrongNumber(56); // false
```

View File

@ -2,7 +2,7 @@
Returns `true` if the specified value is `null`, `false` otherwise.
Use the strict equality operator to check if the value and of `val` are equal to `null`.
Use the strict equality operator to check if the value and of `val` are equal to `null`.
```js
const isNull = val => val === null;
@ -10,5 +10,4 @@ const isNull = val => val === null;
```js
isNull(null); // true
isNull('null'); // false
```

View File

@ -11,4 +11,4 @@ const isNumber = val => typeof val === 'number';
```js
isNumber('1'); // false
isNumber(1); // true
```
```

View File

@ -15,5 +15,4 @@ const isPrime = num => {
```js
isPrime(11); // true
isPrime(12); // false
```

View File

@ -11,12 +11,10 @@ const isPrimitive = val => !['object', 'function'].includes(typeof val) || val =
```
```js
isPrimitive(window.someNonExistentProperty); // true
isPrimitive(null); // true
isPrimitive(50); // true
isPrimitive('Hello!'); // true
isPrimitive(false); // true
isPrimitive(Symbol()); // true
isPrimitive([]); // false
isPrimitive(new String('Hello!')); // false
```

View File

@ -16,7 +16,6 @@ const isSorted = arr => {
```
```js
isSorted([0, 1, 2, 3]); // 1
isSorted([0, 1, 2, 2]); // 1
isSorted([4, 3, 2]); // -1
isSorted([4, 3, 5]); // 0

View File

@ -9,6 +9,5 @@ const isString = val => typeof val === 'string';
```
```js
isString(10); // false
isString('10'); // true
```

View File

@ -9,6 +9,5 @@ const isSymbol = val => typeof val === 'symbol';
```
```js
isSymbol('x'); // false
isSymbol(Symbol('x')); // true
```

View File

@ -18,8 +18,7 @@ const join = (arr, separator = ',', end = separator) =>
```
```js
join(); // ''
join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); //"pen,pineapple,apple&pen"
join(['pen', 'pineapple', 'apple', 'pen'], ','); //"pen,pineapple,apple,pen"
join(['pen', 'pineapple', 'apple', 'pen']); //"pen,pineapple,apple,pen"
join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // "pen,pineapple,apple&pen"
join(['pen', 'pineapple', 'apple', 'pen'], ','); // "pen,pineapple,apple,pen"
join(['pen', 'pineapple', 'apple', 'pen']); // "pen,pineapple,apple,pen"
```

View File

@ -2,7 +2,7 @@
Replaces all but the last `num` of characters with the specified mask character.
Use `String.slice()` to grab the portion of the characters that need to be masked and use `String.replace()` with a regex to replace every character with the mask character.
Use `String.slice()` to grab the portion of the characters that need to be masked and use `String.replace()` with a regex to replace every character with the mask character.
Concatenate the masked characters with the remaining unmasked portion of the string.
Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string.
Omit the third argument, `mask`, to use a default character of `'*'` for the mask.
@ -15,6 +15,5 @@ const mask = (cc, num = 4, mask = '*') =>
```js
mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
mask(1234567890, 4, '$'); // '$$$$$$7890'
mask(1234567890, -4, '$'); // '1234$$$$$$'
```

View File

@ -2,7 +2,7 @@
Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in descending order).
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
Use `Array.slice()` to get the specified number of elements.
Omit the second argument, `n`, to get a one-element array.
@ -13,5 +13,4 @@ const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
```js
maxN([1, 2, 3]); // [3]
maxN([1, 2, 3], 2); // [3,2]
maxN([1, 2, 3], 4); // [3,2,1]
```

View File

@ -15,5 +15,4 @@ const median = arr => {
```js
median([5, 6, 50, 1, -5]); // 5
median([0, 10, -2, 7]); // 3.5
```

View File

@ -22,5 +22,5 @@ const memoize = fn => {
const anagramsCached = memoize(anagrams);
anagramsCached('javascript'); // takes a long time
anagramsCached('javascript'); // returns virtually instantly since it's now cached
console.log(anagramsCached.cache); // Map
console.log(anagramsCached.cache); // The cached anagrams map
```

View File

@ -12,5 +12,4 @@ const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
```js
minN([1, 2, 3]); // [1]
minN([1, 2, 3], 2); // [1,2]
minN([1, 2, 3], 4); // [1,2,3]
```

View File

@ -22,9 +22,8 @@ const orderBy = (arr, props, orders) =>
const users = [
{ name: 'fred', age: 48 },
{ name: 'barney', age: 36 },
{ name: 'fred', age: 40 },
{ name: 'barney', age: 34 }
{ name: 'fred', age: 40 }
];
orderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, {name: 'barney', age: 34}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
orderBy(users, ['name', 'age']); // [{name: 'barney', age: 34}, {name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
orderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
orderBy(users, ['name', 'age']); // [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
```

View File

@ -17,7 +17,6 @@ const pluralize = (val, word, plural = word + 's') => {
pluralize(0, 'apple'); // 'apples'
pluralize(1, 'apple'); // 'apple'
pluralize(2, 'apple'); // 'apples'
pluralize(1, 'person'); // 'person'
pluralize(2, 'person', 'people'); // 'people'
const PLURALS = {

View File

@ -2,8 +2,8 @@
Converts a number in bytes to a human-readable string.
Use an array dictionary of units to be accessed based on the exponent.
Use `Number.toPrecision()` to truncate the number to a certain number of digits.
Use an array dictionary of units to be accessed based on the exponent.
Use `Number.toPrecision()` to truncate the number to a certain number of digits.
Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not.
Omit the second argument, `precision`, to use a default precision of `3` digits.
Omit the third argument, `addSpace`, to add space between the number and unit by default.
@ -20,9 +20,6 @@ const prettyBytes = (num, precision = 3, addSpace = true) => {
```js
prettyBytes(1000); // 1 KB
prettyBytes(123456789); // 123 MB
prettyBytes(-50); // -50 B
prettyBytes(27145424323.5821); // 27.1 GB
prettyBytes(27145424323.5821, 5); // 27.145 GB
prettyBytes(5500, 3, false); // 5.5KB
prettyBytes(-27145424323.5821, 5); // -27.145 GB
prettyBytes(123456789, 3, false); // 123MB
```

View File

@ -17,11 +17,6 @@ const pull = (arr, ...args) => {
```
```js
let myArray1 = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray1, 'a', 'c');
console.log(myArray1); // [ 'b', 'b' ]
let myArray2 = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray2, ['a', 'c']);
console.log(myArray2); // [ 'b', 'b' ]
let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ]
```

View File

@ -20,8 +20,5 @@ const pullAtIndex = (arr, pullArr) => {
```js
let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtIndex(myArray, [1, 3]);
console.log(myArray); // [ 'a', 'c' ]
console.log(pulled); // [ 'b', 'd' ]
let pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
```

View File

@ -19,7 +19,5 @@ const pullAtValue = (arr, pullArr) => {
```js
let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtValue(myArray, ['b', 'd']);
console.log(myArray); // [ 'a', 'c' ]
console.log(pulled); // [ 'b', 'd' ]
let pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
```

View File

@ -13,6 +13,4 @@ const randomHexColorCode = () => {
```js
randomHexColorCode(); // "#e34155"
randomHexColorCode(); // "#fd73a6"
randomHexColorCode(); // "#4144c6"
```

View File

@ -2,8 +2,8 @@
Runs a function in a separate thread by using a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), allowing long running functions to not block the UI.
Create a new `Worker` using a `Blob` object URL, the contents of which should be the stringified version of the supplied function.
Immediately post the return value of calling the function back.
Create a new `Worker` using a `Blob` object URL, the contents of which should be the stringified version of the supplied function.
Immediately post the return value of calling the function back.
Return a promise, listening for `onmessage` and `onerror` events and resolving the data posted back from the worker, or throwing an error.
```js
@ -37,10 +37,11 @@ const longRunningFunction = () => {
}
return result;
};
// NOTE: Since the function is running in a different context, closures are not supported.
// The function supplied to `runAsync` gets stringified, so everything becomes literal.
// All variables and functions must be defined inside.
/*
NOTE: Since the function is running in a different context, closures are not supported.
The function supplied to `runAsync` gets stringified, so everything becomes literal.
All variables and functions must be defined inside.
*/
runAsync(longRunningFunction).then(console.log); // 209685000000
runAsync(() => 10 ** 3).then(console.log); // 1000
let outsideVariable = 50;

View File

@ -10,5 +10,5 @@ const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.r
```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
runPromisesInSeries([() => delay(1000), () => delay(2000)]); // Executes each promise sequentially, taking a total of 3 seconds to complete
```

View File

@ -17,5 +17,4 @@ const sdbm = str => {
```js
console.log(sdbm('name')); // -3521204949
console.log(sdbm('age')); // 808122783
```

View File

@ -10,6 +10,5 @@ const shallowClone = obj => Object.assign({}, obj);
```js
const a = { x: true, y: 1 };
const b = shallowClone(a);
a === b; // false
const b = shallowClone(a); // a !== b
```

View File

@ -17,6 +17,5 @@ const shuffle = ([...arr]) => {
```js
const foo = [1, 2, 3];
shuffle(foo); // [2,3,1]
console.log(foo); // [1,2,3]
shuffle(foo); // [2,3,1], foo = [1,2,3]
```

View File

@ -41,8 +41,5 @@ const solveRPN = rpn => {
```js
solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
solveRPN('3 5 6 + *'); //33
solveRPN('2 4 / 5 6 - *'); //-0.5
solveRPN('2 3 ^'); //8
solveRPN('2 3 ^'); //8
solveRPN('2 3 ^'); // 8
```

View File

@ -11,5 +11,4 @@ const spreadOver = fn => argsArr => fn(...argsArr);
```js
const arrayMax = spreadOver(Math.max);
arrayMax([1, 2, 3]); // 3
arrayMax([1, 2, 4]); // 4
```

View File

@ -14,6 +14,5 @@ const timeTaken = callback => {
```
```js
timeTaken(() => Math.pow(2, 10)); // 1024
// (logged): timeTaken: 0.02099609375ms
timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
```

View File

@ -17,7 +17,6 @@ const toSnakeCase = str =>
```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

@ -4,7 +4,7 @@ Checks if the predicate (second argument) is truthy on all elements of a collect
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]);
```

View File

@ -18,6 +18,7 @@ const unescapeHTML = str =>
}[tag] || tag)
);
```
```js
unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'
```