Merge remote-tracking branch 'origin/snippet-restructuring' into snippet-restructuring

This commit is contained in:
Stefan Feješ
2017-12-27 16:20:18 +01:00
35 changed files with 58 additions and 53 deletions

View File

@ -28,7 +28,7 @@ Here's what you can do to help:
- Use ES6 notation to define your function. For example `const myFunction = ( arg1, arg2 ) => { }`.
- Please use Javacript [Semi-Standard Style](https://github.com/Flet/semistandard).
- Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting.
- All snippets must be followed by one (more if necessary) test case after the code, on a new line, in the form of a comment, along with the expected output. The syntax for this is `myFunction('testInput') -> 'testOutput'`. Use multiline comments only if necessary.
- All snippets must be followed by one (more if necessary) test case after the code, in a new block enclosed inside ` ```js ` and ` ``` `. The syntax for this is `myFunction('testInput') // 'testOutput'`. Use multiline examples only if necessary.
- Try to make your function name unique, so that it does not conflict with existing snippets.
- Snippet functions do not have to handle errors in input, unless it's necessary (e.g. a mathematical function that cannot be extended to negative numbers should handle negative input appropriately).
- Snippets should be short (usually below 10 lines). If your snippet is longer than that, you can still submit it, and we can help you shorten it or figure out ways to improve it.

View File

@ -25,7 +25,8 @@ try {
console.time(`Linter (${snippet})`);
// Synchronously read data from the snippet, get the code, write it to a temporary file
let snippetData = fs.readFileSync(path.join(snippetsPath,snippet),'utf8');
let originalCode = snippetData.slice(snippetData.indexOf('```js')+5,snippetData.lastIndexOf('```'));
let codeStart = snippetData.indexOf('```js'), codeEnd = snippetData.search(/```[\n\r\s]+```js/g);
let originalCode = snippetData.slice(codeStart+5,codeEnd);
while(jobCounter >= 20){
setTimeout(()=>{},1000);
}
@ -36,7 +37,7 @@ try {
cp.exec(`semistandard "${tempSnippet}.temp.js" --fix`,{},(error, stdOut, stdErr) => {
jobCounter += 1;
let lintedCode = fs.readFileSync(`${tempSnippet}.temp.js`,'utf8');
fs.writeFile(path.join(snippetsPath,snippet), `${snippetData.slice(0, snippetData.indexOf('```js')+5)+lintedCode+'```\n'}`);
fs.writeFile(path.join(snippetsPath,snippet), `${snippetData.slice(0, codeStart+5)+lintedCode+snippetData.slice(codeEnd)}`);
fs.unlink(`${tempSnippet}.temp.js`);
// Log a success message
console.log(`${chalk.green('SUCCESS!')} Linted snippet: ${snippet}`);

View File

@ -10,5 +10,5 @@ const functionName = arguments =>
```
```js
functionName()
functionName('sampleInput') // 'sampleOutput'
```

View File

@ -6,7 +6,7 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json`
```js
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));
```
```js

View File

@ -8,7 +8,7 @@ Use `Array.reduce()` and the `gcd` formula (uses recursion) to calculate the gre
const arrayGcd = arr => {
const gcd = (x, y) => !y ? x : gcd(y, x % y);
return arr.reduce((a, b) => gcd(a, b));
}
};
```
```js

View File

@ -9,7 +9,7 @@ const arrayLcm = arr => {
const gcd = (x, y) => !y ? x : gcd(y, x % y);
const lcm = (x, y) => (x * y) / gcd(x, y);
return arr.reduce((a, b) => lcm(a, b));
}
};
```
```js

View File

@ -5,7 +5,7 @@ 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.
```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>`);
```
```js

View File

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

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.
```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';
```
```js

View File

@ -5,7 +5,7 @@ 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.
```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)));
```
```js

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.
```js
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('');
```
```js

View File

@ -10,7 +10,7 @@ Uses a mathematical formula to calculate the length of the array required.
const fibonacciUntilNum = num => {
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), []);
}
};
```
```js

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) => {
if (end && start > end) end = [start, start = end][0];
return (end == null) ? (n >= 0 && n < start) : (n >= start && n < end);
}
};
```
```js

View File

@ -6,7 +6,7 @@ Convert the given number into an array of digits. Use `Math.pow()` to get the ap
```js
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(''));
```
```js

View File

@ -9,7 +9,7 @@ Then, `split('')` into individual characters, `reverse()`, `join('')` and compar
const palindrome = str => {
const s = str.toLowerCase().replace(/[\W_]/g, '');
return s === s.split('').reverse().join('');
}
};
```
```js

View File

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

View File

@ -10,11 +10,11 @@ Use `Array.push()` to keep track of pulled values
const pullAtIndex = (arr, pullArr) => {
let removed = [];
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;
pulled.forEach(v => arr.push(v));
return removed;
}
};
```
```js

View File

@ -14,7 +14,7 @@ const pullAtValue = (arr, pullArr) => {
arr.length = 0;
mutateTo.forEach(v => arr.push(v));
return removed;
}
};
```
```js

View File

@ -5,8 +5,12 @@ Generates a random hexadecimal color code.
Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using `toString(16)`.
```js
<<<<<<< HEAD
const randomHexColorCode = () => '#'+(Math.random()*0xFFFFFF<<0).toString(16);
};
=======
const randomHexColorCode = () => '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
>>>>>>> snippet-restructuring
```
```js

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.
```js
const repeatString = (str="",num=2) => {
const repeatString = (str = '', num = 2) => {
return num >= 0 ? str.repeat(num) : str;
}
};
```
```js

View File

@ -8,7 +8,7 @@ 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))];
}
};
```
```js

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)
.map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
.join('');
return s.slice(0,1).toLowerCase() + s.slice(1)
}
return s.slice(0, 1).toLowerCase() + s.slice(1);
};
```
```js

View File

@ -3,7 +3,7 @@
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");
const toDecimalMark = num => num.toLocaleString('en-US');
```
```js

View File

@ -11,8 +11,8 @@ 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]);
})
}
});
};
```
```js

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()`.
```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), {});
```
```js