1
.gitignore
vendored
1
.gitignore
vendored
@ -3,3 +3,4 @@ currentSnippet\.js
|
||||
*.md.temp.js
|
||||
.idea
|
||||
test.sh
|
||||
dist/
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
#!/bin/sh
|
||||
|
||||
setup_git() {
|
||||
git config --global user.email "david10608@gmail.com"
|
||||
git config --global user.name "Pl4gue"
|
||||
git config --global user.email "travis@travis-ci.org"
|
||||
git config --global user.name "Travis CI"
|
||||
}
|
||||
|
||||
commit_website_files() {
|
||||
|
||||
346
README.md
346
README.md
@ -1,6 +1,8 @@
|
||||

|
||||
|
||||
# 30 seconds of code [](https://gitter.im/30-seconds-of-code/Lobby) [](https://travis-ci.org/Chalarangelo/30-seconds-of-code)
|
||||
# 30 seconds of code
|
||||
[](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [](https://gitter.im/30-seconds-of-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [](https://github.com/Flet/semistandard)
|
||||
|
||||
> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less.
|
||||
|
||||
|
||||
@ -11,6 +13,13 @@
|
||||
|
||||
## Table of Contents
|
||||
|
||||
### Adapter
|
||||
* [`call`](#call)
|
||||
* [`collectInto`](#collectinto)
|
||||
* [`flip`](#flip)
|
||||
* [`promisify`](#promisify)
|
||||
* [`spreadOver`](#spreadover)
|
||||
|
||||
### Array
|
||||
* [`arrayGcd`](#arraygcd)
|
||||
* [`arrayLcm`](#arraylcm)
|
||||
@ -78,7 +87,6 @@
|
||||
* [`curry`](#curry)
|
||||
* [`functionName`](#functionname)
|
||||
* [`pipe`](#pipe)
|
||||
* [`promisify`](#promisify)
|
||||
* [`runPromisesInSeries`](#runpromisesinseries)
|
||||
* [`sleep`](#sleep)
|
||||
|
||||
@ -91,6 +99,8 @@
|
||||
* [`distance`](#distance)
|
||||
* [`factorial`](#factorial)
|
||||
* [`fibonacci`](#fibonacci)
|
||||
* [`fibonacciCountUntilNum`](#fibonaccicountuntilnum)
|
||||
* [`fibonacciUntilNum`](#fibonacciuntilnum)
|
||||
* [`gcd`](#gcd)
|
||||
* [`hammingDistance`](#hammingdistance)
|
||||
* [`inRange`](#inrange)
|
||||
@ -132,9 +142,12 @@
|
||||
* [`countVowels`](#countvowels)
|
||||
* [`escapeRegExp`](#escaperegexp)
|
||||
* [`fromCamelCase`](#fromcamelcase)
|
||||
* [`repeatString`](#repeatstring)
|
||||
* [`reverseString`](#reversestring)
|
||||
* [`sortCharactersInString`](#sortcharactersinstring)
|
||||
* [`toCamelCase`](#tocamelcase)
|
||||
* [`toKebabCase`](#tokebabcase)
|
||||
* [`toSnakeCase`](#tosnakecase)
|
||||
* [`truncateString`](#truncatestring)
|
||||
* [`words`](#words)
|
||||
|
||||
@ -157,6 +170,107 @@
|
||||
* [`UUIDGenerator`](#uuidgenerator)
|
||||
* [`validateNumber`](#validatenumber)
|
||||
|
||||
### _Uncategorized_
|
||||
* [`detectDeviceType`](#detectdevicetype)
|
||||
* [`negate`](#negate)
|
||||
|
||||
## Adapter
|
||||
|
||||
### call
|
||||
|
||||
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
|
||||
|
||||
Use a closure to call a stored key with stored arguments.
|
||||
|
||||
```js
|
||||
const call = ( key, ...args ) => context => context[ key ]( ...args );
|
||||
/*
|
||||
Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
||||
const map = call.bind(null, 'map')
|
||||
Promise.resolve( [ 1, 2, 3 ] ).then( map( x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
||||
*/
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### collectInto
|
||||
|
||||
Changes a function that accepts an array into a variadic function.
|
||||
|
||||
Given a function, return a closure that collects all inputs into an array-accepting function.
|
||||
|
||||
```js
|
||||
const collectInto = fn => ( ...args ) => fn( args );
|
||||
/*
|
||||
const Pall = collectInto( Promise.all.bind(Promise) )
|
||||
let p1 = Promise.resolve(1)
|
||||
let p2 = Promise.resolve(2)
|
||||
let p3 = new Promise((resolve) => setTimeout(resolve,2000,3))
|
||||
Pall(p1, p2, p3).then(console.log)
|
||||
*/
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### flip
|
||||
|
||||
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.
|
||||
|
||||
```js
|
||||
const flip = fn => (...args) => fn(args.pop(), ...args)
|
||||
/*
|
||||
let a = {name: 'John Smith'}
|
||||
let b = {}
|
||||
const mergeFrom = flip(Object.assign)
|
||||
let mergePerson = mergeFrom.bind(a)
|
||||
mergePerson(b) // == b
|
||||
b = {}
|
||||
Object.assign(b, a) // == b
|
||||
*/
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### promisify
|
||||
|
||||
Converts an asynchronous function to return a promise.
|
||||
|
||||
Use currying to return a function returning a `Promise` that calls the original function.
|
||||
Use the `...rest` operator to pass in all the parameters.
|
||||
|
||||
*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
|
||||
|
||||
```js
|
||||
const promisify = func =>
|
||||
(...args) =>
|
||||
new Promise((resolve, reject) =>
|
||||
func(...args, (err, result) =>
|
||||
err ? reject(err) : resolve(result))
|
||||
);
|
||||
// const delay = promisify((d, cb) => setTimeout(cb, d))
|
||||
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### spreadOver
|
||||
|
||||
Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
|
||||
|
||||
Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function.
|
||||
|
||||
```js
|
||||
const spreadOver = fn => argsArr => fn(...argsArr);
|
||||
/*
|
||||
const arrayMax = spreadOver(Math.max)
|
||||
arrayMax([1,2,3]) // -> 3
|
||||
arrayMax([1,2,4]) // -> 4
|
||||
*/
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
## Array
|
||||
|
||||
### arrayGcd
|
||||
@ -178,14 +292,14 @@ const arrayGcd = arr =>{
|
||||
|
||||
### arrayLcm
|
||||
|
||||
Calculates the lowest common multiple (lcm) of an array of numbers.
|
||||
Calculates the lowest common multiple (lcm) of an array of numbers.
|
||||
|
||||
Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers.
|
||||
Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers.
|
||||
|
||||
```js
|
||||
const arrayLcm = arr =>{
|
||||
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));
|
||||
}
|
||||
// arrayLcm([1,2,3,4,5]) -> 60
|
||||
@ -378,10 +492,10 @@ const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexO
|
||||
|
||||
Flattens an array.
|
||||
|
||||
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
|
||||
Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.
|
||||
|
||||
```js
|
||||
const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
|
||||
const flatten = arr => [ ].concat( ...arr );
|
||||
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
||||
```
|
||||
|
||||
@ -407,7 +521,7 @@ const flattenDepth = (arr, depth = 1) =>
|
||||
|
||||
### groupBy
|
||||
|
||||
Groups the element of an array based on the given function.
|
||||
Groups the elements of an array based on the given function.
|
||||
|
||||
Use `Array.map()` to map the values of an array to a function or property name.
|
||||
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.
|
||||
@ -439,7 +553,7 @@ const head = arr => arr[0];
|
||||
|
||||
Returns all the elements of an array except the last one.
|
||||
|
||||
Use `arr.slice(0,-1)`to return all but the last element of the array.
|
||||
Use `arr.slice(0,-1)` to return all but the last element of the array.
|
||||
|
||||
```js
|
||||
const initial = arr => arr.slice(0, -1);
|
||||
@ -450,9 +564,9 @@ const initial = arr => arr.slice(0, -1);
|
||||
|
||||
### initialize2DArray
|
||||
|
||||
Initializes an 2D array of given width and height and value.
|
||||
Initializes a 2D array of given width and height and value.
|
||||
|
||||
Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If value is not provided, default to `null`.
|
||||
Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
|
||||
|
||||
```js
|
||||
const initialize2DArray = (w, h, val = null) => Array(h).fill().map(() => Array(w).fill(val));
|
||||
@ -508,7 +622,7 @@ const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.ha
|
||||
|
||||
Returns the last element in an array.
|
||||
|
||||
Use `arr.length - 1` to compute index of the last element of the given array and returning it.
|
||||
Use `arr.length - 1` to compute the index of the last element of the given array and returning it.
|
||||
|
||||
```js
|
||||
const last = arr => arr[arr.length - 1];
|
||||
@ -521,7 +635,7 @@ const last = arr => arr[arr.length - 1];
|
||||
|
||||
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
|
||||
|
||||
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to stor the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
|
||||
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
|
||||
|
||||
```js
|
||||
const mapObject = (arr, fn) =>
|
||||
@ -554,7 +668,7 @@ const nthElement = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0];
|
||||
|
||||
Picks the key-value pairs corresponding to the given keys from an object.
|
||||
|
||||
Use `Array.reduce()` to convert the filtered/picked keys back to a object with the corresponding key-value pair if the key exist in the obj.
|
||||
Use `Array.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.
|
||||
|
||||
```js
|
||||
const pick = (obj, arr) =>
|
||||
@ -569,7 +683,7 @@ const pick = (obj, arr) =>
|
||||
Mutates the original array to filter out the values specified.
|
||||
|
||||
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
|
||||
Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
|
||||
_(For a snippet that does not mutate the original array see [`without`](#without))_
|
||||
|
||||
@ -597,7 +711,7 @@ const pull = (arr, ...args) => {
|
||||
Mutates the original array to filter out the values at the specified indexes.
|
||||
|
||||
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
|
||||
Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.push()` to keep track of pulled values
|
||||
|
||||
```js
|
||||
@ -624,7 +738,7 @@ const pullAtIndex = (arr, pullArr) => {
|
||||
Mutates the original array to filter out the values specified. Returns the removed elements.
|
||||
|
||||
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
|
||||
Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.push()` to keep track of pulled values
|
||||
|
||||
```js
|
||||
@ -668,7 +782,7 @@ const remove = (arr, func) =>
|
||||
|
||||
Returns a random element from an array.
|
||||
|
||||
Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`.
|
||||
Use `Math.random()` to generate a random number, multiply it by `length` and round it of to the nearest whole number using `Math.floor()`.
|
||||
This method also works with strings.
|
||||
|
||||
```js
|
||||
@ -724,7 +838,7 @@ const symmetricDifference = (a, b) => {
|
||||
|
||||
Returns all elements in an array except for the first one.
|
||||
|
||||
Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise return the whole array.
|
||||
Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array.
|
||||
|
||||
```js
|
||||
const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
|
||||
@ -878,6 +992,7 @@ it is partially visible.
|
||||
```js
|
||||
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
|
||||
const { top, left, bottom, right } = el.getBoundingClientRect();
|
||||
const { innerHeight, innerWidth } = window;
|
||||
return partiallyVisible
|
||||
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
|
||||
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
|
||||
@ -957,7 +1072,7 @@ const redirect = (url, asLink = true) =>
|
||||
Smooth-scrolls to the top of the page.
|
||||
|
||||
Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`.
|
||||
Scroll by a fraction of the distance from top. Use `window.requestAnimationFrame()` to animate the scrolling.
|
||||
Scroll by a fraction of the distance from the top. Use `window.requestAnimationFrame()` to animate the scrolling.
|
||||
|
||||
```js
|
||||
const scrollToTop = () => {
|
||||
@ -977,7 +1092,7 @@ const scrollToTop = () => {
|
||||
|
||||
Returns the difference (in days) between two dates.
|
||||
|
||||
Calculate the difference (in days) between to `Date` objects.
|
||||
Calculate the difference (in days) between two `Date` objects.
|
||||
|
||||
```js
|
||||
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
|
||||
@ -1006,7 +1121,7 @@ const JSONToDate = arr => {
|
||||
|
||||
Converts a date from American format to English format.
|
||||
|
||||
Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from American format to English format.
|
||||
Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from American format to the English format.
|
||||
Throws an error if the passed time cannot be converted to a date.
|
||||
|
||||
```js
|
||||
@ -1062,7 +1177,7 @@ Curries a function.
|
||||
|
||||
Use recursion.
|
||||
If the number of provided arguments (`args`) is sufficient, call the passed function `f`.
|
||||
Otherwise return a curried function `f` that expects the rest of the arguments.
|
||||
Otherwise, return a curried function `f` that expects the rest of the arguments.
|
||||
If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`.
|
||||
|
||||
```js
|
||||
@ -1108,28 +1223,6 @@ multiplyAndAdd5(5, 2) -> 15
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### promisify
|
||||
|
||||
Converts an asynchronous function to return a promise.
|
||||
|
||||
Use currying to return a function returning a `Promise` that calls the original function.
|
||||
Use the `...rest` operator to pass in all the parameters.
|
||||
|
||||
*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
|
||||
|
||||
```js
|
||||
const promisify = func =>
|
||||
(...args) =>
|
||||
new Promise((resolve, reject) =>
|
||||
func(...args, (err, result) =>
|
||||
err ? reject(err) : resolve(result))
|
||||
);
|
||||
// const delay = promisify((d, cb) => setTimeout(cb, d))
|
||||
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### runPromisesInSeries
|
||||
|
||||
Runs an array of promises in series.
|
||||
@ -1196,7 +1289,7 @@ Clamps `num` within the inclusive `lower` and `upper` bounds.
|
||||
|
||||
If `lower` is greater than `upper`, swap them.
|
||||
If `num` falls within the range, return `num`.
|
||||
Otherwise return the nearest number in the range.
|
||||
Otherwise, return the nearest number in the range.
|
||||
|
||||
```js
|
||||
const clampNumber = (num, lower, upper) => {
|
||||
@ -1214,7 +1307,7 @@ const clampNumber = (num, lower, upper) => {
|
||||
|
||||
Applies the Collatz algorithm.
|
||||
|
||||
If `n` is even, return `n/2`. Otherwise return `3n+1`.
|
||||
If `n` is even, return `n/2`. Otherwise, return `3n+1`.
|
||||
|
||||
```js
|
||||
const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1);
|
||||
@ -1284,6 +1377,38 @@ const fibonacci = n =>
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### fibonacciCountUntilNum
|
||||
|
||||
Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive).
|
||||
|
||||
Use a mathematical formula to calculate the number of fibonacci numbers until `num`.
|
||||
|
||||
```js
|
||||
const fibonacciCountUntilNum = num =>
|
||||
Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2));
|
||||
// fibonacciCountUntilNum(10) -> 7
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### fibonacciUntilNum
|
||||
|
||||
Generates an array, containing the Fibonacci sequence, up until the nth term.
|
||||
|
||||
Create an empty array of the specific length, initializing the first two values (`0` and `1`).
|
||||
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||
Uses a mathematical formula to calculate the length of the array required.
|
||||
|
||||
```js
|
||||
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), []);
|
||||
}
|
||||
// fibonacciUntilNum(15) -> [0,1,1,2,3,5,8,13]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### gcd
|
||||
|
||||
Calculates the greatest common divisor between two numbers.
|
||||
@ -1303,7 +1428,7 @@ const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||
|
||||
Calculates the Hamming distance between two values.
|
||||
|
||||
Use XOR operator (`^`) to find the bit difference between the two numbers, convert to binary string using `toString(2)`.
|
||||
Use XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`.
|
||||
Count and return the number of `1`s in the string, using `match(/1/g)`.
|
||||
|
||||
```js
|
||||
@ -1316,10 +1441,10 @@ const hammingDistance = (num1, num2) =>
|
||||
|
||||
### inRange
|
||||
|
||||
Checks if the given number falls in the given range.
|
||||
Checks if the given number falls within the given range.
|
||||
|
||||
Use arithmetic comparison to check if the given number is in the specified range.
|
||||
If the second parameter, `end`, is not specified, the reange is considered to be from `0` to `start`.
|
||||
If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.
|
||||
|
||||
```js
|
||||
const inRange = (n, start, end=null) => {
|
||||
@ -1336,9 +1461,9 @@ const inRange = (n, start, end=null) => {
|
||||
|
||||
### isArmstrongNumber
|
||||
|
||||
Checks if the given number is an armstrong number or not.
|
||||
Checks if the given number is an Armstrong number or not.
|
||||
|
||||
Convert the given number into array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.
|
||||
Convert the given number into an array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.
|
||||
|
||||
```js
|
||||
const isArmstrongNumber = digits =>
|
||||
@ -1622,7 +1747,7 @@ const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').spl
|
||||
|
||||
Removes any properties except the ones specified from a JSON object.
|
||||
|
||||
Use `Object.keys()` method to loop over given json object and deleting keys that are not `include`d in given array.
|
||||
Use `Object.keys()` method to loop over given JSON object and deleting keys that are not `include`d in given array.
|
||||
Also if you give it a special key (`childIndicator`) it will search deeply inside it to apply function to inner objects too.
|
||||
|
||||
```js
|
||||
@ -1696,14 +1821,13 @@ orderby(users, ['name', 'age']) -> [{name: 'barney', age: 34}, {name: 'barney',
|
||||
*/
|
||||
```
|
||||
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### select
|
||||
|
||||
Retrieve a property that indicated by the selector from object.
|
||||
Retrieve a property that indicated by the selector from an object.
|
||||
|
||||
If property not exists returns `undefined`.
|
||||
If the property does not exists returns `undefined`.
|
||||
|
||||
```js
|
||||
const select = (from, selector) =>
|
||||
@ -1799,7 +1923,7 @@ const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperC
|
||||
|
||||
Retuns `number` of vowels in provided string.
|
||||
|
||||
Use a regular expression to count number of vowels `(A, E, I, O, U)` in a `string`.
|
||||
Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.
|
||||
|
||||
```js
|
||||
const countVowels = str => (str.match(/[aeiou]/ig) || []).length;
|
||||
@ -1826,7 +1950,7 @@ const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
Converts a string from camelcase.
|
||||
|
||||
Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase.
|
||||
Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
||||
Omit the second argument to use a default separator of `_`.
|
||||
|
||||
```js
|
||||
@ -1840,6 +1964,22 @@ const fromCamelCase = (str, separator = '_') =>
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### repeatString
|
||||
|
||||
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) => {
|
||||
return num >= 0 ? str.repeat(num) : str;
|
||||
}
|
||||
// repeatString("abc",3) -> 'abcabcabc'
|
||||
// repeatString("abc") -> 'abcabc'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### reverseString
|
||||
|
||||
Reverses a string.
|
||||
@ -1872,7 +2012,7 @@ const sortCharactersInString = str =>
|
||||
|
||||
Converts a string to camelcase.
|
||||
|
||||
Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase.
|
||||
Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
||||
|
||||
```js
|
||||
const toCamelCase = str =>
|
||||
@ -1885,6 +2025,42 @@ const toCamelCase = str =>
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### toKebabCase
|
||||
|
||||
Converts a string to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
|
||||
Use `replace()` to add spaces before capital letters, convert `toLowerCase()`, then `replace()` underscores and spaces with hyphens.
|
||||
Also check if a string starts with a hyphen and remove it if yes.
|
||||
|
||||
```js
|
||||
const toKebabCase = str => {
|
||||
str = str.replace(/([A-Z])/g," $1").toLowerCase().replace(/_/g,' ').replace(/-/g,' ').replace(/\s\s+/g, ' ').replace(/\s/g,'-');
|
||||
return str.startsWith('-') ? str.slice(1,str.length) : str;
|
||||
}
|
||||
// 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"
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### toSnakeCase
|
||||
|
||||
Converts a string to snakecase.
|
||||
|
||||
Use `replace()` to add underscores before capital letters, convert `toLowerCase()`, then `replace()` hyphens and spaces with underscores.
|
||||
|
||||
```js
|
||||
const toSnakeCase = str =>
|
||||
str.replace(/(\w)([A-Z])/g, '$1_$2').replace(/[\s-_]+/g, '_').toLowerCase();
|
||||
// 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'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### truncateString
|
||||
|
||||
Truncates a string up to a specified length.
|
||||
@ -1904,7 +2080,7 @@ const truncateString = (str, num) =>
|
||||
|
||||
Converts a given string into an array of words.
|
||||
|
||||
Use `String.split()` with a supplied pattern (defaults to non alpha as a regex) to convert to an array of strings. Use `Array.filter()` to remove any empty strings.
|
||||
Use `String.split()` with a supplied pattern (defaults to non-alpha as a regex) to convert to an array of strings. Use `Array.filter()` to remove any empty strings.
|
||||
Omit the second argument to use the default regex.
|
||||
|
||||
```js
|
||||
@ -1948,7 +2124,7 @@ const coalesceFactory = valid => (...args) => args.find(valid);
|
||||
Extends a 3-digit color code to a 6-digit color code.
|
||||
|
||||
Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
||||
`Array.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
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
|
||||
@ -1976,7 +2152,7 @@ const getType = v =>
|
||||
|
||||
Converts a color code to a `rgb()` or `rgba()` string if alpha value is provided.
|
||||
|
||||
Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If any alpha value is provided alongside 6-digit hex, give `rgba()` string in return.
|
||||
Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If an alpha value is provided alongside 6-digit hex, give `rgba()` string in return.
|
||||
|
||||
```js
|
||||
const hexToRGB = hex => {
|
||||
@ -2084,7 +2260,7 @@ const isSymbol = val => typeof val === 'symbol';
|
||||
|
||||
### RGBToHex
|
||||
|
||||
Converts the values of RGB components to a colorcode.
|
||||
Converts the values of RGB components to a color code.
|
||||
|
||||
Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value.
|
||||
|
||||
@ -2114,20 +2290,11 @@ const timeTaken = callback => {
|
||||
|
||||
### toDecimalMark
|
||||
|
||||
Convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form.
|
||||
|
||||
Use `toString()` to convert the float `num` to a string, then use regex to separate every three characters of the integer part with a comma.
|
||||
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) => {
|
||||
let cleanNum = num.toString().split('').filter(n => '0123456789.'.includes(n)).join('')
|
||||
let wholeNum = cleanNum.split('.')[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
|
||||
let decNum = `.${cleanNum.split('.')[1]}`
|
||||
return wholeNum + decNum;
|
||||
}
|
||||
// toDecimalMark(12305030388.9087) //-> '12,305,030,388.9087'
|
||||
// toDecimalMark(123.889087e2) //-> '12,388.9087'
|
||||
// toDecimalMark('12305abc030388.9087') // -> '12,305,030,388.9087'
|
||||
const toDecimalMark = num => num.toLocaleString("en-US");
|
||||
// toDecimalMark(12305030388.9087) -> "12,305,030,388.9087"
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -2181,6 +2348,35 @@ const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) ==
|
||||
// validateNumber('10') -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
## _Uncategorized_
|
||||
|
||||
### detectDeviceType
|
||||
|
||||
Detects wether the website is being opened in 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
|
||||
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
||||
// detectDeviceType() -> "Mobile"
|
||||
// detectDeviceType() -> "Desktop"
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### negate
|
||||
|
||||
Negates a predicate function.
|
||||
|
||||
Take a predicate function and apply `not` to it with its arguments.
|
||||
|
||||
```js
|
||||
const negate = func => (...args) => !fun(...args);
|
||||
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
|
||||
// negate(isOdd)(1) -> false
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
## Credits
|
||||
|
||||
291
docs/index.html
291
docs/index.html
@ -17,12 +17,45 @@
|
||||
</head>
|
||||
<script>
|
||||
const search = (node) => {
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => x.style.display = x.getAttribute("href").toUpperCase().indexOf(node.value.toUpperCase()) + 1 ? '' : 'none');
|
||||
var remove = false, childs = Array.from(node.parentElement.parentElement.children), toRemove = childs[0];
|
||||
Array.from(node.parentElement.parentElement.children).forEach(x => x.tagName == 'H3' ? (toRemove.style.display = (remove ? 'none' : ''), toRemove = x, remove = true) : (x.style.display == '' ? remove = false : remove=remove));
|
||||
// Hide non-query-matching snippets
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => {
|
||||
x.style.display = x.getAttribute("href").toUpperCase().indexOf(node.value.toUpperCase()) + 1 ? '' : 'none'
|
||||
});
|
||||
Array.from( node.parentElement.parentElement.children )
|
||||
// Filter out the hidden links
|
||||
.filter( x => !( x.tagName == 'A' && x.style.display == 'none' ) )
|
||||
// set the display for each element based on if it's a H3
|
||||
// If it's the last element and an H3, hide it
|
||||
// Otherwise if it's and H3 and the next element is an H3, hide it
|
||||
// Otherwise display it
|
||||
.forEach( ( element, index, source) => {
|
||||
element.style.display = (element.tagName == 'H3' && index + 1 == source.length ? 'none' : element.tagName == 'H3' && source[index + 1].tagName == 'H3' ? 'none' : '')
|
||||
})
|
||||
}
|
||||
function clipboard() {
|
||||
const snippets = document.querySelectorAll("pre");
|
||||
snippets.forEach(element => {
|
||||
const button = document.createElement("button");
|
||||
button.innerHTML = "Copy to clipboard";
|
||||
element.parentElement.appendChild(button);
|
||||
|
||||
button.addEventListener ("click", function() {
|
||||
//The following regex removes all the comments from the snippet
|
||||
const text = element.textContent.replace(/\/\*(.|[\r\n])*?\*\//g, '').replace(/\/\/.*/gm, '');
|
||||
// Apparently you can't copy a variable to clipboard so you need to create text input element,
|
||||
// give it a value, copy it and then remove it from DOM.
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = text.trim();
|
||||
document.body.appendChild(textArea);
|
||||
console.log(textArea.innerText);
|
||||
textArea.select();
|
||||
document.execCommand("Copy");
|
||||
document.body.removeChild(textArea);
|
||||
});
|
||||
});
|
||||
};
|
||||
</script>
|
||||
<body>
|
||||
<body onload="clipboard()">
|
||||
<a href="https://github.com/Chalarangelo/30-seconds-of-code" class="github-corner" aria-label="View source on Github"><svg width="90" height="90" viewBox="0 0 250 250" style="fill:#151513;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
|
||||
<header style="height:5.5rem">
|
||||
<h1 class="logo" href="https://github.com/Chalarangelo/30-seconds-of-code"><img src="favicon.png" style="height:4rem"/><span id="title"> 30 seconds of code</span>
|
||||
@ -41,6 +74,13 @@
|
||||
</div>
|
||||
<label for="doc-drawer-checkbox" class="button drawer-close"></label>
|
||||
|
||||
<h3>Adapter
|
||||
</h3><a class="sublink-1" href="#call">call</a>
|
||||
<a class="sublink-1" href="#collectinto">collectInto</a>
|
||||
<a class="sublink-1" href="#flip">flip</a>
|
||||
<a class="sublink-1" href="#promisify">promisify</a>
|
||||
<a class="sublink-1" href="#spreadover">spreadOver</a>
|
||||
|
||||
<h3>Array
|
||||
</h3><a class="sublink-1" href="#arraygcd">arrayGcd</a>
|
||||
<a class="sublink-1" href="#arraylcm">arrayLcm</a>
|
||||
@ -108,7 +148,6 @@
|
||||
<a class="sublink-1" href="#curry">curry</a>
|
||||
<a class="sublink-1" href="#functionname">functionName</a>
|
||||
<a class="sublink-1" href="#pipe">pipe</a>
|
||||
<a class="sublink-1" href="#promisify">promisify</a>
|
||||
<a class="sublink-1" href="#runpromisesinseries">runPromisesInSeries</a>
|
||||
<a class="sublink-1" href="#sleep">sleep</a>
|
||||
|
||||
@ -121,6 +160,8 @@
|
||||
<a class="sublink-1" href="#distance">distance</a>
|
||||
<a class="sublink-1" href="#factorial">factorial</a>
|
||||
<a class="sublink-1" href="#fibonacci">fibonacci</a>
|
||||
<a class="sublink-1" href="#fibonaccicountuntilnum">fibonacciCountUntilNum</a>
|
||||
<a class="sublink-1" href="#fibonacciuntilnum">fibonacciUntilNum</a>
|
||||
<a class="sublink-1" href="#gcd">gcd</a>
|
||||
<a class="sublink-1" href="#hammingdistance">hammingDistance</a>
|
||||
<a class="sublink-1" href="#inrange">inRange</a>
|
||||
@ -162,9 +203,12 @@
|
||||
<a class="sublink-1" href="#countvowels">countVowels</a>
|
||||
<a class="sublink-1" href="#escaperegexp">escapeRegExp</a>
|
||||
<a class="sublink-1" href="#fromcamelcase">fromCamelCase</a>
|
||||
<a class="sublink-1" href="#repeatstring">repeatString</a>
|
||||
<a class="sublink-1" href="#reversestring">reverseString</a>
|
||||
<a class="sublink-1" href="#sortcharactersinstring">sortCharactersInString</a>
|
||||
<a class="sublink-1" href="#tocamelcase">toCamelCase</a>
|
||||
<a class="sublink-1" href="#tokebabcase">toKebabCase</a>
|
||||
<a class="sublink-1" href="#tosnakecase">toSnakeCase</a>
|
||||
<a class="sublink-1" href="#truncatestring">truncateString</a>
|
||||
<a class="sublink-1" href="#words">words</a>
|
||||
|
||||
@ -187,7 +231,72 @@
|
||||
<a class="sublink-1" href="#uuidgenerator">UUIDGenerator</a>
|
||||
<a class="sublink-1" href="#validatenumber">validateNumber</a>
|
||||
|
||||
</nav><main class="col-sm-12 col-md-8 col-lg-9" style="height:100%;overflow-y:auto;background:#eceef2;padding:0"><a id="top"> </a><h2 style="text-align:center">Array</h2>
|
||||
<h3>Uncategorized
|
||||
</h3><a class="sublink-1" href="#detectdevicetype">detectDeviceType</a>
|
||||
<a class="sublink-1" href="#negate">negate</a>
|
||||
|
||||
</nav><main class="col-sm-12 col-md-8 col-lg-9" style="height:100%;overflow-y:auto;background:#eceef2;padding:0"><a id="top"> </a><h2 style="text-align:center">Adapter</h2>
|
||||
<div class="card fluid"><div class="section double-padded"><h3 id="call">call</h3></div><div class="section double-padded">
|
||||
<p>Given a key and a set of arguments, call them when given a context. Primarily useful in composition.</p>
|
||||
<p>Use a closure to call a stored key with stored arguments.</p>
|
||||
<pre><code class="language-js">const call = ( key, ...args ) => context => context[ key ]( ...args );
|
||||
/*
|
||||
Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
||||
const map = call.bind(null, 'map')
|
||||
Promise.resolve( [ 1, 2, 3 ] ).then( map( x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
||||
*/
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="collectinto">collectInto</h3></div><div class="section double-padded">
|
||||
<p>Changes a function that accepts an array into a variadic function.</p>
|
||||
<p>Given a function, return a closure that collects all inputs into an array-accepting function.</p>
|
||||
<pre><code class="language-js">const collectInto = fn => ( ...args ) => fn( args );
|
||||
/*
|
||||
const Pall = collectInto( Promise.all.bind(Promise) )
|
||||
let p1 = Promise.resolve(1)
|
||||
let p2 = Promise.resolve(2)
|
||||
let p3 = new Promise((resolve) => setTimeout(resolve,2000,3))
|
||||
Pall(p1, p2, p3).then(console.log)
|
||||
*/
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flip">flip</h3></div><div class="section double-padded">
|
||||
<p>Flip takes a function as an argument, then makes the first argument the last</p>
|
||||
<p>Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.</p>
|
||||
<pre><code class="language-js">const flip = fn => (...args) => fn(args.pop(), ...args)
|
||||
/*
|
||||
let a = {name: 'John Smith'}
|
||||
let b = {}
|
||||
const mergeFrom = flip(Object.assign)
|
||||
let mergePerson = mergeFrom.bind(a)
|
||||
mergePerson(b) // == b
|
||||
b = {}
|
||||
Object.assign(b, a) // == b
|
||||
*/
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="promisify">promisify</h3></div><div class="section double-padded">
|
||||
<p>Converts an asynchronous function to return a promise.</p>
|
||||
<p>Use currying to return a function returning a <code>Promise</code> that calls the original function.
|
||||
Use the <code>...rest</code> operator to pass in all the parameters.</p>
|
||||
<p><em>In Node 8+, you can use <a href="https://nodejs.org/api/util.html#util_util_promisify_original"><code>util.promisify</code></a></em></p>
|
||||
<pre><code class="language-js">const promisify = func =>
|
||||
(...args) =>
|
||||
new Promise((resolve, reject) =>
|
||||
func(...args, (err, result) =>
|
||||
err ? reject(err) : resolve(result))
|
||||
);
|
||||
// const delay = promisify((d, cb) => setTimeout(cb, d))
|
||||
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="spreadover">spreadOver</h3></div><div class="section double-padded">
|
||||
<p>Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.</p>
|
||||
<p>Use closures and the spread operator (<code>...</code>) to map the array of arguments to the inputs of the function.</p>
|
||||
<pre><code class="language-js">const spreadOver = fn => argsArr => fn(...argsArr);
|
||||
/*
|
||||
const arrayMax = spreadOver(Math.max)
|
||||
arrayMax([1,2,3]) // -> 3
|
||||
arrayMax([1,2,4]) // -> 4
|
||||
*/
|
||||
</code></pre>
|
||||
</div></div><br/><h2 style="text-align:center">Array</h2>
|
||||
<div class="card fluid"><div class="section double-padded"><h3 id="arraygcd">arrayGcd</h3></div><div class="section double-padded">
|
||||
<p>Calculates the greatest common denominator (gcd) of an array of numbers.</p>
|
||||
<p>Use <code>Array.reduce()</code> and the <code>gcd</code> formula (uses recursion) to calculate the greatest common denominator of an array of numbers.</p>
|
||||
@ -199,11 +308,11 @@
|
||||
// arrayGcd([4,8,12]) -> 4
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="arraylcm">arrayLcm</h3></div><div class="section double-padded">
|
||||
<p>Calculates the lowest common multiple (lcm) of an array of numbers.</p>
|
||||
<p>Use <code>Array.reduce()</code> and the <code>lcm</code> formula (uses recursion) to calculate the lowest common multiple of an array of numbers.</p>
|
||||
<p>Calculates the lowest common multiple (lcm) of an array of numbers.</p>
|
||||
<p>Use <code>Array.reduce()</code> and the <code>lcm</code> formula (uses recursion) to calculate the lowest common multiple of an array of numbers.</p>
|
||||
<pre><code class="language-js">const arrayLcm = arr =>{
|
||||
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));
|
||||
}
|
||||
// arrayLcm([1,2,3,4,5]) -> 60
|
||||
@ -300,8 +409,8 @@ Returns the remaining elements.</p>
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flatten">flatten</h3></div><div class="section double-padded">
|
||||
<p>Flattens an array.</p>
|
||||
<p>Use <code>Array.reduce()</code> to get all elements inside the array and <code>concat()</code> to flatten them.</p>
|
||||
<pre><code class="language-js">const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
|
||||
<p>Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.</p>
|
||||
<pre><code class="language-js">const flatten = arr => [ ].concat( ...arr );
|
||||
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flattendepth">flattenDepth</h3></div><div class="section double-padded">
|
||||
@ -316,7 +425,7 @@ Omit the second element, <code>depth</code> to flatten only to a depth of <code>
|
||||
// flattenDepth([1,[2],[[[3],4],5]], 2) -> [1,2,[3],4,5]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="groupby">groupBy</h3></div><div class="section double-padded">
|
||||
<p>Groups the element of an array based on the given function.</p>
|
||||
<p>Groups the elements of an array based on the given function.</p>
|
||||
<p>Use <code>Array.map()</code> to map the values of an array to a function or property name.
|
||||
Use <code>Array.reduce()</code> to create an object, where the keys are produced from the mapped results.</p>
|
||||
<pre><code class="language-js">const groupBy = (arr, func) =>
|
||||
@ -333,13 +442,13 @@ Use <code>Array.reduce()</code> to create an object, where the keys are produced
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="initial">initial</h3></div><div class="section double-padded">
|
||||
<p>Returns all the elements of an array except the last one.</p>
|
||||
<p>Use <code>arr.slice(0,-1)</code>to return all but the last element of the array.</p>
|
||||
<p>Use <code>arr.slice(0,-1)</code> to return all but the last element of the array.</p>
|
||||
<pre><code class="language-js">const initial = arr => arr.slice(0, -1);
|
||||
// initial([1,2,3]) -> [1,2]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="initialize2darray">initialize2DArray</h3></div><div class="section double-padded">
|
||||
<p>Initializes an 2D array of given width and height and value.</p>
|
||||
<p>Use <code>Array.map()</code> to generate h rows where each is a new array of size w initialize with value. If value is not provided, default to <code>null</code>.</p>
|
||||
<p>Initializes a 2D array of given width and height and value.</p>
|
||||
<p>Use <code>Array.map()</code> to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to <code>null</code>.</p>
|
||||
<pre><code class="language-js">const initialize2DArray = (w, h, val = null) => Array(h).fill().map(() => Array(w).fill(val));
|
||||
// initializeArrayWithRange(2, 2, 0) -> [[0,0], [0,0]]
|
||||
</code></pre>
|
||||
@ -367,13 +476,13 @@ You can omit <code>value</code> to use a default value of <code>0</code>.</p>
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="last">last</h3></div><div class="section double-padded">
|
||||
<p>Returns the last element in an array.</p>
|
||||
<p>Use <code>arr.length - 1</code> to compute index of the last element of the given array and returning it.</p>
|
||||
<p>Use <code>arr.length - 1</code> to compute the index of the last element of the given array and returning it.</p>
|
||||
<pre><code class="language-js">const last = arr => arr[arr.length - 1];
|
||||
// last([1,2,3]) -> 3
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="mapobject">mapObject</h3></div><div class="section double-padded">
|
||||
<p>Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.</p>
|
||||
<p>Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new <code>Array</code> to stor the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).</p>
|
||||
<p>Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new <code>Array</code> to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).</p>
|
||||
<pre><code class="language-js">const mapObject = (arr, fn) =>
|
||||
(a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( );
|
||||
/*
|
||||
@ -392,7 +501,7 @@ Omit the second argument, <code>n</code>, to get the first element of the array.
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="pick">pick</h3></div><div class="section double-padded">
|
||||
<p>Picks the key-value pairs corresponding to the given keys from an object.</p>
|
||||
<p>Use <code>Array.reduce()</code> to convert the filtered/picked keys back to a object with the corresponding key-value pair if the key exist in the obj.</p>
|
||||
<p>Use <code>Array.reduce()</code> to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.</p>
|
||||
<pre><code class="language-js">const pick = (obj, arr) =>
|
||||
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
|
||||
// pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }
|
||||
@ -400,7 +509,7 @@ Omit the second argument, <code>n</code>, to get the first element of the array.
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="pull">pull</h3></div><div class="section double-padded">
|
||||
<p>Mutates the original array to filter out the values specified.</p>
|
||||
<p>Use <code>Array.filter()</code> and <code>Array.includes()</code> to pull out the values that are not needed.
|
||||
Use <code>Array.length = 0</code> to mutate the passed in array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values.</p>
|
||||
Use <code>Array.length = 0</code> to mutate the passed in an array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values.</p>
|
||||
<p><em>(For a snippet that does not mutate the original array see <a href="#without"><code>without</code></a>)</em></p>
|
||||
<pre><code class="language-js">const pull = (arr, ...args) => {
|
||||
let argState = Array.isArray(args[0]) ? args[0] : args;
|
||||
@ -420,7 +529,7 @@ Use <code>Array.length = 0</code> to mutate the passed in array by resetting it'
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="pullatindex">pullAtIndex</h3></div><div class="section double-padded">
|
||||
<p>Mutates the original array to filter out the values at the specified indexes.</p>
|
||||
<p>Use <code>Array.filter()</code> and <code>Array.includes()</code> to pull out the values that are not needed.
|
||||
Use <code>Array.length = 0</code> to mutate the passed in array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values.
|
||||
Use <code>Array.length = 0</code> to mutate the passed in an array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values.
|
||||
Use <code>Array.push()</code> to keep track of pulled values</p>
|
||||
<pre><code class="language-js">const pullAtIndex = (arr, pullArr) => {
|
||||
let removed = [];
|
||||
@ -440,7 +549,7 @@ Use <code>Array.push()</code> to keep track of pulled values</p>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="pullatvalue">pullAtValue</h3></div><div class="section double-padded">
|
||||
<p>Mutates the original array to filter out the values specified. Returns the removed elements.</p>
|
||||
<p>Use <code>Array.filter()</code> and <code>Array.includes()</code> to pull out the values that are not needed.
|
||||
Use <code>Array.length = 0</code> to mutate the passed in array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values.
|
||||
Use <code>Array.length = 0</code> to mutate the passed in an array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values.
|
||||
Use <code>Array.push()</code> to keep track of pulled values</p>
|
||||
<pre><code class="language-js">const pullAtValue = (arr, pullArr) => {
|
||||
let removed = [],
|
||||
@ -470,7 +579,7 @@ The <code>func</code> is invoked with three arguments (<code>value, index, array
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sample">sample</h3></div><div class="section double-padded">
|
||||
<p>Returns a random element from an array.</p>
|
||||
<p>Use <code>Math.random()</code> to generate a random number, multiply it with <code>length</code> and round it of to the nearest whole number using <code>Math.floor()</code>.
|
||||
<p>Use <code>Math.random()</code> to generate a random number, multiply it by <code>length</code> and round it of to the nearest whole number using <code>Math.floor()</code>.
|
||||
This method also works with strings.</p>
|
||||
<pre><code class="language-js">const sample = arr => arr[Math.floor(Math.random() * arr.length)];
|
||||
// sample([3, 7, 9, 11]) -> 9
|
||||
@ -498,7 +607,7 @@ This method also works with strings.</p>
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tail">tail</h3></div><div class="section double-padded">
|
||||
<p>Returns all elements in an array except for the first one.</p>
|
||||
<p>Return <code>arr.slice(1)</code> if the array's <code>length</code> is more than <code>1</code>, otherwise return the whole array.</p>
|
||||
<p>Return <code>arr.slice(1)</code> if the array's <code>length</code> is more than <code>1</code>, otherwise, return the whole array.</p>
|
||||
<pre><code class="language-js">const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
|
||||
// tail([1,2,3]) -> [2,3]
|
||||
// tail([1]) -> [1]
|
||||
@ -579,6 +688,7 @@ Omit the second argument to determine if the element is entirely visible, or spe
|
||||
it is partially visible.</p>
|
||||
<pre><code class="language-js">const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
|
||||
const { top, left, bottom, right } = el.getBoundingClientRect();
|
||||
const { innerHeight, innerWidth } = window;
|
||||
return partiallyVisible
|
||||
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
|
||||
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
|
||||
@ -625,7 +735,7 @@ Pass a second argument to simulate a link click (<code>true</code> - default) or
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="scrolltotop">scrollToTop</h3></div><div class="section double-padded">
|
||||
<p>Smooth-scrolls to the top of the page.</p>
|
||||
<p>Get distance from top using <code>document.documentElement.scrollTop</code> or <code>document.body.scrollTop</code>.
|
||||
Scroll by a fraction of the distance from top. Use <code>window.requestAnimationFrame()</code> to animate the scrolling.</p>
|
||||
Scroll by a fraction of the distance from the top. Use <code>window.requestAnimationFrame()</code> to animate the scrolling.</p>
|
||||
<pre><code class="language-js">const scrollToTop = () => {
|
||||
const c = document.documentElement.scrollTop || document.body.scrollTop;
|
||||
if (c > 0) {
|
||||
@ -638,7 +748,7 @@ Scroll by a fraction of the distance from top. Use <code>window.requestAnimation
|
||||
</div></div><br/><h2 style="text-align:center">Date</h2>
|
||||
<div class="card fluid"><div class="section double-padded"><h3 id="getdaysdiffbetweendates">getDaysDiffBetweenDates</h3></div><div class="section double-padded">
|
||||
<p>Returns the difference (in days) between two dates.</p>
|
||||
<p>Calculate the difference (in days) between to <code>Date</code> objects.</p>
|
||||
<p>Calculate the difference (in days) between two <code>Date</code> objects.</p>
|
||||
<pre><code class="language-js">const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
|
||||
// getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9
|
||||
</code></pre>
|
||||
@ -653,7 +763,7 @@ Scroll by a fraction of the distance from top. Use <code>window.requestAnimation
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="toenglishdate">toEnglishDate</h3></div><div class="section double-padded">
|
||||
<p>Converts a date from American format to English format.</p>
|
||||
<p>Use <code>Date.toISOString()</code>, <code>split('T')</code> and <code>replace()</code> to convert a date from American format to English format.
|
||||
<p>Use <code>Date.toISOString()</code>, <code>split('T')</code> and <code>replace()</code> to convert a date from American format to the English format.
|
||||
Throws an error if the passed time cannot be converted to a date.</p>
|
||||
<pre><code class="language-js">const toEnglishDate = (time) =>
|
||||
{try{return new Date(time).toISOString().split('T')[0].replace(/-/g, '/')}catch(e){return}};
|
||||
@ -688,7 +798,7 @@ multiplyAndAdd5(5, 2) -> 15
|
||||
<p>Curries a function.</p>
|
||||
<p>Use recursion.
|
||||
If the number of provided arguments (<code>args</code>) is sufficient, call the passed function <code>f</code>.
|
||||
Otherwise return a curried function <code>f</code> that expects the rest of the arguments.
|
||||
Otherwise, return a curried function <code>f</code> that expects the rest of the arguments.
|
||||
If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. <code>Math.min()</code>), you can optionally pass the number of arguments to the second parameter <code>arity</code>.</p>
|
||||
<pre><code class="language-js">const curry = (fn, arity = fn.length, ...args) =>
|
||||
arity <= args.length
|
||||
@ -715,20 +825,6 @@ const multiplyAndAdd5 = pipeFunctions(multiply, add5)
|
||||
multiplyAndAdd5(5, 2) -> 15
|
||||
*/
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="promisify">promisify</h3></div><div class="section double-padded">
|
||||
<p>Converts an asynchronous function to return a promise.</p>
|
||||
<p>Use currying to return a function returning a <code>Promise</code> that calls the original function.
|
||||
Use the <code>...rest</code> operator to pass in all the parameters.</p>
|
||||
<p><em>In Node 8+, you can use <a href="https://nodejs.org/api/util.html#util_util_promisify_original"><code>util.promisify</code></a></em></p>
|
||||
<pre><code class="language-js">const promisify = func =>
|
||||
(...args) =>
|
||||
new Promise((resolve, reject) =>
|
||||
func(...args, (err, result) =>
|
||||
err ? reject(err) : resolve(result))
|
||||
);
|
||||
// const delay = promisify((d, cb) => setTimeout(cb, d))
|
||||
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="runpromisesinseries">runPromisesInSeries</h3></div><div class="section double-padded">
|
||||
<p>Runs an array of promises in series.</p>
|
||||
<p>Use <code>Array.reduce()</code> to create a promise chain, where each promise returns the next promise when resolved.</p>
|
||||
@ -765,7 +861,7 @@ async function sleepyWork() {
|
||||
<p>Clamps <code>num</code> within the inclusive <code>lower</code> and <code>upper</code> bounds.</p>
|
||||
<p>If <code>lower</code> is greater than <code>upper</code>, swap them.
|
||||
If <code>num</code> falls within the range, return <code>num</code>.
|
||||
Otherwise return the nearest number in the range.</p>
|
||||
Otherwise, return the nearest number in the range.</p>
|
||||
<pre><code class="language-js">const clampNumber = (num, lower, upper) => {
|
||||
if(lower > upper) upper = [lower, lower = upper][0];
|
||||
return (num>=lower && num<=upper) ? num : ((num < lower) ? lower : upper)
|
||||
@ -776,7 +872,7 @@ Otherwise return the nearest number in the range.</p>
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="collatz">collatz</h3></div><div class="section double-padded">
|
||||
<p>Applies the Collatz algorithm.</p>
|
||||
<p>If <code>n</code> is even, return <code>n/2</code>. Otherwise return <code>3n+1</code>.</p>
|
||||
<p>If <code>n</code> is even, return <code>n/2</code>. Otherwise, return <code>3n+1</code>.</p>
|
||||
<pre><code class="language-js">const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1);
|
||||
// collatz(8) --> 4
|
||||
// collatz(5) --> 16
|
||||
@ -813,6 +909,24 @@ Use <code>Array.reduce()</code> to add values into the array, using the sum of t
|
||||
Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
|
||||
// fibonacci(5) -> [0,1,1,2,3]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="fibonaccicountuntilnum">fibonacciCountUntilNum</h3></div><div class="section double-padded">
|
||||
<p>Returns the number of fibonnacci numbers up to <code>num</code>(<code>0</code> and <code>num</code> inclusive).</p>
|
||||
<p>Use a mathematical formula to calculate the number of fibonacci numbers until <code>num</code>.</p>
|
||||
<pre><code class="language-js">const fibonacciCountUntilNum = num =>
|
||||
Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2));
|
||||
// fibonacciCountUntilNum(10) -> 7
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="fibonacciuntilnum">fibonacciUntilNum</h3></div><div class="section double-padded">
|
||||
<p>Generates an array, containing the Fibonacci sequence, up until the nth term.</p>
|
||||
<p>Create an empty array of the specific length, initializing the first two values (<code>0</code> and <code>1</code>).
|
||||
Use <code>Array.reduce()</code> to add values into the array, using the sum of the last two values, except for the first two.
|
||||
Uses a mathematical formula to calculate the length of the array required.</p>
|
||||
<pre><code class="language-js">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), []);
|
||||
}
|
||||
// fibonacciUntilNum(15) -> [0,1,1,2,3,5,8,13]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="gcd">gcd</h3></div><div class="section double-padded">
|
||||
<p>Calculates the greatest common divisor between two numbers.</p>
|
||||
<p>Use recursion.
|
||||
@ -823,16 +937,16 @@ Otherwise, return the GCD of <code>y</code> and the remainder of the division <c
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="hammingdistance">hammingDistance</h3></div><div class="section double-padded">
|
||||
<p>Calculates the Hamming distance between two values.</p>
|
||||
<p>Use XOR operator (<code>^</code>) to find the bit difference between the two numbers, convert to binary string using <code>toString(2)</code>.
|
||||
<p>Use XOR operator (<code>^</code>) to find the bit difference between the two numbers, convert to a binary string using <code>toString(2)</code>.
|
||||
Count and return the number of <code>1</code>s in the string, using <code>match(/1/g)</code>.</p>
|
||||
<pre><code class="language-js">const hammingDistance = (num1, num2) =>
|
||||
((num1 ^ num2).toString(2).match(/1/g) || '').length;
|
||||
// hammingDistance(2,3) -> 1
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="inrange">inRange</h3></div><div class="section double-padded">
|
||||
<p>Checks if the given number falls in the given range.</p>
|
||||
<p>Checks if the given number falls within the given range.</p>
|
||||
<p>Use arithmetic comparison to check if the given number is in the specified range.
|
||||
If the second parameter, <code>end</code>, is not specified, the reange is considered to be from <code>0</code> to <code>start</code>.</p>
|
||||
If the second parameter, <code>end</code>, is not specified, the range is considered to be from <code>0</code> to <code>start</code>.</p>
|
||||
<pre><code class="language-js">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);
|
||||
@ -843,8 +957,8 @@ If the second parameter, <code>end</code>, is not specified, the reange is consi
|
||||
// inrange(3, 2) -> false
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isarmstrongnumber">isArmstrongNumber</h3></div><div class="section double-padded">
|
||||
<p>Checks if the given number is an armstrong number or not.</p>
|
||||
<p>Convert the given number into array of digits. Use <code>Math.pow()</code> to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return <code>true</code> otherwise <code>false</code>.</p>
|
||||
<p>Checks if the given number is an Armstrong number or not.</p>
|
||||
<p>Convert the given number into an array of digits. Use <code>Math.pow()</code> to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return <code>true</code> otherwise <code>false</code>.</p>
|
||||
<pre><code class="language-js">const isArmstrongNumber = digits =>
|
||||
( arr => arr.reduce( ( a, d ) => a + Math.pow( parseInt( d ), arr.length ), 0 ) == digits ? true : false )( ( digits+'' ).split( '' ) );
|
||||
// isArmstrongNumber(1634) -> true
|
||||
@ -1008,7 +1122,7 @@ console.log(arr) // -> ['line1', 'line2', 'line3']
|
||||
</div></div><br/><h2 style="text-align:center">Object</h2>
|
||||
<div class="card fluid"><div class="section double-padded"><h3 id="cleanobj">cleanObj</h3></div><div class="section double-padded">
|
||||
<p>Removes any properties except the ones specified from a JSON object.</p>
|
||||
<p>Use <code>Object.keys()</code> method to loop over given json object and deleting keys that are not <code>include</code>d in given array.
|
||||
<p>Use <code>Object.keys()</code> method to loop over given JSON object and deleting keys that are not <code>include</code>d in given array.
|
||||
Also if you give it a special key (<code>childIndicator</code>) it will search deeply inside it to apply function to inner objects too.</p>
|
||||
<pre><code class="language-js">const cleanObj = (obj, keysToKeep = [], childIndicator) => {
|
||||
Object.keys(obj).forEach(key => {
|
||||
@ -1059,8 +1173,8 @@ orderby(users, ['name', 'age']) -> [{name: 'barney', age: 34}, {name: 'barney
|
||||
*/
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="select">select</h3></div><div class="section double-padded">
|
||||
<p>Retrieve a property that indicated by the selector from object.</p>
|
||||
<p>If property not exists returns <code>undefined</code>.</p>
|
||||
<p>Retrieve a property that indicated by the selector from an object.</p>
|
||||
<p>If the property does not exists returns <code>undefined</code>.</p>
|
||||
<pre><code class="language-js">const select = (from, selector) =>
|
||||
selector.split('.').reduce((prev, cur) => prev && prev[cur], from);
|
||||
|
||||
@ -1114,7 +1228,7 @@ Omit the <code>lowerRest</code> parameter to keep the rest of the string intact,
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="countvowels">countVowels</h3></div><div class="section double-padded">
|
||||
<p>Retuns <code>number</code> of vowels in provided string.</p>
|
||||
<p>Use a regular expression to count number of vowels <code>(A, E, I, O, U)</code> in a <code>string</code>.</p>
|
||||
<p>Use a regular expression to count the number of vowels <code>(A, E, I, O, U)</code> in a <code>string</code>.</p>
|
||||
<pre><code class="language-js">const countVowels = str => (str.match(/[aeiou]/ig) || []).length;
|
||||
// countVowels('foobar') -> 3
|
||||
// countVowels('gym') -> 0
|
||||
@ -1127,7 +1241,7 @@ Omit the <code>lowerRest</code> parameter to keep the rest of the string intact,
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="fromcamelcase">fromCamelCase</h3></div><div class="section double-padded">
|
||||
<p>Converts a string from camelcase.</p>
|
||||
<p>Use <code>replace()</code> to remove underscores, hyphens and spaces and convert words to camelcase.
|
||||
<p>Use <code>replace()</code> to remove underscores, hyphens, and spaces and convert words to camelcase.
|
||||
Omit the second argument to use a default separator of <code>_</code>.</p>
|
||||
<pre><code class="language-js">const fromCamelCase = (str, separator = '_') =>
|
||||
str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
|
||||
@ -1136,6 +1250,15 @@ Omit the second argument to use a default separator of <code>_</code>.</p>
|
||||
// fromCamelCase('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized'
|
||||
// fromCamelCase('someJavascriptProperty', '_') -> 'some_javascript_property'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="repeatstring">repeatString</h3></div><div class="section double-padded">
|
||||
<p>Repeats a string n times using <code>String.repeat()</code></p>
|
||||
<p>If no string is provided the default is <code>""</code> and the default number of times is 2.</p>
|
||||
<pre><code class="language-js">const repeatString = (str="",num=2) => {
|
||||
return num >= 0 ? str.repeat(num) : str;
|
||||
}
|
||||
// repeatString("abc",3) -> 'abcabcabc'
|
||||
// repeatString("abc") -> 'abcabc'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="reversestring">reverseString</h3></div><div class="section double-padded">
|
||||
<p>Reverses a string.</p>
|
||||
<p>Use <code>split('')</code> and <code>Array.reverse()</code> to reverse the order of the characters in the string.
|
||||
@ -1152,7 +1275,7 @@ Combine characters to get a string using <code>join('')</code>.</p>
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tocamelcase">toCamelCase</h3></div><div class="section double-padded">
|
||||
<p>Converts a string to camelcase.</p>
|
||||
<p>Use <code>replace()</code> to remove underscores, hyphens and spaces and convert words to camelcase.</p>
|
||||
<p>Use <code>replace()</code> to remove underscores, hyphens, and spaces and convert words to camelcase.</p>
|
||||
<pre><code class="language-js">const toCamelCase = str =>
|
||||
str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase());
|
||||
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
|
||||
@ -1160,6 +1283,29 @@ Combine characters to get a string using <code>join('')</code>.</p>
|
||||
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
|
||||
// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tokebabcase">toKebabCase</h3></div><div class="section double-padded">
|
||||
<p>Converts a string to <a href="https://en.wikipedia.org/wiki/Letter_case#Special_case_styles">kebab case</a>.
|
||||
Use <code>replace()</code> to add spaces before capital letters, convert <code>toLowerCase()</code>, then <code>replace()</code> underscores and spaces with hyphens.
|
||||
Also check if a string starts with a hyphen and remove it if yes.</p>
|
||||
<pre><code class="language-js">const toKebabCase = str => {
|
||||
str = str.replace(/([A-Z])/g," $1").toLowerCase().replace(/_/g,' ').replace(/-/g,' ').replace(/\s\s+/g, ' ').replace(/\s/g,'-');
|
||||
return str.startsWith('-') ? str.slice(1,str.length) : str;
|
||||
}
|
||||
// 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"
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tosnakecase">toSnakeCase</h3></div><div class="section double-padded">
|
||||
<p>Converts a string to snakecase.</p>
|
||||
<p>Use <code>replace()</code> to add underscores before capital letters, convert <code>toLowerCase()</code>, then <code>replace()</code> hyphens and spaces with underscores.</p>
|
||||
<pre><code class="language-js">const toSnakeCase = str =>
|
||||
str.replace(/(\w)([A-Z])/g, '$1_$2').replace(/[\s-_]+/g, '_').toLowerCase();
|
||||
// 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'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="truncatestring">truncateString</h3></div><div class="section double-padded">
|
||||
<p>Truncates a string up to a specified length.</p>
|
||||
<p>Determine if the string's <code>length</code> is greater than <code>num</code>.
|
||||
@ -1170,7 +1316,7 @@ Return the string truncated to the desired length, with <code>...</code> appende
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="words">words</h3></div><div class="section double-padded">
|
||||
<p>Converts a given string into an array of words.</p>
|
||||
<p>Use <code>String.split()</code> with a supplied pattern (defaults to non alpha as a regex) to convert to an array of strings. Use <code>Array.filter()</code> to remove any empty strings.
|
||||
<p>Use <code>String.split()</code> with a supplied pattern (defaults to non-alpha as a regex) to convert to an array of strings. Use <code>Array.filter()</code> to remove any empty strings.
|
||||
Omit the second argument to use the default regex.</p>
|
||||
<pre><code class="language-js">const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
|
||||
// words("I love javaScript!!") -> ["I", "love", "javaScript"]
|
||||
@ -1193,7 +1339,7 @@ Omit the second argument to use the default regex.</p>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="extendhex">extendHex</h3></div><div class="section double-padded">
|
||||
<p>Extends a 3-digit color code to a 6-digit color code.</p>
|
||||
<p>Use <code>Array.map()</code>, <code>split()</code> and <code>Array.join()</code> to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
||||
<code>Array.slice()</code> is used to remove <code>#</code> from string start since it's added once.</p>
|
||||
<code>String.slice()</code> is used to remove <code>#</code> from string start since it's added once.</p>
|
||||
<pre><code class="language-js">const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
|
||||
// extendHex('#03f') -> '#0033ff'
|
||||
@ -1208,7 +1354,7 @@ Omit the second argument to use the default regex.</p>
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="hextorgb">hexToRGB</h3></div><div class="section double-padded">
|
||||
<p>Converts a color code to a <code>rgb()</code> or <code>rgba()</code> string if alpha value is provided.</p>
|
||||
<p>Use bitwise right-shift operator and mask bits with <code>&</code> (and) operator to convert a hexadecimal color code (with or without prefixed with <code>#</code>) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If any alpha value is provided alongside 6-digit hex, give <code>rgba()</code> string in return.</p>
|
||||
<p>Use bitwise right-shift operator and mask bits with <code>&</code> (and) operator to convert a hexadecimal color code (with or without prefixed with <code>#</code>) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If an alpha value is provided alongside 6-digit hex, give <code>rgba()</code> string in return.</p>
|
||||
<pre><code class="language-js">const hexToRGB = hex => {
|
||||
let alpha = false, h = hex.slice(hex.startsWith('#') ? 1 : 0);
|
||||
if (h.length === 3) h = [...h].map(x => x + x).join('');
|
||||
@ -1268,7 +1414,7 @@ Omit the second argument to use the default regex.</p>
|
||||
// isSymbol(Symbol('x')) -> true
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="rgbtohex">RGBToHex</h3></div><div class="section double-padded">
|
||||
<p>Converts the values of RGB components to a colorcode.</p>
|
||||
<p>Converts the values of RGB components to a color code.</p>
|
||||
<p>Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (<code><<</code>) and <code>toString(16)</code>, then <code>padStart(6,'0')</code> to get a 6-digit hexadecimal value.</p>
|
||||
<pre><code class="language-js">const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
// RGBToHex(255, 165, 1) -> 'ffa501'
|
||||
@ -1284,17 +1430,9 @@ Omit the second argument to use the default regex.</p>
|
||||
// (logged): timeTaken: 0.02099609375ms
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="todecimalmark">toDecimalMark</h3></div><div class="section double-padded">
|
||||
<p>Convert a float-point arithmetic to the <a href="https://en.wikipedia.org/wiki/Decimal_mark">Decimal mark</a> form.</p>
|
||||
<p>Use <code>toString()</code> to convert the float <code>num</code> to a string, then use regex to separate every three characters of the integer part with a comma.</p>
|
||||
<pre><code class="language-js">const toDecimalMark = (num) => {
|
||||
let cleanNum = num.toString().split('').filter(n => '0123456789.'.includes(n)).join('')
|
||||
let wholeNum = cleanNum.split('.')[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
|
||||
let decNum = `.${cleanNum.split('.')[1]}`
|
||||
return wholeNum + decNum;
|
||||
}
|
||||
// toDecimalMark(12305030388.9087) //-> '12,305,030,388.9087'
|
||||
// toDecimalMark(123.889087e2) //-> '12,388.9087'
|
||||
// toDecimalMark('12305abc030388.9087') // -> '12,305,030,388.9087'
|
||||
<p>Use <code>toLocaleString()</code> to convert a float-point arithmetic to the <a href="https://en.wikipedia.org/wiki/Decimal_mark">Decimal mark</a> form. It makes a comma separated string from a number.</p>
|
||||
<pre><code class="language-js">const toDecimalMark = num => num.toLocaleString("en-US");
|
||||
// toDecimalMark(12305030388.9087) -> "12,305,030,388.9087"
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="toordinalsuffix">toOrdinalSuffix</h3></div><div class="section double-padded">
|
||||
<p>Adds an ordinal suffix to a number.</p>
|
||||
@ -1326,6 +1464,21 @@ Use <code>Number()</code> to check if the coercion holds.</p>
|
||||
<pre><code class="language-js">const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
|
||||
// validateNumber('10') -> true
|
||||
</code></pre>
|
||||
</div></div><br/><h2 style="text-align:center">Uncategorized</h2>
|
||||
<div class="card fluid"><div class="section double-padded"><h3 id="detectdevicetype">detectDeviceType</h3></div><div class="section double-padded">
|
||||
<p>Detects wether the website is being opened in a mobile device or a desktop/laptop.</p>
|
||||
<p>Use a regular expression to test the <code>navigator.userAgent</code> property to figure out if the device is a mobile device or a desktop/laptop.</p>
|
||||
<pre><code class="language-js">const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
||||
// detectDeviceType() -> "Mobile"
|
||||
// detectDeviceType() -> "Desktop"
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="negate">negate</h3></div><div class="section double-padded">
|
||||
<p>Negates a predicate function.</p>
|
||||
<p>Take a predicate function and apply <code>not</code> to it with its arguments.</p>
|
||||
<pre><code class="language-js">const negate = func => (...args) => !fun(...args);
|
||||
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
|
||||
// negate(isOdd)(1) -> false
|
||||
</code></pre>
|
||||
</div></div><br/>
|
||||
<footer>
|
||||
<p style="display:inline-block"><strong>30 seconds of code</strong> is licensed under the <a href="https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE">CC0-1.0</a> license.<br/>Icons made by <a href="https://www.flaticon.com/authors/smashicons">Smashicons</a> from <a href="https://www.flaticon.com/">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/">CC 3.0 BY</a>.<br/>Ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> is licensed by <a href="https://opensource.org/licenses/MIT">The MIT License</a><br/>Built with the <a href="https://minicss.org">mini.css framework</a>.</p>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -110,7 +110,9 @@ $mark-tag-border-radius: 1em;
|
||||
// Website-specific styles
|
||||
|
||||
html, * { font-family: 'Poppins', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Ubuntu, "Helvetica Neue", Helvetica, sans-serif; }
|
||||
code, pre, kbd, code *, pre *, kbd * { font-family: 'Inconsolata', Menlo, Consolas, monospace; }
|
||||
code, pre, kbd, code *, pre *, kbd *, code[class*="language-"], pre[class*="language-"] {
|
||||
font-family: 'Inconsolata', Menlo, Consolas, monospace !important;
|
||||
}
|
||||
code, kbd { font-size: 1em; }
|
||||
code { transform: scale(1); } /* Deals with the issue described in #243 */
|
||||
pre { font-size: 1rem; border: 0.0625rem solid var(--secondary-border-color); border-radius: var(--universal-border-radius);}
|
||||
|
||||
@ -10,6 +10,7 @@ var snippetsPath = './snippets';
|
||||
// Read files, lint each one individually and update
|
||||
try {
|
||||
let snippetFilenames = fs.readdirSync(snippetsPath);
|
||||
let jobCounter = 0;
|
||||
snippetFilenames.sort((a, b) => {
|
||||
a = a.toLowerCase();
|
||||
b = b.toLowerCase();
|
||||
@ -25,10 +26,14 @@ try {
|
||||
// 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('```'));
|
||||
while(jobCounter >= 20){
|
||||
setTimeout(()=>{},5000);
|
||||
}
|
||||
fs.writeFileSync(`${snippet}.temp.js`,`${originalCode}`);
|
||||
// Run semistandard asynchronously (only way this manages to run), get linted code
|
||||
// and write back to the original snippet file. Remove temporary file
|
||||
cp.exec(`semistandard "${snippet}.temp.js" --fix`,{},(error, stdOut, stdErr) => {
|
||||
jobCounter += 1;
|
||||
let lintedCode = fs.readFileSync(`${snippet}.temp.js`,'utf8');
|
||||
fs.writeFile(path.join(snippetsPath,snippet), `${snippetData.slice(0, snippetData.indexOf('```js')+5)+lintedCode+'```\n'}`);
|
||||
fs.unlink(`${snippet}.temp.js`);
|
||||
@ -36,6 +41,7 @@ try {
|
||||
console.log(`${chalk.green('SUCCESS!')} Linted snippet: ${snippet}`);
|
||||
// Log the time taken for the file
|
||||
console.timeEnd(`Linter (${snippet})`);
|
||||
jobCounter -= 1;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
### RGBToHex
|
||||
|
||||
Converts the values of RGB components to a colorcode.
|
||||
Converts the values of RGB components to a color code.
|
||||
|
||||
Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value.
|
||||
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
### arrayLcm
|
||||
|
||||
Calculates the lowest common multiple (lcm) of an array of numbers.
|
||||
Calculates the lowest common multiple (lcm) of an array of numbers.
|
||||
|
||||
Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers.
|
||||
Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers.
|
||||
|
||||
```js
|
||||
const arrayLcm = arr =>{
|
||||
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));
|
||||
}
|
||||
// arrayLcm([1,2,3,4,5]) -> 60
|
||||
|
||||
14
snippets/call.md
Normal file
14
snippets/call.md
Normal file
@ -0,0 +1,14 @@
|
||||
### call
|
||||
|
||||
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
|
||||
|
||||
Use a closure to call a stored key with stored arguments.
|
||||
|
||||
```js
|
||||
const call = ( key, ...args ) => context => context[ key ]( ...args );
|
||||
/*
|
||||
Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
||||
const map = call.bind(null, 'map')
|
||||
Promise.resolve( [ 1, 2, 3 ] ).then( map( x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
||||
*/
|
||||
```
|
||||
@ -4,7 +4,7 @@ Clamps `num` within the inclusive `lower` and `upper` bounds.
|
||||
|
||||
If `lower` is greater than `upper`, swap them.
|
||||
If `num` falls within the range, return `num`.
|
||||
Otherwise return the nearest number in the range.
|
||||
Otherwise, return the nearest number in the range.
|
||||
|
||||
```js
|
||||
const clampNumber = (num, lower, upper) => {
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Removes any properties except the ones specified from a JSON object.
|
||||
|
||||
Use `Object.keys()` method to loop over given json object and deleting keys that are not `include`d in given array.
|
||||
Use `Object.keys()` method to loop over given JSON object and deleting keys that are not `include`d in given array.
|
||||
Also if you give it a special key (`childIndicator`) it will search deeply inside it to apply function to inner objects too.
|
||||
|
||||
```js
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Applies the Collatz algorithm.
|
||||
|
||||
If `n` is even, return `n/2`. Otherwise return `3n+1`.
|
||||
If `n` is even, return `n/2`. Otherwise, return `3n+1`.
|
||||
|
||||
```js
|
||||
const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1);
|
||||
|
||||
16
snippets/collectInto.md
Normal file
16
snippets/collectInto.md
Normal file
@ -0,0 +1,16 @@
|
||||
### collectInto
|
||||
|
||||
Changes a function that accepts an array into a variadic function.
|
||||
|
||||
Given a function, return a closure that collects all inputs into an array-accepting function.
|
||||
|
||||
```js
|
||||
const collectInto = fn => ( ...args ) => fn( args );
|
||||
/*
|
||||
const Pall = collectInto( Promise.all.bind(Promise) )
|
||||
let p1 = Promise.resolve(1)
|
||||
let p2 = Promise.resolve(2)
|
||||
let p3 = new Promise((resolve) => setTimeout(resolve,2000,3))
|
||||
Pall(p1, p2, p3).then(console.log)
|
||||
*/
|
||||
```
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Retuns `number` of vowels in provided string.
|
||||
|
||||
Use a regular expression to count number of vowels `(A, E, I, O, U)` in a `string`.
|
||||
Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.
|
||||
|
||||
```js
|
||||
const countVowels = str => (str.match(/[aeiou]/ig) || []).length;
|
||||
|
||||
@ -4,7 +4,7 @@ Curries a function.
|
||||
|
||||
Use recursion.
|
||||
If the number of provided arguments (`args`) is sufficient, call the passed function `f`.
|
||||
Otherwise return a curried function `f` that expects the rest of the arguments.
|
||||
Otherwise, return a curried function `f` that expects the rest of the arguments.
|
||||
If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`.
|
||||
|
||||
```js
|
||||
|
||||
11
snippets/detectDeviceType.md
Normal file
11
snippets/detectDeviceType.md
Normal file
@ -0,0 +1,11 @@
|
||||
### detectDeviceType
|
||||
|
||||
Detects wether the website is being opened in 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
|
||||
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
||||
// detectDeviceType() -> "Mobile"
|
||||
// detectDeviceType() -> "Desktop"
|
||||
```
|
||||
@ -1,11 +1,11 @@
|
||||
### dropRight
|
||||
|
||||
Returns a new array with `n` elements removed from the right
|
||||
Returns a new array with `n` elements removed from the right.
|
||||
|
||||
Check if `n` is shorter than the given array and use `Array.slice()` to slice it accordingly or return an empty array.
|
||||
Use `Array.slice()` to slice the remove the specified number of elements from the right.
|
||||
|
||||
```js
|
||||
const dropRight = (arr, n = 1) => n < arr.length ? arr.slice(0, arr.length - n) : []
|
||||
const dropRight = (arr, n = 1) => arr.slice(0, -n);
|
||||
//dropRight([1,2,3]) -> [1,2]
|
||||
//dropRight([1,2,3], 2) -> [1]
|
||||
//dropRight([1,2,3], 42) -> []
|
||||
|
||||
@ -10,6 +10,7 @@ it is partially visible.
|
||||
```js
|
||||
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
|
||||
const { top, left, bottom, right } = el.getBoundingClientRect();
|
||||
const { innerHeight, innerWidth } = window;
|
||||
return partiallyVisible
|
||||
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
|
||||
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
Extends a 3-digit color code to a 6-digit color code.
|
||||
|
||||
Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
||||
`Array.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
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
|
||||
|
||||
@ -2,9 +2,9 @@
|
||||
|
||||
Flattens an array.
|
||||
|
||||
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
|
||||
Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.
|
||||
|
||||
```js
|
||||
const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
|
||||
const flatten = arr => [ ].concat( ...arr );
|
||||
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
||||
```
|
||||
|
||||
18
snippets/flip.md
Normal file
18
snippets/flip.md
Normal file
@ -0,0 +1,18 @@
|
||||
### flip
|
||||
|
||||
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.
|
||||
|
||||
```js
|
||||
const flip = fn => (...args) => fn(args.pop(), ...args)
|
||||
/*
|
||||
let a = {name: 'John Smith'}
|
||||
let b = {}
|
||||
const mergeFrom = flip(Object.assign)
|
||||
let mergePerson = mergeFrom.bind(a)
|
||||
mergePerson(b) // == b
|
||||
b = {}
|
||||
Object.assign(b, a) // == b
|
||||
*/
|
||||
```
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Converts a string from camelcase.
|
||||
|
||||
Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase.
|
||||
Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
||||
Omit the second argument to use a default separator of `_`.
|
||||
|
||||
```js
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Returns the difference (in days) between two dates.
|
||||
|
||||
Calculate the difference (in days) between to `Date` objects.
|
||||
Calculate the difference (in days) between two `Date` objects.
|
||||
|
||||
```js
|
||||
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
### groupBy
|
||||
|
||||
Groups the element of an array based on the given function.
|
||||
Groups the elements of an array based on the given function.
|
||||
|
||||
Use `Array.map()` to map the values of an array to a function or property name.
|
||||
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Calculates the Hamming distance between two values.
|
||||
|
||||
Use XOR operator (`^`) to find the bit difference between the two numbers, convert to binary string using `toString(2)`.
|
||||
Use XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`.
|
||||
Count and return the number of `1`s in the string, using `match(/1/g)`.
|
||||
|
||||
```js
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Converts a color code to a `rgb()` or `rgba()` string if alpha value is provided.
|
||||
|
||||
Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If any alpha value is provided alongside 6-digit hex, give `rgba()` string in return.
|
||||
Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If an alpha value is provided alongside 6-digit hex, give `rgba()` string in return.
|
||||
|
||||
```js
|
||||
const hexToRGB = hex => {
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
### inRange
|
||||
|
||||
Checks if the given number falls in the given range.
|
||||
Checks if the given number falls within the given range.
|
||||
|
||||
Use arithmetic comparison to check if the given number is in the specified range.
|
||||
If the second parameter, `end`, is not specified, the reange is considered to be from `0` to `start`.
|
||||
If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.
|
||||
|
||||
```js
|
||||
const inRange = (n, start, end=null) => {
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Returns all the elements of an array except the last one.
|
||||
|
||||
Use `arr.slice(0,-1)`to return all but the last element of the array.
|
||||
Use `arr.slice(0,-1)` to return all but the last element of the array.
|
||||
|
||||
```js
|
||||
const initial = arr => arr.slice(0, -1);
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
### initialize2DArray
|
||||
|
||||
Initializes an 2D array of given width and height and value.
|
||||
Initializes a 2D array of given width and height and value.
|
||||
|
||||
Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If value is not provided, default to `null`.
|
||||
Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
|
||||
|
||||
```js
|
||||
const initialize2DArray = (w, h, val = null) => Array(h).fill().map(() => Array(w).fill(val));
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
### isArmstrongNumber
|
||||
|
||||
Checks if the given number is an armstrong number or not.
|
||||
Checks if the given number is an Armstrong number or not.
|
||||
|
||||
Convert the given number into array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.
|
||||
Convert the given number into an array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.
|
||||
|
||||
```js
|
||||
const isArmstrongNumber = digits =>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Returns the last element in an array.
|
||||
|
||||
Use `arr.length - 1` to compute index of the last element of the given array and returning it.
|
||||
Use `arr.length - 1` to compute the index of the last element of the given array and returning it.
|
||||
|
||||
```js
|
||||
const last = arr => arr[arr.length - 1];
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
|
||||
|
||||
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to stor the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
|
||||
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
|
||||
|
||||
```js
|
||||
const mapObject = (arr, fn) =>
|
||||
|
||||
11
snippets/negate.md
Normal file
11
snippets/negate.md
Normal file
@ -0,0 +1,11 @@
|
||||
### negate
|
||||
|
||||
Negates a predicate function.
|
||||
|
||||
Take a predicate function and apply `not` to it with its arguments.
|
||||
|
||||
```js
|
||||
const negate = func => (...args) => !fun(...args);
|
||||
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
|
||||
// negate(isOdd)(1) -> false
|
||||
```
|
||||
@ -23,4 +23,3 @@ orderby(users, ['name', 'age'], ['asc', 'desc']) -> [{name: 'barney', age: 36},
|
||||
orderby(users, ['name', 'age']) -> [{name: 'barney', age: 34}, {name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
|
||||
*/
|
||||
```
|
||||
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Picks the key-value pairs corresponding to the given keys from an object.
|
||||
|
||||
Use `Array.reduce()` to convert the filtered/picked keys back to a object with the corresponding key-value pair if the key exist in the obj.
|
||||
Use `Array.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.
|
||||
|
||||
```js
|
||||
const pick = (obj, arr) =>
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
Mutates the original array to filter out the values specified.
|
||||
|
||||
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
|
||||
Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
|
||||
_(For a snippet that does not mutate the original array see [`without`](#without))_
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
Mutates the original array to filter out the values at the specified indexes.
|
||||
|
||||
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
|
||||
Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.push()` to keep track of pulled values
|
||||
|
||||
```js
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
Mutates the original array to filter out the values specified. Returns the removed elements.
|
||||
|
||||
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
|
||||
Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
Use `Array.push()` to keep track of pulled values
|
||||
|
||||
```js
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Returns a random element from an array.
|
||||
|
||||
Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`.
|
||||
Use `Math.random()` to generate a random number, multiply it by `length` and round it of to the nearest whole number using `Math.floor()`.
|
||||
This method also works with strings.
|
||||
|
||||
```js
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
Smooth-scrolls to the top of the page.
|
||||
|
||||
Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`.
|
||||
Scroll by a fraction of the distance from top. Use `window.requestAnimationFrame()` to animate the scrolling.
|
||||
Scroll by a fraction of the distance from the top. Use `window.requestAnimationFrame()` to animate the scrolling.
|
||||
|
||||
```js
|
||||
const scrollToTop = () => {
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
### select
|
||||
|
||||
Retrieve a property that indicated by the selector from object.
|
||||
Retrieve a property that indicated by the selector from an object.
|
||||
|
||||
If property not exists returns `undefined`.
|
||||
If the property does not exists returns `undefined`.
|
||||
|
||||
```js
|
||||
const select = (from, selector) =>
|
||||
|
||||
14
snippets/spreadOver.md
Normal file
14
snippets/spreadOver.md
Normal file
@ -0,0 +1,14 @@
|
||||
### spreadOver
|
||||
|
||||
Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
|
||||
|
||||
Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function.
|
||||
|
||||
```js
|
||||
const spreadOver = fn => argsArr => fn(...argsArr);
|
||||
/*
|
||||
const arrayMax = spreadOver(Math.max)
|
||||
arrayMax([1,2,3]) // -> 3
|
||||
arrayMax([1,2,4]) // -> 4
|
||||
*/
|
||||
```
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Returns all elements in an array except for the first one.
|
||||
|
||||
Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise return the whole array.
|
||||
Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array.
|
||||
|
||||
```js
|
||||
const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Converts a string to camelcase.
|
||||
|
||||
Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase.
|
||||
Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
||||
|
||||
```js
|
||||
const toCamelCase = str =>
|
||||
|
||||
@ -1,17 +1,8 @@
|
||||
### toDecimalMark
|
||||
|
||||
Convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form.
|
||||
|
||||
Use `toString()` to convert the float `num` to a string, then use regex to separate every three characters of the integer part with a comma.
|
||||
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) => {
|
||||
let cleanNum = num.toString().split('').filter(n => '0123456789.'.includes(n)).join('')
|
||||
let wholeNum = cleanNum.split('.')[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
|
||||
let decNum = `.${cleanNum.split('.')[1]}`
|
||||
return wholeNum + decNum;
|
||||
}
|
||||
// toDecimalMark(12305030388.9087) //-> '12,305,030,388.9087'
|
||||
// toDecimalMark(123.889087e2) //-> '12,388.9087'
|
||||
// toDecimalMark('12305abc030388.9087') // -> '12,305,030,388.9087'
|
||||
const toDecimalMark = num => num.toLocaleString("en-US");
|
||||
// toDecimalMark(12305030388.9087) -> "12,305,030,388.9087"
|
||||
```
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Converts a date from American format to English format.
|
||||
|
||||
Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from American format to English format.
|
||||
Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from American format to the English format.
|
||||
Throws an error if the passed time cannot be converted to a date.
|
||||
|
||||
```js
|
||||
|
||||
14
snippets/toSnakeCase.md
Normal file
14
snippets/toSnakeCase.md
Normal file
@ -0,0 +1,14 @@
|
||||
### toSnakeCase
|
||||
|
||||
Converts a string to snakecase.
|
||||
|
||||
Use `replace()` to add underscores before capital letters, convert `toLowerCase()`, then `replace()` hyphens and spaces with underscores.
|
||||
|
||||
```js
|
||||
const toSnakeCase = str =>
|
||||
str.replace(/(\w)([A-Z])/g, '$1_$2').replace(/[\s-_]+/g, '_').toLowerCase();
|
||||
// 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'
|
||||
```
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Converts a given string into an array of words.
|
||||
|
||||
Use `String.split()` with a supplied pattern (defaults to non alpha as a regex) to convert to an array of strings. Use `Array.filter()` to remove any empty strings.
|
||||
Use `String.split()` with a supplied pattern (defaults to non-alpha as a regex) to convert to an array of strings. Use `Array.filter()` to remove any empty strings.
|
||||
Omit the second argument to use the default regex.
|
||||
|
||||
```js
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||

|
||||
|
||||
# 30 seconds of code [](https://gitter.im/30-seconds-of-code/Lobby) [](https://travis-ci.org/Chalarangelo/30-seconds-of-code)
|
||||
# 30 seconds of code
|
||||
[](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [](https://gitter.im/30-seconds-of-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [](https://github.com/Flet/semistandard)
|
||||
|
||||
> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less.
|
||||
|
||||
|
||||
|
||||
@ -17,12 +17,45 @@
|
||||
</head>
|
||||
<script>
|
||||
const search = (node) => {
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => x.style.display = x.getAttribute("href").toUpperCase().indexOf(node.value.toUpperCase()) + 1 ? '' : 'none');
|
||||
var remove = false, childs = Array.from(node.parentElement.parentElement.children), toRemove = childs[0];
|
||||
Array.from(node.parentElement.parentElement.children).forEach(x => x.tagName == 'H3' ? (toRemove.style.display = (remove ? 'none' : ''), toRemove = x, remove = true) : (x.style.display == '' ? remove = false : remove=remove));
|
||||
// Hide non-query-matching snippets
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => {
|
||||
x.style.display = x.getAttribute("href").toUpperCase().indexOf(node.value.toUpperCase()) + 1 ? '' : 'none'
|
||||
});
|
||||
Array.from( node.parentElement.parentElement.children )
|
||||
// Filter out the hidden links
|
||||
.filter( x => !( x.tagName == 'A' && x.style.display == 'none' ) )
|
||||
// set the display for each element based on if it's a H3
|
||||
// If it's the last element and an H3, hide it
|
||||
// Otherwise if it's and H3 and the next element is an H3, hide it
|
||||
// Otherwise display it
|
||||
.forEach( ( element, index, source) => {
|
||||
element.style.display = (element.tagName == 'H3' && index + 1 == source.length ? 'none' : element.tagName == 'H3' && source[index + 1].tagName == 'H3' ? 'none' : '')
|
||||
})
|
||||
}
|
||||
function clipboard() {
|
||||
const snippets = document.querySelectorAll("pre");
|
||||
snippets.forEach(element => {
|
||||
const button = document.createElement("button");
|
||||
button.innerHTML = "Copy to clipboard";
|
||||
element.parentElement.appendChild(button);
|
||||
|
||||
button.addEventListener ("click", function() {
|
||||
//The following regex removes all the comments from the snippet
|
||||
const text = element.textContent.replace(/\/\*(.|[\r\n])*?\*\//g, '').replace(/\/\/.*/gm, '');
|
||||
// Apparently you can't copy a variable to clipboard so you need to create text input element,
|
||||
// give it a value, copy it and then remove it from DOM.
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = text.trim();
|
||||
document.body.appendChild(textArea);
|
||||
console.log(textArea.innerText);
|
||||
textArea.select();
|
||||
document.execCommand("Copy");
|
||||
document.body.removeChild(textArea);
|
||||
});
|
||||
});
|
||||
};
|
||||
</script>
|
||||
<body>
|
||||
<body onload="clipboard()">
|
||||
<a href="https://github.com/Chalarangelo/30-seconds-of-code" class="github-corner" aria-label="View source on Github"><svg width="90" height="90" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
|
||||
<header style="height: 5.5rem;">
|
||||
<h1 class="logo" href="https://github.com/Chalarangelo/30-seconds-of-code"><img src="favicon.png" style="height: 4rem;"/><span id="title"> 30 seconds of code</span>
|
||||
|
||||
13
tag_database
13
tag_database
@ -7,6 +7,7 @@ arrayMin:array
|
||||
arraySum:math
|
||||
arrayToHtmlList:browser
|
||||
bottomVisible:browser
|
||||
call:adapter
|
||||
capitalize:string
|
||||
capitalizeEveryWord:string
|
||||
chainAsync:function
|
||||
@ -16,6 +17,7 @@ cleanObj:object
|
||||
coalesce:utility
|
||||
coalesceFactory:utility
|
||||
collatz:math
|
||||
collectInto:adapter
|
||||
compact:array
|
||||
compose:function
|
||||
countOccurrences:array
|
||||
@ -23,6 +25,7 @@ countVowels:string
|
||||
currentURL:browser
|
||||
curry:function
|
||||
deepFlatten:array
|
||||
detectDeviceType:browser
|
||||
difference:array
|
||||
differenceWith:array
|
||||
digitize:math
|
||||
@ -36,9 +39,12 @@ everyNth:array
|
||||
extendHex:utility
|
||||
factorial:math
|
||||
fibonacci:math
|
||||
fibonacciCountUntilNum:math
|
||||
fibonacciUntilNum:math
|
||||
filterNonUnique:array
|
||||
flatten:array
|
||||
flattenDepth:array
|
||||
flip:adapter
|
||||
fromCamelCase:string
|
||||
functionName:function
|
||||
gcd:math
|
||||
@ -73,6 +79,7 @@ last:array
|
||||
lcm:math
|
||||
mapObject:array
|
||||
median:math
|
||||
negate:logic
|
||||
nthElement:array
|
||||
objectFromPairs:object
|
||||
objectToPairs:object
|
||||
@ -83,7 +90,7 @@ pick:array
|
||||
pipe:function
|
||||
powerset:math
|
||||
primes:math
|
||||
promisify:function
|
||||
promisify:adapter
|
||||
pull:array
|
||||
pullAtIndex:array
|
||||
pullAtValue:array
|
||||
@ -92,6 +99,7 @@ randomNumberInRange:math
|
||||
readFileLines:node
|
||||
redirect:browser
|
||||
remove:array
|
||||
repeatString:string
|
||||
reverseString:string
|
||||
RGBToHex:utility
|
||||
round:math
|
||||
@ -105,6 +113,7 @@ similarity:array
|
||||
sleep:function
|
||||
sortCharactersInString:string
|
||||
speechSynthesis:media
|
||||
spreadOver:adapter
|
||||
standardDeviation:math
|
||||
symmetricDifference:array
|
||||
tail:array
|
||||
@ -114,7 +123,9 @@ timeTaken:utility
|
||||
toCamelCase:string
|
||||
toDecimalMark:utility
|
||||
toEnglishDate:date
|
||||
toKebabCase:string
|
||||
toOrdinalSuffix:utility
|
||||
toSnakeCase:string
|
||||
truncateString:string
|
||||
truthCheckCollection:object
|
||||
union:array
|
||||
|
||||
Reference in New Issue
Block a user