This commit is contained in:
Angelos Chalaris
2017-12-27 11:02:46 +02:00
parent 0d9b02a3cb
commit b74eb9d9bd
45 changed files with 89 additions and 91 deletions

View File

@ -7,7 +7,7 @@ Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).
```js ```js
const JSONToDate = arr => { const JSONToDate = arr => {
const dt = new Date(parseInt(arr.toString().substr(6))); const dt = new Date(parseInt(arr.toString().substr(6)));
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }` return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
}; };
// JSONToDate(/Date(1489525200000)/) -> "14/3/2017" // JSONToDate(/Date(1489525200000)/) -> "14/3/2017"
``` ```

View File

@ -6,6 +6,6 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json`
```js ```js
const fs = require('fs'); const fs = require('fs');
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
// JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json' // JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
``` ```

View File

@ -8,7 +8,7 @@ Use `Array.reduce()` and the `gcd` formula (uses recursion) to calculate the gre
const arrayGcd = arr => { const arrayGcd = arr => {
const gcd = (x, y) => !y ? x : gcd(y, x % y); const gcd = (x, y) => !y ? x : gcd(y, x % y);
return arr.reduce((a, b) => gcd(a, b)); return arr.reduce((a, b) => gcd(a, b));
} };
// arrayGcd([1,2,3,4,5]) -> 1 // arrayGcd([1,2,3,4,5]) -> 1
// arrayGcd([4,8,12]) -> 4 // arrayGcd([4,8,12]) -> 4
``` ```

View File

@ -9,7 +9,7 @@ const arrayLcm = arr =>{
const gcd = (x, y) => !y ? x : gcd(y, x % y); const gcd = (x, y) => !y ? x : gcd(y, x % y);
const lcm = (x, y) => (x * y) / gcd(x, y); const lcm = (x, y) => (x * y) / gcd(x, y);
return arr.reduce((a, b) => lcm(a, b)); return arr.reduce((a, b) => lcm(a, b));
} };
// arrayLcm([1,2,3,4,5]) -> 60 // arrayLcm([1,2,3,4,5]) -> 60
// arrayLcm([4,8,12]) -> 24 // arrayLcm([4,8,12]) -> 24
``` ```

View File

@ -5,6 +5,6 @@ Converts the given array elements into `<li>` tags and appends them to the list
Use `Array.map()` and `document.querySelector()` to create a list of html tags. Use `Array.map()` and `document.querySelector()` to create a list of html tags.
```js ```js
const arrayToHtmlList = (arr, listID) => arr.map(item => document.querySelector("#"+listID).innerHTML+=`<li>${item}</li>`); const arrayToHtmlList = (arr, listID) => arr.map(item => document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`);
// arrayToHtmlList(['item 1', 'item 2'],'myListID') // arrayToHtmlList(['item 1', 'item 2'],'myListID')
``` ```

View File

@ -9,8 +9,8 @@ Otherwise, return the nearest number in the range.
```js ```js
const clampNumber = (num, lower, upper) => { const clampNumber = (num, lower, upper) => {
if (lower > upper) upper = [lower, lower = upper][0]; if (lower > upper) upper = [lower, lower = upper][0];
return (num>=lower && num<=upper) ? num : ((num < lower) ? lower : upper) return (num >= lower && num <= upper) ? num : ((num < lower) ? lower : upper);
} };
// clampNumber(2, 3, 5) -> 3 // clampNumber(2, 3, 5) -> 3
// clampNumber(1, -1, -5) -> -1 // clampNumber(1, -1, -5) -> -1
// clampNumber(3, 2, 4) -> 3 // clampNumber(3, 2, 4) -> 3

View File

@ -15,7 +15,7 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => {
} }
 });  });
return obj; return obj;
} };
/* /*
const testObj = {a: 1, b: 2, children: {a: 1, b: 2}} const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
cleanObj(testObj, ["a"],"children") // { a: 1, children : { a: 1}} cleanObj(testObj, ["a"],"children") // { a: 1, children : { a: 1}}

View File

@ -5,6 +5,6 @@ Returns the first non-null/undefined argument.
Use `Array.find()` to return the first non `null`/`undefined` argument. Use `Array.find()` to return the first non `null`/`undefined` argument.
```js ```js
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)) const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
// coalesce(null,undefined,"",NaN, "Waldo") -> "" // coalesce(null,undefined,"",NaN, "Waldo") -> ""
``` ```

View File

@ -5,7 +5,7 @@ Detects wether the website is being opened in a mobile device or a desktop/lapto
Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop. Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop.
```js ```js
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop"; const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
// detectDeviceType() -> "Mobile" // detectDeviceType() -> "Mobile"
// detectDeviceType() -> "Desktop" // detectDeviceType() -> "Desktop"
``` ```

View File

@ -5,6 +5,6 @@ Filters out all values from an array for which the comparator function does not
Use `Array.filter()` and `Array.find()` to find the appropriate values. Use `Array.filter()` and `Array.find()` to find the appropriate values.
```js ```js
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))) const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)));
// differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2] // differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2]
``` ```

View File

@ -6,7 +6,7 @@ Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for con
`String.slice()` is used to remove `#` from string start since it's added once. `String.slice()` is used to remove `#` from string start since it's added once.
```js ```js
const extendHex = shortHex => const extendHex = shortHex =>
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('') '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x + x).join('');
// extendHex('#03f') -> '#0033ff' // extendHex('#03f') -> '#0033ff'
// extendHex('05a') -> '#0055aa' // extendHex('05a') -> '#0055aa'
``` ```

View File

@ -9,7 +9,7 @@ Throws an exception if `n` is a negative number.
```js ```js
const factorial = n => const factorial = n =>
n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!') })() n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!'); })()
: n <= 1 ? 1 : n * factorial(n - 1); : n <= 1 ? 1 : n * factorial(n - 1);
// factorial(6) -> 720 // factorial(6) -> 720
``` ```

View File

@ -10,6 +10,6 @@ Uses a mathematical formula to calculate the length of the array required.
const fibonacciUntilNum = num => { const fibonacciUntilNum = num => {
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
return Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []); return Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
} };
// fibonacciUntilNum(15) -> [0,1,1,2,3,5,8,13] // fibonacciUntilNum(15) -> [0,1,1,2,3,5,8,13]
``` ```

View File

@ -5,7 +5,7 @@ Flip takes a function as an argument, then makes the first argument the last
Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.
```js ```js
const flip = fn => (...args) => fn(args.pop(), ...args) const flip = fn => (...args) => fn(args.pop(), ...args);
/* /*
let a = {name: 'John Smith'} let a = {name: 'John Smith'}
let b = {} let b = {}

View File

@ -10,14 +10,13 @@ const hexToRGB = hex => {
if (h.length === 3) h = [...h].map(x => x + x).join(''); if (h.length === 3) h = [...h].map(x => x + x).join('');
else if (h.length === 8) alpha = true; else if (h.length === 8) alpha = true;
h = parseInt(h, 16); h = parseInt(h, 16);
return 'rgb' + (alpha ? 'a' : '') + '(' return 'rgb' + (alpha ? 'a' : '') + '(' +
+ (h >>> (alpha ? 24 : 16)) + ', ' (h >>> (alpha ? 24 : 16)) + ', ' +
+ ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + ', ' ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + ', ' +
+ ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
+ (alpha ? `, ${(h & 0x000000ff)}` : '') + ')'; (alpha ? `, ${(h & 0x000000ff)}` : '') + ')';
}; };
// hexToRGB('#27ae60ff') -> 'rgba(39, 174, 96, 255)' // hexToRGB('#27ae60ff') -> 'rgba(39, 174, 96, 255)'
// hexToRGB('27ae60') -> 'rgb(39, 174, 96)' // hexToRGB('27ae60') -> 'rgb(39, 174, 96)'
// hexToRGB('#fff') -> 'rgb(255, 255, 255)' // hexToRGB('#fff') -> 'rgb(255, 255, 255)'
``` ```

View File

@ -6,6 +6,6 @@ Use `location.protocol` to get the protocol currently being used. If it's not HT
```js ```js
const httpsRedirect = () => { const httpsRedirect = () => {
if(location.protocol !== "https:") location.replace("https://" + location.href.split("//")[1]); if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
} };
``` ```

View File

@ -9,7 +9,7 @@ If the second parameter, `end`, is not specified, the range is considered to be
const inRange = (n, start, end = null) => { const inRange = (n, start, end = null) => {
if (end && start > end) end = [start, start = end][0]; if (end && start > end) end = [start, start = end][0];
return (end == null) ? (n >= 0 && n < start) : (n >= start && n < end); return (end == null) ? (n >= 0 && n < start) : (n >= start && n < end);
} };
// inRange(3, 2, 5) -> true // inRange(3, 2, 5) -> true
// inRange(3, 4) -> true // inRange(3, 4) -> true
// inRange(2, 3, 5) -> false // inRange(2, 3, 5) -> false

View File

@ -6,7 +6,7 @@ Convert the given number into an array of digits. Use `Math.pow()` to get the ap
```js ```js
const isArmstrongNumber = digits => const isArmstrongNumber = digits =>
( arr => arr.reduce( ( a, d ) => a + Math.pow( parseInt( d ), arr.length ), 0 ) == digits ? true : false )( ( digits+'' ).split( '' ) ); (arr => arr.reduce((a, d) => a + Math.pow(parseInt(d), arr.length), 0) == digits)((digits + '').split(''));
// isArmstrongNumber(1634) -> true // isArmstrongNumber(1634) -> true
// isArmstrongNumber(371) -> true // isArmstrongNumber(371) -> true
// isArmstrongNumber(56) -> false // isArmstrongNumber(56) -> false

View File

@ -11,6 +11,6 @@ const primes = num => {
numsTillSqroot = Array.from({length: sqroot - 1}).map((x, i) => i + 2); numsTillSqroot = Array.from({length: sqroot - 1}).map((x, i) => i + 2);
numsTillSqroot.forEach(x => arr = arr.filter(y => ((y % x) !== 0) || (y == x))); numsTillSqroot.forEach(x => arr = arr.filter(y => ((y % x) !== 0) || (y == x)));
return arr; return arr;
} };
// primes(10) -> [2,3,5,7] // primes(10) -> [2,3,5,7]
``` ```

View File

@ -10,11 +10,11 @@ Use `Array.push()` to keep track of pulled values
const pullAtIndex = (arr, pullArr) => { const pullAtIndex = (arr, pullArr) => {
let removed = []; let removed = [];
let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v) let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v)
.filter((v, i) => !pullArr.includes(i)) .filter((v, i) => !pullArr.includes(i));
arr.length = 0; arr.length = 0;
pulled.forEach(v => arr.push(v)); pulled.forEach(v => arr.push(v));
return removed; return removed;
} };
// let myArray = ['a', 'b', 'c', 'd']; // let myArray = ['a', 'b', 'c', 'd'];
// let pulled = pullAtIndex(myArray, [1, 3]); // let pulled = pullAtIndex(myArray, [1, 3]);

View File

@ -14,7 +14,7 @@ const pullAtValue = (arr, pullArr) => {
arr.length = 0; arr.length = 0;
mutateTo.forEach(v => arr.push(v)); mutateTo.forEach(v => arr.push(v));
return removed; return removed;
} };
/* /*
let myArray = ['a', 'b', 'c', 'd']; let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtValue(myArray, ['b', 'd']); let pulled = pullAtValue(myArray, ['b', 'd']);

View File

@ -9,7 +9,7 @@ const randomHexColor = () => {
let n = (Math.random() * 0xfffff | 0).toString(16); let n = (Math.random() * 0xfffff | 0).toString(16);
return '#' + (n.length !== 6 return '#' + (n.length !== 6
? (Math.random() * 0xf | 0).toString(16) + n : n); ? (Math.random() * 0xf | 0).toString(16) + n : n);
} };
// randomHexColorCode() -> "#e34155" // randomHexColorCode() -> "#e34155"
// randomHexColorCode() -> "#fd73a6" // randomHexColorCode() -> "#fd73a6"
// randomHexColorCode() -> "#4144c6" // randomHexColorCode() -> "#4144c6"

View File

@ -5,9 +5,9 @@ Repeats a string n times using `String.repeat()`
If no string is provided the default is `""` and the default number of times is 2. If no string is provided the default is `""` and the default number of times is 2.
```js ```js
const repeatString = (str="",num=2) => { const repeatString = (str = '', num = 2) => {
return num >= 0 ? str.repeat(num) : str; return num >= 0 ? str.repeat(num) : str;
} };
// repeatString("abc",3) -> 'abcabcabc' // repeatString("abc",3) -> 'abcabcabc'
// repeatString("abc") -> 'abcabc' // repeatString("abc") -> 'abcabc'
``` ```

View File

@ -8,6 +8,6 @@ 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] // symmetricDifference([1,2,3], [1,2,4]) -> [3,4]
``` ```

View File

@ -10,8 +10,8 @@ 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_database_field_name") -> 'someDatabaseFieldName'
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' // toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty' // toCamelCase("some-javascript-property") -> 'someJavascriptProperty'

View File

@ -3,6 +3,6 @@
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" // toDecimalMark(12305030388.9087) -> "12,305,030,388.9087"
``` ```

View File

@ -6,7 +6,6 @@ Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from Am
Throws an error if the passed time cannot be converted to a date. Throws an error if the passed time cannot be converted to a date.
```js ```js
const toEnglishDate = (time) => const toEnglishDate = (time) => { try { return new Date(time).toISOString().split('T')[0].replace(/-/g, '/'); } catch (e) {} };
{try{return new Date(time).toISOString().split('T')[0].replace(/-/g, '/')}catch(e){return}};
// toEnglishDate('09/21/2010') -> '21/09/2010' // toEnglishDate('09/21/2010') -> '21/09/2010'
``` ```

View File

@ -10,7 +10,7 @@ const toSnakeCase = 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('_');
} };
// toSnakeCase("camelCase") -> 'camel_case' // toSnakeCase("camelCase") -> 'camel_case'
// toSnakeCase("some text") -> 'some_text' // toSnakeCase("some text") -> 'some_text'
// toSnakeCase("some-javascript-property") -> 'some_javascript_property' // toSnakeCase("some-javascript-property") -> 'some_javascript_property'

View File

@ -11,8 +11,8 @@ 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', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]]
// zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] // zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]]
``` ```

View File

@ -5,7 +5,7 @@ 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','c'], [1,2]) -> {a: 1, b: 2, c: undefined}
// zipObject(['a','b'], [1,2,3]) -> {a: 1, b: 2} // zipObject(['a','b'], [1,2,3]) -> {a: 1, b: 2}
``` ```