diff --git a/docs/about.html b/docs/about.html new file mode 100644 index 000000000..5cdc41d1d --- /dev/null +++ b/docs/about.html @@ -0,0 +1,128 @@ + + + + + + + + About - 30 seconds of code + + + + + + + + + + + + + +
+

logo 30 + seconds of code + Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. +

+
+
+
+

+

Our philosophy

+

The core goal of 30 seconds of code is to provide a quality resource for beginner and advanced JavaScript developers alike. We want to help improve the JavaScript ecosystem, by lowering the barrier of entry for newcomers and help seasoned veterans pick up new tricks and remember old ones. In order to achieve this, we have collected hundreds of snippets that can be of use in a wide range of situations. We welcome new contributors and we like fresh ideas, as long as the code is short and easy to grasp in about 30 seconds. The only catch, if you may, is that a few of our snippets are not perfectly optimized for large, enterprise applications and they might not be deemed production-ready.


+

Related projects

+

The idea behind 30 seconds of code has inspired some people to create similar collections in other programming languages and environments. Here are the ones we like the most:

+
+

Maintainers

+
+
+ +
+
+
+ fejes713 + Stefan Fejes +
+
+
+
+ flxwu + Felix Wu +
+
+
+
+ atomiks + atomiks +
+
+
+ +
+
+

Past maintainers

+
+
+ +
+ +
+
+ iamsoorena + Soorena +
+
+

License

+

In order for 30 seconds of code to be as accessible and useful as + possible, all of the snippets in the collection are licensed under the CC0-1.0 + License, meaning they are absolutely free to use in any project you like. If you like what we do, you can + always credit us, but that is not mandatory.


+
+ +
+ + + + diff --git a/docs/adapter.html b/docs/adapter.html index 14a90f377..3f765a68c 100644 --- a/docs/adapter.html +++ b/docs/adapter.html @@ -1,6 +1,6 @@ -Adapter - 30 seconds of codeAdapter - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

ary

Creates a function that accepts up to n arguments, ignoring any additional arguments.

Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
-
const firstTwoMax = ary(Math.max, 2);
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Adapter

intermediate

ary

Creates a function that accepts up to n arguments, ignoring any additional arguments.

Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
+
const firstTwoMax = ary(Math.max, 2);
 [[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]
-

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.

const call = (key, ...args) => context => context[key](...args);
-
Promise.resolve([1, 2, 3])
+
intermediate

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.

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 ]
-

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.

const collectInto = fn => (...args) => fn(args);
-
const Pall = collectInto(Promise.all.bind(Promise));
+
intermediate

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.

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); // [1, 2, 3] (after about 2 seconds)
-

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.

const flip = fn => (first, ...rest) => fn(...rest, first);
-
let a = { name: 'John Smith' };
+
intermediate

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.

const flip = fn => (first, ...rest) => fn(...rest, first);
+
let a = { name: 'John Smith' };
 let b = {};
 const mergeFrom = flip(Object.assign);
 let mergePerson = mergeFrom.bind(null, a);
 mergePerson(b); // == b
 b = {};
 Object.assign(b, a); // == b
-

over

Creates a function that invokes each provided function with the arguments it receives and returns the results.

Use Array.map() and Function.apply() to apply each function to the given arguments.

const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));
-
const minMax = over(Math.min, Math.max);
+
intermediate

over

Creates a function that invokes each provided function with the arguments it receives and returns the results.

Use Array.map() and Function.apply() to apply each function to the given arguments.

const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));
+
const minMax = over(Math.min, Math.max);
 minMax(1, 2, 3, 4, 5); // [1,5]
-

overArgs

Creates a function that invokes the provided function with its arguments transformed.

Use Array.map() to apply transforms to args in combination with the spread operator (...) to pass the transformed arguments to fn.

const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));
-
const square = n => n * n;
+
intermediate

overArgs

Creates a function that invokes the provided function with its arguments transformed.

Use Array.map() to apply transforms to args in combination with the spread operator (...) to pass the transformed arguments to fn.

const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));
+
const square = n => n * n;
 const double = n => n * 2;
 const fn = overArgs((x, y) => [x, y], [square, double]);
 fn(9, 3); // [81, 6]
-

pipeAsyncFunctions

Performs left-to-right function composition for asynchronous functions.

Use Array.reduce() with the spread operator (...) to perform left-to-right function composition using Promise.then(). The functions can return a combination of: simple values, Promise's, or they can be defined as async ones returning through await. All functions must be unary.

const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
-
const sum = pipeAsyncFunctions(
+
intermediate

pipeAsyncFunctions

Performs left-to-right function composition for asynchronous functions.

Use Array.reduce() with the spread operator (...) to perform left-to-right function composition using Promise.then(). The functions can return a combination of: simple values, Promise's, or they can be defined as async ones returning through await. All functions must be unary.

const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
+
const sum = pipeAsyncFunctions(
   x => x + 1,
   x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
   x => x + 3,
@@ -122,28 +116,28 @@ Object.assig
 (async () => {
   console.log(await sum(5)); // 15 (after one second)
 })();
-

pipeFunctions

Performs left-to-right function composition.

Use Array.reduce() with the spread operator (...) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.

const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
-
const add5 = x => x + 5;
+
intermediate

pipeFunctions

Performs left-to-right function composition.

Use Array.reduce() with the spread operator (...) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.

const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
+
const add5 = x => x + 5;
 const multiply = (x, y) => x * y;
 const multiplyAndAdd5 = pipeFunctions(multiply, add5);
 multiplyAndAdd5(5, 2); // 15
-

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

const promisify = func => (...args) =>
+
intermediate

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

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));
+
const delay = promisify((d, cb) => setTimeout(cb, d));
 delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s
-

rearg

Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.

Use Array.map() to reorder arguments based on indexes in combination with the spread operator (...) to pass the transformed arguments to fn.

const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));
-
var rearged = rearg(
+
intermediate

rearg

Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.

Use Array.map() to reorder arguments based on indexes in combination with the spread operator (...) to pass the transformed arguments to fn.

const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));
+
var rearged = rearg(
   function(a, b, c) {
     return [a, b, c];
   },
   [2, 0, 1]
 );
 rearged('b', 'c', 'a'); // ['a', 'b', 'c']
-

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.

const spreadOver = fn => argsArr => fn(...argsArr);
-
const arrayMax = spreadOver(Math.max);
+
intermediate

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.

const spreadOver = fn => argsArr => fn(...argsArr);
+
const arrayMax = spreadOver(Math.max);
 arrayMax([1, 2, 3]); // 3
-

unary

Creates a function that accepts up to one argument, ignoring any additional arguments.

Call the provided function, fn, with just the first argument given.

const unary = fn => val => fn(val);
-
['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10]
-
\ No newline at end of file +
intermediate

unary

Creates a function that accepts up to one argument, ignoring any additional arguments.

Call the provided function, fn, with just the first argument given.

const unary = fn => val => fn(val);
+
['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10]
+
\ No newline at end of file diff --git a/docs/archive.html b/docs/archive.html index 66b918536..a12072190 100644 --- a/docs/archive.html +++ b/docs/archive.html @@ -1,8 +1,22 @@ -Snippets Archive - 30 seconds of codeSnippets Archive - 30 seconds of code

logo 30 seconds of code

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

Snippets Archive

These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.


binarySearch

Use recursion. Similar to Array.indexOf() that finds the index of a value within an array. The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or Array.indexOf().

Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return -1.

const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Snippets Archive

These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.


binarySearch

Use recursion. Similar to Array.indexOf() that finds the index of a value within an array. The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or Array.indexOf().

Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return -1.

const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
   if (start > end) return -1;
   const mid = Math.floor((start + end) / 2);
   if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);
   if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);
   return mid;
 };
-
binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2
+
binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2
 binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1
-

cleanObj

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 included in given array. If you pass a special key,childIndicator, it will search deeply apply the function to inner objects, too.

const cleanObj = (obj, keysToKeep = [], childIndicator) => {
+

cleanObj

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 included in given array. If you pass a special key,childIndicator, it will search deeply apply the function to inner objects, too.

const cleanObj = (obj, keysToKeep = [], childIndicator) => {
   Object.keys(obj).forEach(key => {
     if (key === childIndicator) {
       cleanObj(obj[key], keysToKeep, childIndicator);
@@ -75,14 +92,14 @@
   });
   return obj;
 };
-
const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };
+
const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };
 cleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}
-

collatz

Applies the Collatz algorithm.

If n is even, return n/2. Otherwise, return 3n+1.

const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
-
collatz(8); // 4
-

countVowels

Retuns number of vowels in provided string.

Use a regular expression to count the number of vowels (A, E, I, O, U) in a string.

const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
-
countVowels('foobar'); // 3
+

collatz

Applies the Collatz algorithm.

If n is even, return n/2. Otherwise, return 3n+1.

const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
+
collatz(8); // 4
+

countVowels

Retuns number of vowels in provided string.

Use a regular expression to count the number of vowels (A, E, I, O, U) in a string.

const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
+
countVowels('foobar'); // 3
 countVowels('gym'); // 0
-

factors

Returns the array of factors of the given num. If the second argument is set to true returns only the prime factors of num. If num is 1 or 0 returns an empty array. If num is less than 0 returns all the factors of -int together with their additive inverses.

Use Array.from(), Array.map() and Array.filter() to find all the factors of num. If given num is negative, use Array.reduce() to add the additive inverses to the array. Return all results if primes is false, else determine and return only the prime factors using isPrime and Array.filter(). Omit the second argument, primes, to return prime and non-prime factors by default.

Note:- Negative numbers are not considered prime.

const factors = (num, primes = false) => {
+

factors

Returns the array of factors of the given num. If the second argument is set to true returns only the prime factors of num. If num is 1 or 0 returns an empty array. If num is less than 0 returns all the factors of -int together with their additive inverses.

Use Array.from(), Array.map() and Array.filter() to find all the factors of num. If given num is negative, use Array.reduce() to add the additive inverses to the array. Return all results if primes is false, else determine and return only the prime factors using isPrime and Array.filter(). Omit the second argument, primes, to return prime and non-prime factors by default.

Note:- Negative numbers are not considered prime.

const factors = (num, primes = false) => {
   const isPrime = num => {
     const boundary = Math.floor(Math.sqrt(num));
     for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
@@ -101,22 +118,22 @@
     }, []);
   return primes ? array.filter(isPrime) : array;
 };
-
factors(12); // [2,3,4,6,12]
+
factors(12); // [2,3,4,6,12]
 factors(12, true); // [2,3]
 factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]
 factors(-12, true); // [2,3]
-

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.

const fibonacciCountUntilNum = num =>
+

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.

const fibonacciCountUntilNum = num =>
   Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
-
fibonacciCountUntilNum(10); // 7
-

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.

const fibonacciUntilNum = num => {
+
fibonacciCountUntilNum(10); // 7
+

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.

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(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
-

howManyTimes

Returns the number of times num can be divided by divisor (integer or fractional) without getting a fractional answer. Works for both negative and positive integers.

If divisor is -1 or 1 return Infinity. If divisor is -0 or 0 return 0. Otherwise, keep dividing num with divisor and incrementing i, while the result is an integer. Return the number of times the loop was executed, i.

const howManyTimes = (num, divisor) => {
+
fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
+

howManyTimes

Returns the number of times num can be divided by divisor (integer or fractional) without getting a fractional answer. Works for both negative and positive integers.

If divisor is -1 or 1 return Infinity. If divisor is -0 or 0 return 0. Otherwise, keep dividing num with divisor and incrementing i, while the result is an integer. Return the number of times the loop was executed, i.

const howManyTimes = (num, divisor) => {
   if (divisor === 1 || divisor === -1) return Infinity;
   if (divisor === 0) return 0;
   let i = 0;
@@ -126,21 +143,21 @@
   }
   return i;
 };
-
howManyTimes(100, 2); // 2
+
howManyTimes(100, 2); // 2
 howManyTimes(100, 2.5); // 2
 howManyTimes(100, 0); // 0
 howManyTimes(100, -1); // Infinity
-

httpDelete

Makes a DELETE request to the passed URL.

Use XMLHttpRequest web api to make a delete request to the given url. Handle the onload event, by running the provided callback function. Handle the onerror event, by running the provided err function. Omit the third argument, err to log the request to the console's error stream by default.

const httpDelete = (url, callback, err = console.error) => {
+

httpDelete

Makes a DELETE request to the passed URL.

Use XMLHttpRequest web api to make a delete request to the given url. Handle the onload event, by running the provided callback function. Handle the onerror event, by running the provided err function. Omit the third argument, err to log the request to the console's error stream by default.

const httpDelete = (url, callback, err = console.error) => {
   const request = new XMLHttpRequest();
   request.open("DELETE", url, true);
   request.onload = () => callback(request);
   request.onerror = () => err(request);
   request.send();
 };
-
httpDelete('https://website.com/users/123', request => {
+
httpDelete('https://website.com/users/123', request => {
   console.log(request.responseText);
 }); // 'Deletes a user from the database'
-

httpPut

Makes a PUT request to the passed URL.

Use XMLHttpRequest web api to make a put request to the given url. Set the value of an HTTP request header with setRequestHeader method. Handle the onload event, by running the provided callback function. Handle the onerror event, by running the provided err function. Omit the last argument, err to log the request to the console's error stream by default.

const httpPut = (url, data, callback, err = console.error) => {
+

httpPut

Makes a PUT request to the passed URL.

Use XMLHttpRequest web api to make a put request to the given url. Set the value of an HTTP request header with setRequestHeader method. Handle the onload event, by running the provided callback function. Handle the onerror event, by running the provided err function. Omit the last argument, err to log the request to the console's error stream by default.

const httpPut = (url, data, callback, err = console.error) => {
     const request = new XMLHttpRequest();
     request.open("PUT", url, true);
     request.setRequestHeader('Content-type','application/json; charset=utf-8');
@@ -148,29 +165,29 @@
     request.onerror = () => err(request);
     request.send(data);
 };
-
const password = "fooBaz";
+
const password = "fooBaz";
 const data = JSON.stringify(password);
 httpPut('https://website.com/users/123', data, request => {
   console.log(request.responseText);
 }); // 'Updates a user's password in database'
-

isArmstrongNumber

Checks if the given number is an Armstrong number or not.

Convert the given number into an array of digits. Use the exponent operator (**) 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.

const isArmstrongNumber = digits =>
+

isArmstrongNumber

Checks if the given number is an Armstrong number or not.

Convert the given number into an array of digits. Use the exponent operator (**) 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.

const isArmstrongNumber = digits =>
   (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
     (digits + '').split('')
   );
-
isArmstrongNumber(1634); // true
+
isArmstrongNumber(1634); // true
 isArmstrongNumber(56); // false
-

isSimilar

Determines if the pattern matches with str.

Use String.toLowerCase() to convert both strings to lowercase, then loop through str and determine if it contains all characters of pattern and in the correct order. Adapted from here.

const isSimilar = (pattern, str) =>
+

isSimilar

Determines if the pattern matches with str.

Use String.toLowerCase() to convert both strings to lowercase, then loop through str and determine if it contains all characters of pattern and in the correct order. Adapted from here.

const isSimilar = (pattern, str) =>
 	[...str].reduce(
 		(matchIndex, char) => char.toLowerCase() === (pattern[matchIndex]  || '').toLowerCase() ? matchIndex + 1 : matchIndex, 0
 	) === pattern.length ? true : false;
-
isSimilar('rt','Rohit'); // true
+
isSimilar('rt','Rohit'); // true
 isSimilar('tr','Rohit'); // false
-

JSONToDate

Converts a JSON object to a date.

Use Date(), to convert dates in JSON format to readable format (dd/mm/yyyy).

const JSONToDate = arr => {
+

JSONToDate

Converts a JSON object to a date.

Use Date(), to convert dates in JSON format to readable format (dd/mm/yyyy).

const JSONToDate = arr => {
   const dt = new Date(parseInt(arr.toString().substr(6)));
   return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
 };
-
JSONToDate(/Date(1489525200000)/); // "14/3/2017"
-

levenshteinDistance

Calculates the Levenshtein distance between two strings.

Calculates the number of changes (substitutions, deletions or additions) required to convert string1 to string2. Can also be used to compare two strings as shown in the second example.

const levenshteinDistance = (string1, string2) => {
+
JSONToDate(/Date(1489525200000)/); // "14/3/2017"
+

levenshteinDistance

Calculates the Levenshtein distance between two strings.

Calculates the number of changes (substitutions, deletions or additions) required to convert string1 to string2. Can also be used to compare two strings as shown in the second example.

const levenshteinDistance = (string1, string2) => {
     if(string1.length === 0) return string2.length;
     if(string2.length === 0) return string1.length;
     let matrix = Array(string2.length + 1).fill(0).map((x,i) => [i]);
@@ -187,10 +204,10 @@
     }
     return matrix[string2.length][string1.length];
 };
-
levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7
+
levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7
 const compareStrings = (string1,string2) => (100 - levenshteinDistance(string1,string2) / Math.max(string1.length,string2.length));
 compareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)
-

quickSort

QuickSort an Array (ascending sort by default).

Use recursion. Use Array.filter and spread operator (...) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. If the parameter desc is truthy, return array sorts in descending order.

const quickSort = ([n, ...nums], desc) =>
+

quickSort

QuickSort an Array (ascending sort by default).

Use recursion. Use Array.filter and spread operator (...) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. If the parameter desc is truthy, return array sorts in descending order.

const quickSort = ([n, ...nums], desc) =>
   isNaN(n)
     ? []
     : [
@@ -198,12 +215,12 @@
         n,
         ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
       ];
-
quickSort([4, 1, 3, 2]); // [1,2,3,4]
+
quickSort([4, 1, 3, 2]); // [1,2,3,4]
 quickSort([4, 1, 3, 2], true); // [4,3,2,1]
-

removeVowels

Returns all the vowels in a str replaced by repl.

Use String.replace() with a regexp to replace all vowels in str. Omot repl to use a default value of ''.

const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl);
-
removeVowels("foobAr"); // "fbr"
+

removeVowels

Returns all the vowels in a str replaced by repl.

Use String.replace() with a regexp to replace all vowels in str. Omot repl to use a default value of ''.

const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl);
+
removeVowels("foobAr"); // "fbr"
 removeVowels("foobAr","*"); // "f**b*r"
-

solveRPN

Solves the given mathematical expression in reverse polish notation. Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- +,-,*,/,^,** (^&** are the exponential symbols and are same). This snippet does not supports any unary operators.

Use a dictionary, OPERATORS to specify each operator's matching mathematical operation. Use String.replace() with a regular expression to replace ^ with **, String.split() to tokenize the string and Array.filter() to remove empty tokens. Use Array.forEach() to parse each symbol, evaluate it as a numeric value or operator and solve the mathematical expression. Numeric values are converted to floating point numbers and pushed to a stack, while operators are evaluated using the OPERATORS dictionary and pop elements from the stack to apply operations.

const solveRPN = rpn => {
+

solveRPN

Solves the given mathematical expression in reverse polish notation. Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- +,-,*,/,^,** (^&** are the exponential symbols and are same). This snippet does not supports any unary operators.

Use a dictionary, OPERATORS to specify each operator's matching mathematical operation. Use String.replace() with a regular expression to replace ^ with **, String.split() to tokenize the string and Array.filter() to remove empty tokens. Use Array.forEach() to parse each symbol, evaluate it as a numeric value or operator and solve the mathematical expression. Numeric values are converted to floating point numbers and pushed to a stack, while operators are evaluated using the OPERATORS dictionary and pop elements from the stack to apply operations.

const solveRPN = rpn => {
   const OPERATORS = {
     '*': (a, b) => a * b,
     '+': (a, b) => a + b,
@@ -231,12 +248,12 @@
   if (stack.length === 1) return stack.pop();
   else throw `${rpn} is not a proper RPN. Please check it and try again`;
 };
-
solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
+
solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
 solveRPN('2 3 ^'); // 8
-

speechSynthesis

Performs speech synthesis (experimental).

Use SpeechSynthesisUtterance.voice and window.speechSynthesis.getVoices() to convert a message to speech. Use window.speechSynthesis.speak() to play the message.

Learn more about the SpeechSynthesisUtterance interface of the Web Speech API.

const speechSynthesis = message => {
+

speechSynthesis

Performs speech synthesis (experimental).

Use SpeechSynthesisUtterance.voice and window.speechSynthesis.getVoices() to convert a message to speech. Use window.speechSynthesis.speak() to play the message.

Learn more about the SpeechSynthesisUtterance interface of the Web Speech API.

const speechSynthesis = message => {
   const msg = new SpeechSynthesisUtterance(message);
   msg.voice = window.speechSynthesis.getVoices()[0];
   window.speechSynthesis.speak(msg);
 };
-
speechSynthesis('Hello, World'); // // plays the message
-

\ No newline at end of file +
speechSynthesis('Hello, World'); // // plays the message
+
\ No newline at end of file diff --git a/docs/beginner.html b/docs/beginner.html deleted file mode 100644 index f84bb8a41..000000000 --- a/docs/beginner.html +++ /dev/null @@ -1,150 +0,0 @@ -Snippets for Beginners - 30 seconds of code

logo 30 seconds of code

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

Snippets for Beginners

The following section is aimed towards individuals who are at the start of their web developer journey. Each snippet in the next section is simple yet very educational for newcomers. This section is by no means a complete resource for learning modern JavaScript. However, it is enough to grasp some common concepts and use cases. We also strongly recommend checking out MDN web docs as a learning resource.


allEqual

Check if all elements are equal

Use Array.every() to check if all the elements of the array are the same as the first one.

const allEqual = arr => arr.every(val => val === arr[0]);
-
allEqual([1, 2, 3, 4, 5, 6]); // false
-allEqual([1, 1, 1, 1]); // true
-

currentURL

Returns the current URL.

Use window.location.href to get current URL.

const currentURL = () => window.location.href;
-
currentURL(); // 'https://google.com'
-

everyNth

Returns every nth element in an array.

Use Array.filter() to create a new array that contains every nth element of a given array.

const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
-
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
-

factorial

Calculates the factorial of a number.

Use recursion. If n is less than or equal to 1, return 1. Otherwise, return the product of n and the factorial of n - 1. Throws an exception if n is a negative number.

const factorial = n =>
-  n < 0
-    ? (() => {
-        throw new TypeError('Negative numbers are not allowed!');
-      })()
-    : n <= 1
-      ? 1
-      : n * factorial(n - 1);
-
factorial(6); // 720
-

fibonacci

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.

const fibonacci = n =>
-  Array.from({ length: n }).reduce(
-    (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
-    []
-  );
-
fibonacci(6); // [0, 1, 1, 2, 3, 5]
-

filterNonUnique

Filters out the non-unique values in an array.

Use Array.filter() for an array containing only the unique values.

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
-
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5]
-

gcd

Calculates the greatest common divisor between two or more numbers/arrays.

The inner _gcd function uses recursion. Base case is when y equals 0. In this case, return x. Otherwise, return the GCD of y and the remainder of the division x/y.

const gcd = (...arr) => {
-  const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
-  return [...arr].reduce((a, b) => _gcd(a, b));
-};
-
gcd(8, 36); // 4
-gcd(...[12, 8, 32]); // 4
-

getMeridiemSuffixOfInteger

Converts an integer to a suffixed string, adding am or pm based on its value.

Use the modulo operator (%) and conditional checks to transform an integer to a stringified 12-hour format with meridiem suffix.

const getMeridiemSuffixOfInteger = num =>
-  num === 0 || num === 24
-    ? 12 + 'am'
-    : num === 12
-      ? 12 + 'pm'
-      : num < 12
-        ? (num % 12) + 'am'
-        : (num % 12) + 'pm';
-
getMeridiemSuffixOfInteger(0); // "12am"
-getMeridiemSuffixOfInteger(11); // "11am"
-getMeridiemSuffixOfInteger(13); // "1pm"
-getMeridiemSuffixOfInteger(25); // "1pm"
-

hasClass

Returns true if the element has the specified class, false otherwise.

Use element.classList.contains() to check if the element has the specified class.

const hasClass = (el, className) => el.classList.contains(className);
-
hasClass(document.querySelector('p.special'), 'special'); // true
-

isDivisible

Checks if the first numeric argument is divisible by the second one.

Use the modulo operator (%) to check if the remainder is equal to 0.

const isDivisible = (dividend, divisor) => dividend % divisor === 0;
-
isDivisible(6, 3); // true
-

isEven

Returns true if the given number is even, false otherwise.

Checks whether a number is odd or even using the modulo (%) operator. Returns true if the number is even, false if the number is odd.

const isEven = num => num % 2 === 0;
-
isEven(3); // false
-

isPrime

Checks if the provided integer is a prime number.

Check numbers from 2 to the square root of the given number. Return false if any of them divides the given number, else return true, unless the number is less than 2.

const isPrime = num => {
-  const boundary = Math.floor(Math.sqrt(num));
-  for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
-  return num >= 2;
-};
-
isPrime(11); // true
-

last

Returns the last element in an array.

Use arr.length - 1 to compute the index of the last element of the given array and returning it.

const last = arr => arr[arr.length - 1];
-
last([1, 2, 3]); // 3
-

lcm

Returns the least common multiple of two or more numbers.

Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. The GCD formula uses recursion.

const lcm = (...arr) => {
-  const gcd = (x, y) => (!y ? x : gcd(y, x % y));
-  const _lcm = (x, y) => (x * y) / gcd(x, y);
-  return [...arr].reduce((a, b) => _lcm(a, b));
-};
-
lcm(12, 7); // 84
-lcm(...[1, 3, 4, 5]); // 60
-

maxN

Returns the n maximum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in descending order).

Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
-
maxN([1, 2, 3]); // [3]
-maxN([1, 2, 3], 2); // [3,2]
-

minN

Returns the n minimum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in ascending order).

Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in ascending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
-
minN([1, 2, 3]); // [1]
-minN([1, 2, 3], 2); // [1,2]
-

nthElement

Returns the nth element of an array.

Use Array.slice() to get an array containing the nth element at the first place. If the index is out of bounds, return undefined. Omit the second argument, n, to get the first element of the array.

const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];
-
nthElement(['a', 'b', 'c'], 1); // 'b'
-nthElement(['a', 'b', 'b'], -3); // 'a'
-

offset

Moves the specified amount of elements to the end of the array.

Use Array.slice() twice to get the elements after the specified index and the elements before that. Use the spread operator(...) to combine the two into one array. If offset is negative, the elements will be moved from end to start.

const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];
-
offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
-offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]
-

randomIntegerInRange

Returns a random integer in the specified range.

Use Math.random() to generate a random number and map it to the desired range, using Math.floor() to make it an integer.

const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
-
randomIntegerInRange(0, 5); // 2
-

reverseString

Reverses a string.

Use the spread operator (...) and Array.reverse() to reverse the order of the characters in the string. Combine characters to get a string using String.join('').

const reverseString = str => [...str].reverse().join('');
-
reverseString('foobar'); // 'raboof'
-

sample

Returns a random element from an array.

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.

const sample = arr => arr[Math.floor(Math.random() * arr.length)];
-
sample([3, 7, 9, 11]); // 9
-

similarity

Returns an array of elements that appear in both arrays.

Use Array.filter() to remove values that are not part of values, determined using Array.includes().

const similarity = (arr, values) => arr.filter(v => values.includes(v));
-
similarity([1, 2, 3], [1, 2, 4]); // [1,2]
-

sum

Returns the sum of two or more numbers/arrays.

Use Array.reduce() to add each value to an accumulator, initialized with a value of 0.

const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
-
sum(...[1, 2, 3, 4]); // 10
-

tail

Returns all elements in an array except for the first one.

Return Array.slice(1) if the array's length is more than 1, otherwise, return the whole array.

const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
-
tail([1, 2, 3]); // [2,3]
-tail([1]); // [1]
-

truncateString

Truncates a string up to a specified length.

Determine if the string's length is greater than num. Return the string truncated to the desired length, with '...' appended to the end or the original string.

const truncateString = (str, num) =>
-  str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
-
truncateString('boomerang', 7); // 'boom...'
-

\ No newline at end of file diff --git a/docs/browser.html b/docs/browser.html index 8105f2f04..1e14397dd 100644 --- a/docs/browser.html +++ b/docs/browser.html @@ -1,6 +1,6 @@ -Browser - 30 seconds of codeBrowser - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Browser

arrayToHtmlList

Converts the given array elements into <li> tags and appends them to the list of the given id.

Use Array.map(), document.querySelector(), and an anonymous inner closure to create a list of html tags.

const arrayToHtmlList = (arr, listID) =>
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Browser

intermediate

arrayToHtmlList

Converts the given array elements into <li> tags and appends them to the list of the given id.

Use Array.map(), document.querySelector(), and an anonymous inner closure to create a list of html tags.

const arrayToHtmlList = (arr, listID) =>
   (el => (
     (el = document.querySelector('#' + listID)),
     (el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))
   ))();
-
arrayToHtmlList(['item 1', 'item 2'], 'myListID');
-

bottomVisible

Returns true if the bottom of the page is visible, false otherwise.

Use scrollY, scrollHeight and clientHeight to determine if the bottom of the page is visible.

const bottomVisible = () =>
+
arrayToHtmlList(['item 1', 'item 2'], 'myListID');
+
intermediate

bottomVisible

Returns true if the bottom of the page is visible, false otherwise.

Use scrollY, scrollHeight and clientHeight to determine if the bottom of the page is visible.

const bottomVisible = () =>
   document.documentElement.clientHeight + window.scrollY >=
   (document.documentElement.scrollHeight || document.documentElement.clientHeight);
-
bottomVisible(); // true
-

copyToClipboardadvanced

⚠️ NOTICE: The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it here.

Copy a string to the clipboard. Only works as a result of user action (i.e. inside a click event listener).

Create a new <textarea> element, fill it with the supplied data and add it to the HTML document. Use Selection.getRangeAt()to store the selected range (if any). Use document.execCommand('copy') to copy to the clipboard. Remove the <textarea> element from the HTML document. Finally, use Selection().addRange() to recover the original selected range (if any).

const copyToClipboard = str => {
+
bottomVisible(); // true
+
advanced

copyToClipboard

⚠️ NOTICE: The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it here.

Copy a string to the clipboard. Only works as a result of user action (i.e. inside a click event listener).

Create a new <textarea> element, fill it with the supplied data and add it to the HTML document. Use Selection.getRangeAt()to store the selected range (if any). Use document.execCommand('copy') to copy to the clipboard. Remove the <textarea> element from the HTML document. Finally, use Selection().addRange() to recover the original selected range (if any).

const copyToClipboard = str => {
   const el = document.createElement('textarea');
   el.value = str;
   el.setAttribute('readonly', '');
@@ -106,8 +100,8 @@
     document.getSelection().addRange(selected);
   }
 };
-
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
-

counteradvanced

Creates a counter with the specified range, step and duration for the specified selector.

Check if step has the proper sign and change it accordingly. Use setInterval() in combination with Math.abs() and Math.floor() to calculate the time between each new text draw. Use document.querySelector().innerHTML to update the value of the selected element. Omit the fourth parameter, step, to use a default step of 1. Omit the fifth parameter, duration, to use a default duration of 2000ms.

const counter = (selector, start, end, step = 1, duration = 2000) => {
+
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
+
advanced

counter

Creates a counter with the specified range, step and duration for the specified selector.

Check if step has the proper sign and change it accordingly. Use setInterval() in combination with Math.abs() and Math.floor() to calculate the time between each new text draw. Use document.querySelector().innerHTML to update the value of the selected element. Omit the fourth parameter, step, to use a default step of 1. Omit the fifth parameter, duration, to use a default duration of 2000ms.

const counter = (selector, start, end, step = 1, duration = 2000) => {
   let current = start,
     _step = (end - start) * step < 0 ? -step : step,
     timer = setInterval(() => {
@@ -118,19 +112,19 @@
     }, Math.abs(Math.floor(duration / (end - start))));
   return timer;
 };
-
counter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element with id="my-id"
-

createElement

Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.

Use document.createElement() to create a new element. Set its innerHTML to the string supplied as the argument. Use ParentNode.firstElementChild to return the element version of the string.

const createElement = str => {
+
counter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element with id="my-id"
+
intermediate

createElement

Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.

Use document.createElement() to create a new element. Set its innerHTML to the string supplied as the argument. Use ParentNode.firstElementChild to return the element version of the string.

const createElement = str => {
   const el = document.createElement('div');
   el.innerHTML = str;
   return el.firstElementChild;
 };
-
const el = createElement(
+
const el = createElement(
   `<div class="container">
     <p>Hello!</p>
   </div>`
 );
 console.log(el.className); // 'container'
-

createEventHubadvanced

Creates a pub/sub (publish–subscribe) event hub with emit, on, and off methods.

Use Object.create(null) to create an empty hub object that does not inherit properties from Object.prototype. For emit, resolve the array of handlers based on the event argument and then run each one with Array.forEach() by passing in the data as an argument. For on, create an array for the event if it does not yet exist, then use Array.push() to add the handler to the array. For off, use Array.findIndex() to find the index of the handler in the event array and remove it using Array.splice().

const createEventHub = () => ({
+
advanced

createEventHub

Creates a pub/sub (publish–subscribe) event hub with emit, on, and off methods.

Use Object.create(null) to create an empty hub object that does not inherit properties from Object.prototype. For emit, resolve the array of handlers based on the event argument and then run each one with Array.forEach() by passing in the data as an argument. For on, create an array for the event if it does not yet exist, then use Array.push() to add the handler to the array. For off, use Array.findIndex() to find the index of the handler in the event array and remove it using Array.splice().

const createEventHub = () => ({
   hub: Object.create(null),
   emit(event, data) {
     (this.hub[event] || []).forEach(handler => handler(data));
@@ -144,7 +138,7 @@ console.log<
     if (i > -1) this.hub[event].splice(i, 1);
   }
 });
-
const handler = data => console.log(data);
+
const handler = data => console.log(data);
 const hub = createEventHub();
 let increment = 0;
 
@@ -160,17 +154,17 @@ hub.emit// Unsubscribe: stop a specific handler from listening to the 'message' event
 hub.off('message', handler);
-

currentURL

Returns the current URL.

Use window.location.href to get current URL.

const currentURL = () => window.location.href;
-
currentURL(); // 'https://google.com'
-

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.

const detectDeviceType = () =>
+
beginner

currentURL

Returns the current URL.

Use window.location.href to get current URL.

const currentURL = () => window.location.href;
+
currentURL(); // 'https://google.com'
+
intermediate

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.

const detectDeviceType = () =>
   /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
     ? 'Mobile'
     : 'Desktop';
-
detectDeviceType(); // "Mobile" or "Desktop"
-

elementContains

Returns true if the parent element contains the child element, false otherwise.

Check that parent is not the same element as child, use parent.contains(child) to check if the parent element contains the child element.

const elementContains = (parent, child) => parent !== child && parent.contains(child);
-
elementContains(document.querySelector('head'), document.querySelector('title')); // true
+
detectDeviceType(); // "Mobile" or "Desktop"
+
intermediate

elementContains

Returns true if the parent element contains the child element, false otherwise.

Check that parent is not the same element as child, use parent.contains(child) to check if the parent element contains the child element.

const elementContains = (parent, child) => parent !== child && parent.contains(child);
+
elementContains(document.querySelector('head'), document.querySelector('title')); // true
 elementContains(document.querySelector('body'), document.querySelector('body')); // false
-

elementIsVisibleInViewport

Returns true if the element specified is visible in the viewport, false otherwise.

Use Element.getBoundingClientRect() and the window.inner(Width|Height) values to determine if a given element is visible in the viewport. Omit the second argument to determine if the element is entirely visible, or specify true to determine if it is partially visible.

const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
+
intermediate

elementIsVisibleInViewport

Returns true if the element specified is visible in the viewport, false otherwise.

Use Element.getBoundingClientRect() and the window.inner(Width|Height) values to determine if a given element is visible in the viewport. Omit the second argument to determine if the element is entirely visible, or specify true to determine if it is partially visible.

const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
   const { top, left, bottom, right } = el.getBoundingClientRect();
   const { innerHeight, innerWidth } = window;
   return partiallyVisible
@@ -178,19 +172,19 @@ hub.off((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
     : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
 };
-
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
+
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
 elementIsVisibleInViewport(el); // false - (not fully visible)
 elementIsVisibleInViewport(el, true); // true - (partially visible)
-

getScrollPosition

Returns the scroll position of the current page.

Use pageXOffset and pageYOffset if they are defined, otherwise scrollLeft and scrollTop. You can omit el to use a default value of window.

const getScrollPosition = (el = window) => ({
+
intermediate

getScrollPosition

Returns the scroll position of the current page.

Use pageXOffset and pageYOffset if they are defined, otherwise scrollLeft and scrollTop. You can omit el to use a default value of window.

const getScrollPosition = (el = window) => ({
   x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
   y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
 });
-
getScrollPosition(); // {x: 0, y: 200}
-

getStyle

Returns the value of a CSS rule for the specified element.

Use Window.getComputedStyle() to get the value of the CSS rule for the specified element.

const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
-
getStyle(document.querySelector('p'), 'font-size'); // '16px'
-

hasClass

Returns true if the element has the specified class, false otherwise.

Use element.classList.contains() to check if the element has the specified class.

const hasClass = (el, className) => el.classList.contains(className);
-
hasClass(document.querySelector('p.special'), 'special'); // true
-

hashBrowseradvanced

Creates a hash for a value using the SHA-256 algorithm. Returns a promise.

Use the SubtleCrypto API to create a hash for the given value.

const hashBrowser = val =>
+
getScrollPosition(); // {x: 0, y: 200}
+
intermediate

getStyle

Returns the value of a CSS rule for the specified element.

Use Window.getComputedStyle() to get the value of the CSS rule for the specified element.

const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
+
getStyle(document.querySelector('p'), 'font-size'); // '16px'
+
beginner

hasClass

Returns true if the element has the specified class, false otherwise.

Use element.classList.contains() to check if the element has the specified class.

const hasClass = (el, className) => el.classList.contains(className);
+
hasClass(document.querySelector('p.special'), 'special'); // true
+
advanced

hashBrowser

Creates a hash for a value using the SHA-256 algorithm. Returns a promise.

Use the SubtleCrypto API to create a hash for the given value.

const hashBrowser = val =>
   crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => {
     let hexes = [],
       view = new DataView(h);
@@ -198,22 +192,22 @@ hub.off.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
     return hexes.join('');
   });
-
hashBrowser(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
-

hide

Hides all the elements specified.

Use NodeList.prototype.forEach() to apply display: none to each element specified.

const hide = els => els.forEach(e => (e.style.display = 'none'));
-
hide(document.querySelectorAll('img')); // Hides all <img> elements on the page
-

httpsRedirect

Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.

Use location.protocol to get the protocol currently being used. If it's not HTTPS, use location.replace() to replace the existing page with the HTTPS version of the page. Use location.href to get the full address, split it with String.split() and remove the protocol part of the URL.

const httpsRedirect = () => {
+
hashBrowser(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
+
intermediate

hide

Hides all the elements specified.

Use NodeList.prototype.forEach() to apply display: none to each element specified.

const hide = els => els.forEach(e => (e.style.display = 'none'));
+
hide(document.querySelectorAll('img')); // Hides all <img> elements on the page
+
intermediate

httpsRedirect

Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.

Use location.protocol to get the protocol currently being used. If it's not HTTPS, use location.replace() to replace the existing page with the HTTPS version of the page. Use location.href to get the full address, split it with String.split() and remove the protocol part of the URL.

const httpsRedirect = () => {
   if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
 };
-
httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com
-

insertAfter

Inserts an HTML string after the end of the specified element.

Use el.insertAdjacentHTML() with a position of 'afterend' to parse htmlString and insert it after the end of el.

const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
-
insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>
-

insertBefore

Inserts an HTML string before the start of the specified element.

Use el.insertAdjacentHTML() with a position of 'beforebegin' to parse htmlString and insert it before the start of el.

const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
-
insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>
-

isBrowserTabFocused

Returns true if the browser tab of the page is focused, false otherwise.

Use the Document.hidden property, introduced by the Page Visibility API to check if the browser tab of the page is visible or hidden.

const isBrowserTabFocused = () => !document.hidden;
-
isBrowserTabFocused(); // true
-

nodeListToArray

Converts a NodeList to an array.

Use spread operator inside new array to convert a NodeList to an array.

const nodeListToArray = nodeList => [...nodeList];
-
nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]
-

observeMutationsadvanced

Returns a new MutationObserver and runs the provided callback for each mutation on the specified element.

Use a MutationObserver to observe mutations on the given element. Use Array.forEach() to run the callback for each mutation that is observed. Omit the third argument, options, to use the default options (all true).

const observeMutations = (element, callback, options) => {
+
httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com
+
intermediate

insertAfter

Inserts an HTML string after the end of the specified element.

Use el.insertAdjacentHTML() with a position of 'afterend' to parse htmlString and insert it after the end of el.

const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
+
insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>
+
intermediate

insertBefore

Inserts an HTML string before the start of the specified element.

Use el.insertAdjacentHTML() with a position of 'beforebegin' to parse htmlString and insert it before the start of el.

const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
+
insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>
+
intermediate

isBrowserTabFocused

Returns true if the browser tab of the page is focused, false otherwise.

Use the Document.hidden property, introduced by the Page Visibility API to check if the browser tab of the page is visible or hidden.

const isBrowserTabFocused = () => !document.hidden;
+
isBrowserTabFocused(); // true
+
intermediate

nodeListToArray

Converts a NodeList to an array.

Use Array.prototype.slice() and Function.prototype.call() to convert a NodeList to an array.

const nodeListToArray = nodeList => Array.prototype.slice.call(nodeList);
+
nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]
+
advanced

observeMutations

Returns a new MutationObserver and runs the provided callback for each mutation on the specified element.

Use a MutationObserver to observe mutations on the given element. Use Array.forEach() to run the callback for each mutation that is observed. Omit the third argument, options, to use the default options (all true).

const observeMutations = (element, callback, options) => {
   const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m)));
   observer.observe(
     element,
@@ -231,22 +225,22 @@ hub.off
   return observer;
 };
-
const obs = observeMutations(document, console.log); // Logs all mutations that happen on the page
+
const obs = observeMutations(document, console.log); // Logs all mutations that happen on the page
 obs.disconnect(); // Disconnects the observer and stops logging mutations on the page
-

off

Removes an event listener from an element.

Use EventTarget.removeEventListener() to remove an event listener from an element. Omit the fourth argument opts to use false or specify it based on the options used when the event listener was added.

const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);
-
const fn = () => console.log('!');
+
intermediate

off

Removes an event listener from an element.

Use EventTarget.removeEventListener() to remove an event listener from an element. Omit the fourth argument opts to use false or specify it based on the options used when the event listener was added.

const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);
+
const fn = () => console.log('!');
 document.body.addEventListener('click', fn);
 off(document.body, 'click', fn); // no longer logs '!' upon clicking on the page
-

on

Adds an event listener to an element with the ability to use event delegation.

Use EventTarget.addEventListener() to add an event listener to an element. If there is a target property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct this context. Returns a reference to the custom delegator function, in order to be possible to use with off. Omit opts to default to non-delegation behavior and event bubbling.

const on = (el, evt, fn, opts = {}) => {
+
intermediate

on

Adds an event listener to an element with the ability to use event delegation.

Use EventTarget.addEventListener() to add an event listener to an element. If there is a target property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct this context. Returns a reference to the custom delegator function, in order to be possible to use with off. Omit opts to default to non-delegation behavior and event bubbling.

const on = (el, evt, fn, opts = {}) => {
   const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e);
   el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);
   if (opts.target) return delegatorFn;
 };
-
const fn = () => console.log('!');
+
const fn = () => console.log('!');
 on(document.body, 'click', fn); // logs '!' upon clicking the body
 on(document.body, 'click', fn, { target: 'p' }); // logs '!' upon clicking a `p` element child of the body
 on(document.body, 'click', fn, { options: true }); // use capturing instead of bubbling
-

onUserInputChangeadvanced

Run the callback whenever the user input type changes (mouse or touch). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops).

Use two event listeners. Assume mouse input initially and bind a touchstart event listener to the document. On touchstart, add a mousemove event listener to listen for two consecutive mousemove events firing within 20ms, using performance.now(). Run the callback with the input type as an argument in either of these situations.

const onUserInputChange = callback => {
+
advanced

onUserInputChange

Run the callback whenever the user input type changes (mouse or touch). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops).

Use two event listeners. Assume mouse input initially and bind a touchstart event listener to the document. On touchstart, add a mousemove event listener to listen for two consecutive mousemove events firing within 20ms, using performance.now(). Run the callback with the input type as an argument in either of these situations.

const onUserInputChange = callback => {
   let type = 'mouse',
     lastTime = 0;
   const mousemoveHandler = () => {
@@ -260,10 +254,10 @@ document.body= 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler);
   });
 };
-
onUserInputChange(type => {
+
onUserInputChange(type => {
   console.log('The user is now using', type, 'as an input method.');
 });
-

prefix

Returns the prefixed version (if necessary) of a CSS property that the browser supports.

Use Array.findIndex() on an array of vendor prefix strings to test if document.body has one of them defined in its CSSStyleDeclaration object, otherwise return null. Use String.charAt() and String.toUpperCase() to capitalize the property, which will be appended to the vendor prefix string.

const prefix = prop => {
+
intermediate

prefix

Returns the prefixed version (if necessary) of a CSS property that the browser supports.

Use Array.findIndex() on an array of vendor prefix strings to test if document.body has one of them defined in its CSSStyleDeclaration object, otherwise return null. Use String.charAt() and String.toUpperCase() to capitalize the property, which will be appended to the vendor prefix string.

const prefix = prop => {
   const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1);
   const prefixes = ['', 'webkit', 'moz', 'ms', 'o'];
   const i = prefixes.findIndex(
@@ -271,8 +265,8 @@ document.body);
   return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null;
 };
-
prefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance'
-

recordAnimationFrames

Invokes the provided callback on each animation frame.

Use recursion. Provided that running is true, continue invoking window.requestAnimationFrame() which invokes the provided callback. Return an object with two methods start and stop to allow manual control of the recording. Omit the second argument, autoStart, to implicitly call start when the function is invoked.

const recordAnimationFrames = (callback, autoStart = true) => {
+
prefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance'
+
intermediate

recordAnimationFrames

Invokes the provided callback on each animation frame.

Use recursion. Provided that running is true, continue invoking window.requestAnimationFrame() which invokes the provided callback. Return an object with two methods start and stop to allow manual control of the recording. Omit the second argument, autoStart, to implicitly call start when the function is invoked.

const recordAnimationFrames = (callback, autoStart = true) => {
   let running = true,
     raf;
   const stop = () => {
@@ -292,15 +286,15 @@ document.bodyif (autoStart) start();
   return { start, stop };
 };
-
const cb = () => console.log('Animation frame fired');
+
const cb = () => console.log('Animation frame fired');
 const recorder = recordAnimationFrames(cb); // logs 'Animation frame fired' on each animation frame
 recorder.stop(); // stops logging
 recorder.start(); // starts again
 const recorder2 = recordAnimationFrames(cb, false); // `start` needs to be explicitly called to begin recording frames
-

redirect

Redirects to a specified URL.

Use window.location.href or window.location.replace() to redirect to url. Pass a second argument to simulate a link click (true - default) or an HTTP redirect (false).

const redirect = (url, asLink = true) =>
+
intermediate

redirect

Redirects to a specified URL.

Use window.location.href or window.location.replace() to redirect to url. Pass a second argument to simulate a link click (true - default) or an HTTP redirect (false).

const redirect = (url, asLink = true) =>
   asLink ? (window.location.href = url) : window.location.replace(url);
-
redirect('https://google.com');
-

runAsyncadvanced

Runs a function in a separate thread by using a Web Worker, allowing long running functions to not block the UI.

Create a new Worker using a Blob object URL, the contents of which should be the stringified version of the supplied function. Immediately post the return value of calling the function back. Return a promise, listening for onmessage and onerror events and resolving the data posted back from the worker, or throwing an error.

const runAsync = fn => {
+
redirect('https://google.com');
+
advanced

runAsync

Runs a function in a separate thread by using a Web Worker, allowing long running functions to not block the UI.

Create a new Worker using a Blob object URL, the contents of which should be the stringified version of the supplied function. Immediately post the return value of calling the function back. Return a promise, listening for onmessage and onerror events and resolving the data posted back from the worker, or throwing an error.

const runAsync = fn => {
   const worker = new Worker(
     URL.createObjectURL(new Blob([`postMessage((${fn})());`]), {
       type: 'application/javascript; charset=utf-8'
@@ -315,7 +309,7 @@ recorder.sta
     };
   });
 };
-
const longRunningFunction = () => {
+
const longRunningFunction = () => {
   let result = 0;
   for (let i = 0; i < 1000; i++) {
     for (let j = 0; j < 700; j++) {
@@ -335,33 +329,33 @@ recorder.sta
 runAsync(() => 10 ** 3).then(console.log); // 1000
 let outsideVariable = 50;
 runAsync(() => typeof outsideVariable).then(console.log); // 'undefined'
-

scrollToTop

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 the top. Use window.requestAnimationFrame() to animate the scrolling.

const scrollToTop = () => {
+
intermediate

scrollToTop

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 the top. Use window.requestAnimationFrame() to animate the scrolling.

const scrollToTop = () => {
   const c = document.documentElement.scrollTop || document.body.scrollTop;
   if (c > 0) {
     window.requestAnimationFrame(scrollToTop);
     window.scrollTo(0, c - c / 8);
   }
 };
-
scrollToTop();
-

setStyle

Sets the value of a CSS rule for the specified element.

Use element.style to set the value of the CSS rule for the specified element to val.

const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
-
setStyle(document.querySelector('p'), 'font-size', '20px'); // The first <p> element on the page will have a font-size of 20px
-

show

Shows all the elements specified.

Use the spread operator (...) and Array.forEach() to clear the display property for each element specified.

const show = (...el) => [...el].forEach(e => (e.style.display = ''));
-
show(...document.querySelectorAll('img')); // Shows all <img> elements on the page
-

smoothScroll

Smoothly scrolls the element on which it's called into the visible area of the browser window.

Use .scrollIntoView method to scroll the element. Pass { behavior: 'smooth' } to .scrollIntoView so it scrolls smoothly.

const smoothScroll = element =>
+
scrollToTop();
+
intermediate

setStyle

Sets the value of a CSS rule for the specified element.

Use element.style to set the value of the CSS rule for the specified element to val.

const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
+
setStyle(document.querySelector('p'), 'font-size', '20px'); // The first <p> element on the page will have a font-size of 20px
+
intermediate

show

Shows all the elements specified.

Use the spread operator (...) and Array.forEach() to clear the display property for each element specified.

const show = (...el) => [...el].forEach(e => (e.style.display = ''));
+
show(...document.querySelectorAll('img')); // Shows all <img> elements on the page
+
intermediate

smoothScroll

Smoothly scrolls the element on which it's called into the visible area of the browser window.

Use .scrollIntoView method to scroll the element. Pass { behavior: 'smooth' } to .scrollIntoView so it scrolls smoothly.

const smoothScroll = element =>
   document.querySelector(element).scrollIntoView({
     behavior: 'smooth'
   });
-
smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar
+
smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar
 smoothScroll('.fooBar'); // scrolls smoothly to the first element with a class of fooBar
-

toggleClass

Toggle a class for an element.

Use element.classList.toggle() to toggle the specified class for the element.

const toggleClass = (el, className) => el.classList.toggle(className);
-
toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore
-

triggerEvent

Triggers a specific event on a given element, optionally passing custom data.

Use new CustomEvent() to create an event from the specified eventType and details. Use el.dispatchEvent() to trigger the newly created event on the given element. Omit the third argument, detail, if you do not want to pass custom data to the triggered event.

const triggerEvent = (el, eventType, detail = undefined) =>
+
intermediate

toggleClass

Toggle a class for an element.

Use element.classList.toggle() to toggle the specified class for the element.

const toggleClass = (el, className) => el.classList.toggle(className);
+
toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore
+
intermediate

triggerEvent

Triggers a specific event on a given element, optionally passing custom data.

Use new CustomEvent() to create an event from the specified eventType and details. Use el.dispatchEvent() to trigger the newly created event on the given element. Omit the third argument, detail, if you do not want to pass custom data to the triggered event.

const triggerEvent = (el, eventType, detail = undefined) =>
   el.dispatchEvent(new CustomEvent(eventType, { detail: detail }));
-
triggerEvent(document.getElementById('myId'), 'click');
+
triggerEvent(document.getElementById('myId'), 'click');
 triggerEvent(document.getElementById('myId'), 'click', { username: 'bob' });
-

UUIDGeneratorBrowser

Generates a UUID in a browser.

Use crypto API to generate a UUID, compliant with RFC4122 version 4.

const UUIDGeneratorBrowser = () =>
+
intermediate

UUIDGeneratorBrowser

Generates a UUID in a browser.

Use crypto API to generate a UUID, compliant with RFC4122 version 4.

const UUIDGeneratorBrowser = () =>
   ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
     (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
   );
-
UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
-
\ No newline at end of file +
UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
+
\ No newline at end of file diff --git a/docs/contributing.html b/docs/contributing.html new file mode 100644 index 000000000..a3b47913b --- /dev/null +++ b/docs/contributing.html @@ -0,0 +1,79 @@ + + + + + + + + Contributing - 30 seconds of code + + + + + + + + + + + + + +
+

logo 30 + seconds of code + Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. +

+
+
+
+

+

How to contribute

+

Do you have a cool idea for a new snippet? Maybe some code you use often and is not part of our collection? Contributing to 30 seconds of code is as simple as 1,2,3,4!


+

1. Create

+

Start by creating a snippet, according to the snippet template. Make sure to follow these simple guidelines:

+
+

2. Tag

+

Run npm run tagger from your terminal, then open the tag_database file and tag your snippet appropriately. Multitagging is also supported, just make sure the first tag you specify is on of the major tags and the one that is most relevant to the implemented function.


+

3. Test

+

You can optionally test your snippet to make our job easier. Simply run npm run tester to generate the test files for your snippet. Find the related folder for you snippet under the test directory and write some tests. Remember to run npm run tester again to make sure your tests are passing.


+

4. Pull request

+

If you have done everything mentioned above, you should now have an awesome snippet to add to our collection. Simply start a pull request and follow the guidelines provided. Remember to only submit one snippet per pull request, so that we can quickly evaluate and merge your code into the collection.


+
+ +
+ + + + diff --git a/docs/date.html b/docs/date.html index 62132e292..0c6fd899b 100644 --- a/docs/date.html +++ b/docs/date.html @@ -1,6 +1,6 @@ -Date - 30 seconds of codeDate - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Date

formatDuration

Returns the human readable format of the given number of milliseconds.

Divide ms with the appropriate values to obtain the appropriate values for day, hour, minute, second and millisecond. Use Object.entries() with Array.filter() to keep only non-zero values. Use Array.map() to create the string for each value, pluralizing appropriately. Use String.join(', ') to combine the values into a string.

const formatDuration = ms => {
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Date

intermediate

formatDuration

Returns the human readable format of the given number of milliseconds.

Divide ms with the appropriate values to obtain the appropriate values for day, hour, minute, second and millisecond. Use Object.entries() with Array.filter() to keep only non-zero values. Use Array.map() to create the string for each value, pluralizing appropriately. Use String.join(', ') to combine the values into a string.

const formatDuration = ms => {
   if (ms < 0) ms = -ms;
   const time = {
     day: Math.floor(ms / 86400000),
@@ -93,14 +87,14 @@
     .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
     .join(', ');
 };
-
formatDuration(1001); // '1 second, 1 millisecond'
+
formatDuration(1001); // '1 second, 1 millisecond'
 formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
-

getColonTimeFromDate

Returns a string of the form HH:MM:SS from a Date object.

Use Date.toString() and String.slice() to get the HH:MM:SS part of a given Date object.

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
-
getColonTimeFromDate(new Date()); // "08:38:00"
-

getDaysDiffBetweenDates

Returns the difference (in days) between two dates.

Calculate the difference (in days) between two Date objects.

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
+
intermediate

getColonTimeFromDate

Returns a string of the form HH:MM:SS from a Date object.

Use Date.toString() and String.slice() to get the HH:MM:SS part of a given Date object.

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
+
getColonTimeFromDate(new Date()); // "08:38:00"
+
intermediate

getDaysDiffBetweenDates

Returns the difference (in days) between two dates.

Calculate the difference (in days) between two Date objects.

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
   (dateFinal - dateInitial) / (1000 * 3600 * 24);
-
getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9
-

getMeridiemSuffixOfInteger

Converts an integer to a suffixed string, adding am or pm based on its value.

Use the modulo operator (%) and conditional checks to transform an integer to a stringified 12-hour format with meridiem suffix.

const getMeridiemSuffixOfInteger = num =>
+
getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9
+
beginner

getMeridiemSuffixOfInteger

Converts an integer to a suffixed string, adding am or pm based on its value.

Use the modulo operator (%) and conditional checks to transform an integer to a stringified 12-hour format with meridiem suffix.

const getMeridiemSuffixOfInteger = num =>
   num === 0 || num === 24
     ? 12 + 'am'
     : num === 12
@@ -108,11 +102,11 @@
       : num < 12
         ? (num % 12) + 'am'
         : (num % 12) + 'pm';
-
getMeridiemSuffixOfInteger(0); // "12am"
+
getMeridiemSuffixOfInteger(0); // "12am"
 getMeridiemSuffixOfInteger(11); // "11am"
 getMeridiemSuffixOfInteger(13); // "1pm"
 getMeridiemSuffixOfInteger(25); // "1pm"
-

tomorrow

Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.

const tomorrow = (long = false) => {
+
intermediate

tomorrow

Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.

const tomorrow = (long = false) => {
   let t = new Date();
   t.setDate(t.getDate() + 1);
   const ret = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
@@ -120,6 +114,6 @@
   ).padStart(2, '0')}`;
   return !long ? ret : `${ret}T00:00:00`;
 };
-
tomorrow(); // 2017-12-27 (if current date is 2017-12-26)
+
tomorrow(); // 2017-12-27 (if current date is 2017-12-26)
 tomorrow(true); // 2017-12-27T00:00:00 (if current date is 2017-12-26)
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/function.html b/docs/function.html index 8ed5254cf..4a479fc68 100644 --- a/docs/function.html +++ b/docs/function.html @@ -1,6 +1,6 @@ -Function - 30 seconds of codeFunction - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Function

attempt

Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.

Use a try... catch block to return either the result of the function or an appropriate error.

const attempt = (fn, ...args) => {
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Function

intermediate

attempt

Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.

Use a try... catch block to return either the result of the function or an appropriate error.

const attempt = (fn, ...args) => {
   try {
     return fn(...args);
   } catch (e) {
     return e instanceof Error ? e : new Error(e);
   }
 };
-
var elements = attempt(function(selector) {
+
var elements = attempt(function(selector) {
   return document.querySelectorAll(selector);
 }, '>_>');
 if (elements instanceof Error) elements = []; // elements = []
-

bind

Creates a function that invokes fn with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.

Return a function that uses Function.apply() to apply the given context to fn. Use Array.concat() to prepend any additional supplied parameters to the arguments.

const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);
-
function greet(greeting, punctuation) {
+
intermediate

bind

Creates a function that invokes fn with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.

Return a function that uses Function.apply() to apply the given context to fn. Use Array.concat() to prepend any additional supplied parameters to the arguments.

const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);
+
function greet(greeting, punctuation) {
   return greeting + ' ' + this.user + punctuation;
 }
 const freddy = { user: 'fred' };
 const freddyBound = bind(greet, freddy);
 console.log(freddyBound('hi', '!')); // 'hi fred!'
-

bindKey

Creates a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.

Return a function that uses Function.apply() to bind context[fn] to context. Use the spread operator (...) to prepend any additional supplied parameters to the arguments.

const bindKey = (context, fn, ...boundArgs) => (...args) =>
+
intermediate

bindKey

Creates a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.

Return a function that uses Function.apply() to bind context[fn] to context. Use the spread operator (...) to prepend any additional supplied parameters to the arguments.

const bindKey = (context, fn, ...boundArgs) => (...args) =>
   context[fn].apply(context, [...boundArgs, ...args]);
-
const freddy = {
+
const freddy = {
   user: 'fred',
   greet: function(greeting, punctuation) {
     return greeting + ' ' + this.user + punctuation;
@@ -107,12 +101,12 @@ console.log<
 };
 const freddyBound = bindKey(freddy, 'greet');
 console.log(freddyBound('hi', '!')); // 'hi fred!'
-

chainAsync

Chains asynchronous functions.

Loop through an array of functions containing asynchronous events, calling next when each asynchronous event has completed.

const chainAsync = fns => {
+
intermediate

chainAsync

Chains asynchronous functions.

Loop through an array of functions containing asynchronous events, calling next when each asynchronous event has completed.

const chainAsync = fns => {
   let curr = 0;
   const next = () => fns[curr++](next);
   next();
 };
-
chainAsync([
+
chainAsync([
   next => {
     console.log('0 seconds');
     setTimeout(next, 1000);
@@ -121,67 +115,67 @@ console.log<
     console.log('1 second');
   }
 ]);
-

compose

Performs right-to-left function composition.

Use Array.reduce() to perform right-to-left function composition. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.

const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
-
const add5 = x => x + 5;
+
intermediate

compose

Performs right-to-left function composition.

Use Array.reduce() to perform right-to-left function composition. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.

const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
+
const add5 = x => x + 5;
 const multiply = (x, y) => x * y;
 const multiplyAndAdd5 = compose(
   add5,
   multiply
 );
 multiplyAndAdd5(5, 2); // 15
-

composeRight

Performs left-to-right function composition.

Use Array.reduce() to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.

const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
-
const add = (x, y) => x + y;
+
intermediate

composeRight

Performs left-to-right function composition.

Use Array.reduce() to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.

const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
+
const add = (x, y) => x + y;
 const square = x => x * x;
 const addAndSquare = composeRight(add, square);
 addAndSquare(1, 2); // 9
-

converge

Accepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function.

Use Array.map() and Function.apply() to apply each function to the given arguments. Use the spread operator (...) to call coverger with the results of all other functions.

const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args)));
-
const average = converge((a, b) => a / b, [
+
intermediate

converge

Accepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function.

Use Array.map() and Function.apply() to apply each function to the given arguments. Use the spread operator (...) to call coverger with the results of all other functions.

const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args)));
+
const average = converge((a, b) => a / b, [
   arr => arr.reduce((a, v) => a + v, 0),
   arr => arr.length
 ]);
 average([1, 2, 3, 4, 5, 6, 7]); // 4
-

curry

Curries a function.

Use recursion. If the number of provided arguments (args) is sufficient, call the passed function fn. Otherwise, return a curried function fn 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.

const curry = (fn, arity = fn.length, ...args) =>
+
intermediate

curry

Curries a function.

Use recursion. If the number of provided arguments (args) is sufficient, call the passed function fn. Otherwise, return a curried function fn 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.

const curry = (fn, arity = fn.length, ...args) =>
   arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
-
curry(Math.pow)(2)(10); // 1024
+
curry(Math.pow)(2)(10); // 1024
 curry(Math.min, 3)(10)(50)(2); // 2
-

debounce

Creates a debounced function that delays invoking the provided function until at least ms milliseconds have elapsed since the last time it was invoked.

Each time the debounced function is invoked, clear the current pending timeout with clearTimeout() and use setTimeout() to create a new timeout that delays invoking the function until at least ms milliseconds has elapsed. Use Function.apply() to apply the this context to the function and provide the necessary arguments. Omit the second argument, ms, to set the timeout at a default of 0 ms.

const debounce = (fn, ms = 0) => {
+
intermediate

debounce

Creates a debounced function that delays invoking the provided function until at least ms milliseconds have elapsed since the last time it was invoked.

Each time the debounced function is invoked, clear the current pending timeout with clearTimeout() and use setTimeout() to create a new timeout that delays invoking the function until at least ms milliseconds has elapsed. Use Function.apply() to apply the this context to the function and provide the necessary arguments. Omit the second argument, ms, to set the timeout at a default of 0 ms.

const debounce = (fn, ms = 0) => {
   let timeoutId;
   return function(...args) {
     clearTimeout(timeoutId);
     timeoutId = setTimeout(() => fn.apply(this, args), ms);
   };
 };
-
window.addEventListener(
+
window.addEventListener(
   'resize',
   debounce(() => {
     console.log(window.innerWidth);
     console.log(window.innerHeight);
   }, 250)
 ); // Will log the window dimensions at most every 250ms
-

defer

Defers invoking a function until the current call stack has cleared.

Use setTimeout() with a timeout of 1ms to add a new event to the browser event queue and allow the rendering engine to complete its work. Use the spread (...) operator to supply the function with an arbitrary number of arguments.

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
-
// Example A:
+
intermediate

defer

Defers invoking a function until the current call stack has cleared.

Use setTimeout() with a timeout of 1ms to add a new event to the browser event queue and allow the rendering engine to complete its work. Use the spread (...) operator to supply the function with an arbitrary number of arguments.

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
+
// Example A:
 defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
 
 // Example B:
 document.querySelector('#someElement').innerHTML = 'Hello';
 longRunningFunction(); //Browser will not update the HTML until this has finished
 defer(longRunningFunction); // Browser will update the HTML then run the function
-

delay

Invokes the provided function after wait milliseconds.

Use setTimeout() to delay execution of fn. Use the spread (...) operator to supply the function with an arbitrary number of arguments.

const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
-
delay(
+
intermediate

delay

Invokes the provided function after wait milliseconds.

Use setTimeout() to delay execution of fn. Use the spread (...) operator to supply the function with an arbitrary number of arguments.

const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
+
delay(
   function(text) {
     console.log(text);
   },
   1000,
   'later'
 ); // Logs 'later' after one second.
-

functionName

Logs the name of a function.

Use console.debug() and the name property of the passed method to log the method's name to the debug channel of the console.

const functionName = fn => (console.debug(fn.name), fn);
-
functionName(Math.max); // max (logged in debug channel of console)
-

hz

Returns the number of times a function executed per second. hz is the unit for hertz, the unit of frequency defined as one cycle per second.

Use performance.now() to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function iterations times. Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed. Omit the second argument, iterations, to use the default of 100 iterations.

const hz = (fn, iterations = 100) => {
+
intermediate

functionName

Logs the name of a function.

Use console.debug() and the name property of the passed method to log the method's name to the debug channel of the console.

const functionName = fn => (console.debug(fn.name), fn);
+
functionName(Math.max); // max (logged in debug channel of console)
+
intermediate

hz

Returns the number of times a function executed per second. hz is the unit for hertz, the unit of frequency defined as one cycle per second.

Use performance.now() to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function iterations times. Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed. Omit the second argument, iterations, to use the default of 100 iterations.

const hz = (fn, iterations = 100) => {
   const before = performance.now();
   for (let i = 0; i < iterations; i++) fn();
   return (1000 * iterations) / (performance.now() - before);
 };
-
// 10,000 element array
+
// 10,000 element array
 const numbers = Array(10000)
   .fill()
   .map((_, i) => i);
@@ -197,7 +191,7 @@ document.que
 // `sumForLoop` is nearly 10 times faster
 Math.round(hz(sumReduce)); // 572
 Math.round(hz(sumForLoop)); // 4784
-

memoize

Returns the memoized (cached) function.

Create an empty cache by instantiating a new Map object. Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. The function keyword must be used in order to allow the memoized function to have its this context changed if necessary. Allow access to the cache by setting it as a property on the returned function.

const memoize = fn => {
+
intermediate

memoize

Returns the memoized (cached) function.

Create an empty cache by instantiating a new Map object. Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. The function keyword must be used in order to allow the memoized function to have its this context changed if necessary. Allow access to the cache by setting it as a property on the returned function.

const memoize = fn => {
   const cache = new Map();
   const cached = function(val) {
     return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
@@ -205,14 +199,14 @@ Math.round.cache = cache;
   return cached;
 };
-
// See the `anagrams` snippet.
+
// See the `anagrams` snippet.
 const anagramsCached = memoize(anagrams);
 anagramsCached('javascript'); // takes a long time
 anagramsCached('javascript'); // returns virtually instantly since it's now cached
 console.log(anagramsCached.cache); // The cached anagrams map
-

negate

Negates a predicate function.

Take a predicate function and apply the not operator (!) to it with its arguments.

const negate = func => (...args) => !func(...args);
-
[1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]
-

once

Ensures a function is called only once.

Utilizing a closure, use a flag, called, and set it to true once the function is called for the first time, preventing it from being called again. In order to allow the function to have its this context changed (such as in an event listener), the function keyword must be used, and the supplied function must have the context applied. Allow the function to be supplied with an arbitrary number of arguments using the rest/spread (...) operator.

const once = fn => {
+
intermediate

negate

Negates a predicate function.

Take a predicate function and apply the not operator (!) to it with its arguments.

const negate = func => (...args) => !func(...args);
+
[1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]
+
intermediate

once

Ensures a function is called only once.

Utilizing a closure, use a flag, called, and set it to true once the function is called for the first time, preventing it from being called again. In order to allow the function to have its this context changed (such as in an event listener), the function keyword must be used, and the supplied function must have the context applied. Allow the function to be supplied with an arbitrary number of arguments using the rest/spread (...) operator.

const once = fn => {
   let called = false;
   return function(...args) {
     if (called) return;
@@ -220,28 +214,28 @@ console.log<
     return fn.apply(this, args);
   };
 };
-
const startApp = function(event) {
+
const startApp = function(event) {
   console.log(this, event); // document.body, MouseEvent
 };
 document.body.addEventListener('click', once(startApp)); // only runs `startApp` once upon click
-

partial

Creates a function that invokes fn with partials prepended to the arguments it receives.

Use the spread operator (...) to prepend partials to the list of arguments of fn.

const partial = (fn, ...partials) => (...args) => fn(...partials, ...args);
-
const greet = (greeting, name) => greeting + ' ' + name + '!';
+
intermediate

partial

Creates a function that invokes fn with partials prepended to the arguments it receives.

Use the spread operator (...) to prepend partials to the list of arguments of fn.

const partial = (fn, ...partials) => (...args) => fn(...partials, ...args);
+
const greet = (greeting, name) => greeting + ' ' + name + '!';
 const greetHello = partial(greet, 'Hello');
 greetHello('John'); // 'Hello John!'
-

partialRight

Creates a function that invokes fn with partials appended to the arguments it receives.

Use the spread operator (...) to append partials to the list of arguments of fn.

const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials);
-
const greet = (greeting, name) => greeting + ' ' + name + '!';
+
intermediate

partialRight

Creates a function that invokes fn with partials appended to the arguments it receives.

Use the spread operator (...) to append partials to the list of arguments of fn.

const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials);
+
const greet = (greeting, name) => greeting + ' ' + name + '!';
 const greetJohn = partialRight(greet, 'John');
 greetJohn('Hello'); // 'Hello John!'
-

runPromisesInSeries

Runs an array of promises in series.

Use Array.reduce() to create a promise chain, where each promise returns the next promise when resolved.

const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
-
const delay = d => new Promise(r => setTimeout(r, d));
+
intermediate

runPromisesInSeries

Runs an array of promises in series.

Use Array.reduce() to create a promise chain, where each promise returns the next promise when resolved.

const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
+
const delay = d => new Promise(r => setTimeout(r, d));
 runPromisesInSeries([() => delay(1000), () => delay(2000)]); // Executes each promise sequentially, taking a total of 3 seconds to complete
-

sleep

Delays the execution of an asynchronous function.

Delay executing part of an async function, by putting it to sleep, returning a Promise.

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
-
async function sleepyWork() {
+
intermediate

sleep

Delays the execution of an asynchronous function.

Delay executing part of an async function, by putting it to sleep, returning a Promise.

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+
async function sleepyWork() {
   console.log("I'm going to sleep for 1 second.");
   await sleep(1000);
   console.log('I woke up after 1 second.');
 }
-

throttle

Creates a throttled function that only invokes the provided function at most once per every wait milliseconds

Use setTimeout() and clearTimeout() to throttle the given method, fn. Use Function.apply() to apply the this context to the function and provide the necessary arguments. Use Date.now() to keep track of the last time the throttled function was invoked. Omit the second argument, wait, to set the timeout at a default of 0 ms.

const throttle = (fn, wait) => {
+
intermediate

throttle

Creates a throttled function that only invokes the provided function at most once per every wait milliseconds

Use setTimeout() and clearTimeout() to throttle the given method, fn. Use Function.apply() to apply the this context to the function and provide the necessary arguments. Use Date.now() to keep track of the last time the throttled function was invoked. Omit the second argument, wait, to set the timeout at a default of 0 ms.

const throttle = (fn, wait) => {
   let inThrottle, lastFn, lastTime;
   return function() {
     const context = this,
@@ -261,38 +255,38 @@ document.bodyShow examples
window.addEventListener(
+
window.addEventListener(
   'resize',
   throttle(function(evt) {
     console.log(window.innerWidth);
     console.log(window.innerHeight);
   }, 250)
 ); // Will log the window dimensions at most every 250ms
-

times

Iterates over a callback n times

Use Function.call() to call fn n times or until it returns false. Omit the last argument, context, to use an undefined object (or the global object in non-strict mode).

const times = (n, fn, context = undefined) => {
+
intermediate

times

Iterates over a callback n times

Use Function.call() to call fn n times or until it returns false. Omit the last argument, context, to use an undefined object (or the global object in non-strict mode).

const times = (n, fn, context = undefined) => {
   let i = 0;
   while (fn.call(context, i) !== false && ++i < n) {}
 };
-
var output = '';
+
var output = '';
 times(5, i => (output += i));
 console.log(output); // 01234
-

uncurry

Uncurries a function up to depth n.

Return a variadic function. Use Array.reduce() on the provided arguments to call each subsequent curry level of the function. If the length of the provided arguments is less than n throw an error. Otherwise, call fn with the proper amount of arguments, using Array.slice(0, n). Omit the second argument, n, to uncurry up to depth 1.

const uncurry = (fn, n = 1) => (...args) => {
+
intermediate

uncurry

Uncurries a function up to depth n.

Return a variadic function. Use Array.reduce() on the provided arguments to call each subsequent curry level of the function. If the length of the provided arguments is less than n throw an error. Otherwise, call fn with the proper amount of arguments, using Array.slice(0, n). Omit the second argument, n, to uncurry up to depth 1.

const uncurry = (fn, n = 1) => (...args) => {
   const next = acc => args => args.reduce((x, y) => x(y), acc);
   if (n > args.length) throw new RangeError('Arguments too few!');
   return next(fn)(args.slice(0, n));
 };
-
const add = x => y => z => x + y + z;
+
const add = x => y => z => x + y + z;
 const uncurriedAdd = uncurry(add, 3);
 uncurriedAdd(1, 2, 3); // 6
-

unfold

Builds an array, using an iterator function and an initial seed value.

Use a while loop and Array.push() to call the function repeatedly until it returns false. The iterator function accepts one argument (seed) and must always return an array with two elements ([value, nextSeed]) or false to terminate.

const unfold = (fn, seed) => {
+
intermediate

unfold

Builds an array, using an iterator function and an initial seed value.

Use a while loop and Array.push() to call the function repeatedly until it returns false. The iterator function accepts one argument (seed) and must always return an array with two elements ([value, nextSeed]) or false to terminate.

const unfold = (fn, seed) => {
   let result = [],
     val = [null, seed];
   while ((val = fn(val[1]))) result.push(val[0]);
   return result;
 };
-
var f = n => (n > 50 ? false : [-n, n + 10]);
+
var f = n => (n > 50 ? false : [-n, n + 10]);
 unfold(f, 10); // [-10, -20, -30, -40, -50]
-

when

Tests a value, x, against a predicate function. If true, return fn(x). Else, return x.

Return a function expecting a single value, x, that returns the appropriate value based on pred.

const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x);
-
const doubleEvenNumbers = when(x => x % 2 === 0, x => x * 2);
+
intermediate

when

Tests a value, x, against a predicate function. If true, return fn(x). Else, return x.

Return a function expecting a single value, x, that returns the appropriate value based on pred.

const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x);
+
const doubleEvenNumbers = when(x => x % 2 === 0, x => x * 2);
 doubleEvenNumbers(2); // 4
 doubleEvenNumbers(1); // 1
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/glossary.html b/docs/glossary.html new file mode 100644 index 000000000..7ff357814 --- /dev/null +++ b/docs/glossary.html @@ -0,0 +1,76 @@ +Glossary - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Glossary

Developers use a lot of terminology daily. Every once in a while, you might find a term you do not know. We know how frustrating that can get, so we provide you with a handy glossary of frequently used web development terms.


AJAX

Asynchronous JavaScript and XML (known as AJAX) is a term that describes a new approach to using multiple technologies together in order to enable web applications to make quick updates to the user interface without reloading the entire browser page.

API

API stands for Application Programming Interface and is a set of features and rules provided by a provided by a software to enable third-party software to interact with it. The code features of a web API usually include methods, properties, events or URLs.

Argument

An argument is a value passed as an input to a function and can be either a primitive or an object. In JavaScript, functions can also be passed as arguments to other functions.

Array

Arrays are used to store multiple values in a single variable. Arrays are ordered and each item in an array has a numeric index associated with it. JavaScript arrays are zero-indexed, meaning the first element's index is 0.

Asynchronous programming

Asynchronous programming is a way to allow multiple events to trigger code without waiting for each other. The main benefits of asynchronous programming are improved application performance and responsiveness.

Automatic semicolon insertion

Automatic semicolon insertion (ASI) is a JavaScript feature that allows developers to omit semicolons in their code.

Boolean

Booleans are one of the primitive data types in JavaScript. They represent logical data values and can only be true or false.

Callback

A callback function, also known as a high-order function, is a function that is passed into another function as an argument, which is then executed inside the outer function. Callbacks can be synchronous or asynchronous.

Character encoding

A character encoding defines a mapping between bytes and text, specifying how the sequenece of bytes should be interpreted. Two commonly used character encodings are ASCII and UTF-8.

Class

In object-oriented programming, a class is a template definition of an object's properties and methods.

Closure

A closure is the combination of a function and the lexical environment within which that function was declared. The closure allows a function to access the contents of that environment.

CoffeeScript

CoffeeScript is a programming language inspired by Ruby, Python and Haskell that transpiles to JavaScript.

Constant

A constant is a value, associated with an identifier. The value of a constant can be accessed using the identifier and cannot be altered during execution.

Constructor

In class-based object-oriented programming, a constructor is a special type of function called to instantiate an object. Constructors often accept arguments that are commonly used to set member properties.

Continuous Deployment

Continuous Deployment follows the testing that happens during Continuous Integration and pushes changes to a staging or production system. Continuous Deployment ensures that a version of the codebase is accessible at all times.

Continuous Integration

Continuous Integration (CI) is the practice of testing each change done to a codebase automatically and as early as possible. Two popular CI systems that integrate with GitHub are Travis CI and Circle CI.

CORS

Cross-Origin Resource Sharing (known as CORS) is a mechanism that uses extra HTTP headers to tell a browser to let a web application running at one domain have permission to access resources from a server at a different domain.

Cross-site scripting (XSS)

XSS refers to client-side code injection where the attacker injects malicious scripts into a legitimate website or web application. This is often achieved when the application does not validate user input and freely injects dynamic HTML content.

CSS

CSS stands for Cascading Style Sheets and is a language used to style web pages. CSS documents are plaintext documents structured with rules, which consist of element selectors and property-value pairs that apply the styles to the specified selectors.

CSV

CSV stands for Comma-Separated Values and is a storage format for tabular data. CSV documents are plaintext documents where each line represents a table row, with table columns separated by commas or some other delimiter (e.g. semicolons). The first line of a CSV document sometimes consists of the table column headings for the data to follow.

Currying

Currying is a way of constructing functions that allows partial application of a function's arguments. Practically, this means that a function is broken down into a series of functions, each one accepting part of the arguments.

Deserialization

Deserialization is the process of converting a format that has been transferred over a network and/or used for storage to an object or data structure. A common type of deserialization in JavaScript is the conversion of JSON string into an object.

DNS

A DNS (Domain Name System) translates domain names to the IP addresses needed to find a particular computer service on a network.

DOM

The DOM (Document Object Model) is a cross-platform API that treats HTML and XML documents as a tree structure consisting of nodes. These nodes (such as elements and text nodes) are objects that can be programmatically manipulated and any visible changes made to them are reflected live in the document. In a browser, this API is available to JavaScript where DOM nodes can be manipulated to change their styles, contents, placement in the document, or interacted with through event listeners.

Domain name registrar

A domain name registrar is a company that manages the reservation of internet domain names. A domain name registrar must be approved by a general top-level domain (gTLD) registry or a country code top-level domain (ccTLD) registry.

Domain name

A domain name is a website's address on the Internet, used primarily in URLs to identify the server for each webpage. A domain name consists of a hierarchical sequence of names, separated by dots and ending with an extension.

Element

A JavaScript representation of a DOM element commonly returned by document.querySelector() and document.createElement(). They are used when creating content with JavaScript for display in the DOM that needs to be programatically generated.

ES6

ES6 stands for ECMAScript 6 (also known as ECMAScript 2015), a version of the ECMAScript specification that standardizes JavaScript. ES6 adds a wide variety of new features to the specification, such as classes, promises, generators and arrow functions.

Event-driven programming

Event-driven programming is a programming paradigm in which the flow of the program is determined by events (e.g. user actions, thread messages, sensor outputs). In event-driven applications, there is usually a main loop that listens for events and trigger callback functions accordingly when one of these events is detected.

Event loop

The event loop handles all asynchronous callbacks. Callbacks are queued in a loop, while other code runs, and will run one by one when the response for each one has been received. The event loop allows JavaScript to perform non-blocking I/O operations, despite the fact that JavaScript is single-threaded.

Express

Express is a backend framework, that provides a layer of fundamental web application features for Node.js. Some of its key features are routing, middleware, template engines and error handling.

Factory functions

In JavaScript, a factory function is any function, which is not a class or constructor, that returns a new object. Factory functions don't require the use of the new keyword.

First-class function

A programming language is said to have first-class functions if it treats them as first-class citizens, meaning they can be passed as arguments, be returned as values from other functions, be assigned to variables and stored in data structures.

Flexbox

Flexbox is a one-dimensional layout model used to style websites as a property that could advance space distribution between items and provide powerful alignment capabilities.

Function

Functions are self-contained blocks of code with their own scope, that can be called by other code and are usually associated with a unique identifier. Functions accept input in the form of arguments and can optionally return an output (if no return statement is present, the default value of undefined will be returned instead). JavaScript functions are also objects.

Functional programming

Functional programming is a paradigm in which programs are built in a declarative manner using pure functions that avoid shared state and mutable data. Functions that always return the same value for the same input and don't produce side effects are the pillar of functional programming.

Functor

A Functor is a data type common in functional programming that implements a map method. The map method takes a function and applies it to the data in the Functor, returning a new instance of the Functor with the result. JavaScript Arrays are an example of the Functor data type.

Garbage collection

Garbage collection is a form of automatic memory management. It attempts to reclaim memory occupied by objects that are no longer used by the program.

Git

Git is an open-source version control system, used for source code management. Git allows users to copy (clone) and edit code on their local machines, before merging it into the main code base (master repository).

Higher-order function

Higher-order functions are functions that either take other functions as arguments, return a function as a result, or both.

Hoisting

Hoisting is JavaScript's default behavior of adding declarations to memory during the compile phase. Hoisting allows for JavaScript variables to be used before the line they were declared on.

HTML

HTML stands for HyperText Markup Language and is a language used to structure web pages. HTML documents are plaintext documents structured with elements, which are surrounded by <> tags and optionally extended with attributes.

HTTP and HTTPS

The HyperText Transfer Protocol (HTTP) is the underlying network protocol that enables transfer of hypermedia documents on the Web, usually between a client and a server. The HyperText Transfer Protocol Secure (HTTPS) is an encrypted version of the HTTP protocol, that uses SSL to encrypt all data transfered between a client and a server.

Integer

Integers are one of the primitive data types in Javascript. They represent a numerical value that has no fractional component.

Integration testing

Integration testing is a type of software testing, used to test groups of units/components of a software. The purpose of integration tests are to validate that the units/components interact with each other as expected.

IP

An IP address is a number assigned to a device connected to a network that uses the Internet protocol. Two IP versions are currently in use - IPv4, the older version of the communication protocol (e.g. 192.168.1.100) and IPv6, the newest version of the communication protocol which allows for many different IP addresses (e.g. 0:0:0:0:ffff:c0a8:164).

jQuery

jQuery is a frontend JavaScript library, that simplifies DOM manipulation, AJAX calls and Event handling. jQuery uses its globally defined function, $(), to select and manipulate DOM elements.

JSON

JSON (JavaScript Object Notation) is a format for storing and exchanging data. It closely resembles the JavaScript object syntax, however some data types, such as dates and functions, cannot be natively represented and need to be serialized first.

ajax api argument array asynchronous-programming automatic-semicolon-insertion boolean callback character-encoding class closure coffeescript constant constructor continuous-deployment continuous-integration cors cross-site-scripting-xss css csv currying deserialization dns dom domain-name-registrar domain-name element es6 event-driven-programming event-loop express factory-functions first-class-function flexbox function functional-programming functor garbage-collection git higher-order-function hoisting html http-and-https integer integration-testing ip jquery json keyword_database mdn module mongodb mutabe-value mvc node-js nosql npm object-oriented-programming object prepared-statements promise prototype-based-programming pseudo-class pseudo-element pwa react readme recursion regular-expressions repository responsive-web-design scope selector seo serialization sql-injection sql ssl stream strict-mode string svg template-literals typescript unit-testing uri url utf-8 value-vs-reference variable viewport vue webassembly webgl webrtc websockets xhtml xml yarn

MDN

MDN Web Docs, formerly known as Mozilla Developer Network, is the official Mozilla website for development documentation of web standards and Mozilla projects.

Module

Modules are independent, self-contained pieces of code that can be incorporated into other pieces of code. Modules improve maintainability and reusability of the code.

MongoDB

MongoDB is a NoSQL database model that stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time

Mutable value

Mutable value is a type of variable that can be changed once created. Objects are mutable as their state can be modified after they are created. Primitive values are not mutable as we perform reassignment once we change them.

MVC

MVC stands for Model-View-Controller and is a software design pattern, emphasizing separation of concerns (logic and display). The Model part of the MVC pattern refers to the data and business logic, the View handles the layout and display, while the Controller routes commands to the model and view parts.

Node.js

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js can execute JavaScript code outside of the browser and can be used to develop web backends or standalone applications.

NoSQL

NoSQL databases provide a mechanism to create, update, retrieve and calculate data that is stored in models that are non-tabular.

Npm

Npm is a package manager for the JavaScript programming language and the default package manager for Node.js. It consists of a command-line client and the npm registry, an online database of packages.

Object-oriented programming

Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which may contain both data and procedures which can be use to operate on them. JavaScript supports Object-oriented programming both via prototypes and classes.

Object

Objects are data structures that contain data and instructions for working with the data. Objects consist of key-value pairs, where the keys are alphanumeric identifiers and the values can either be primitives or objects. JavaScript functions are also objects.

Prepared statements

In databases management systems, prepared statements are templates that can be used to execute queries with the provided values substituting the template's parameters. Prepared statements offer many benefits, such as reusability, maintainability and higher security.

Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. A Promise can be in one of these states: pending(initial state, neither fulfilled nor rejected), fulfilled(operation completed successfully), rejected(operation failed).

Prototype-based programming

Prototype-based programming is a style of object-oriented programming, where inheritance is based on object delegation, reusing objects that serve as prototypes. Prototype-based programming allows the creation of objects before defining their classes.

Pseudo-class

In CSS, a pseudo-class is used to define a special state of an element and can be used as a selector in combination with an id, element or class selector.

Pseudo-element

In CSS, a pseudo-element is used to style specific parts of an element and can be used as a selector in combination with an id, element or class selector.

PWA

Progressive Web App (known as PWA) is a term used to describe web applications that load like regular websites but can offer the user functionality such as working offline, push notifications, and device hardware access that were traditionally available only to native mobile applications.

React

React is a frontend framework, that allows developers to create dynamic, component-based user interfaces. React separates view and state, utilizing a virtual DOM to update the user interface.

Recursion

Recursion is the repeated application of a process. In JavaScript, recursion involves functions that call themselves repeatedly until they reach a base condition. The base condition breaks out of the recursion loop because otherwise the function would call itself indefinitely. Recursion is very useful when working with nested data, especially when the nesting depth is dynamically defined or unkown.

Regular expressions

Regular expressions (known as regex or regexp) are patterns used to match character combinations in strings. JavaScript provides a regular expression implementation through the RegExp object.

Repository

In a version control system, a repository (or repo for short) is a data structure that stores metadata for a set of files (i.e. a project).

Responsive web design

Responsive web design is a web development concept aiming to provide optimal behavior and performance of websites on all web-enabled devices. Responsive web design is usually coupled with a mobile-first approach.

Scope

Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions.

Selector

A CSS selector is a pattern that is used to select and/or style one or more elements in a document, based on certain rules. The order in which CSS selectors apply styles to elements is based on the rules of CSS specificity.

SEO

SEO stands for Search Engine Optimization and refers to the process of improving a website's search rankings and visibility.

Serialization

Serialization is the process of converting an object or data structure into a format suitable for transfer over a network and/or storage. A common type of serialization in JavaScript is the conversion of an object into a JSON string.

SQL injection

SQL injection is a code injection technique, used to attack data-driven applications. SQL injections get their name from the SQL language and mainly target data stored in relational databases.

SQL

SQL stands for Structured Query Language and is a language used to create, update, retrieve and calculate data in table-based databases. SQL databases use a relational database model and are particularly useful in handlind structured data with relations between different entities.

SSL

Secure Sockets Layer, commonly known as SSL or TLS, is a set of protocols and standards for transferring private data across the Internet. SSL uses a cryptographic system that uses two keys to encrypt data.

Stream

A stream is a sequence of data made available over time, often due to network transmission or storage access times.

Strict mode

JavaScript's strict mode is a JavaScript feature that allows developers to use a more restrictive variant of JavaScript and it can be enabled by adding 'use strict'; at the very top of their code. Strict mode elimiated some silent errors, might improve performance and changes the behavior of eval and arguments among other things.

String

Strings are one of the primitive data types in JavaScript. They are sequences of characters and are used to represent text.

SVG

SVG stands for Scalable Vector Graphics and is a 2D vector image format based on an XML syntax. SVG images can scale infinitely and can utilize clipping, masking, filters, animations etc.

Template literals

Template literals are strings that allow embedded expressions. They support multi-line strings, expression interpolation and nesting.

TypeScript

TypeScript is a superset of JavaScript, adding optional static typing to the language. TypeScript compiles to plain JavaScript.

Unit testing

Unit testing is a type of software testing, used to test individual units/components of a software. The purpose of unit tests are to validate that each individual unit/component performs as designed.

URI

URI stands for Uniform Resource Identifier and is a text string referring to a resource. A common type of URI is a URL, which is used for the identification of resources on the Web.

URL

URL stands for Uniform Resource Locator and is a text string specifying where a resource can be found on the Internet. In the HTTP protocol, URLs are the same as web addresses and hyperlinks.

UTF-8

UTF-8 stands for UCS Transformation Format 8 and is a commonly used character encoding. UTF-8 is backwards compatible with ASCII and can represent any standard Unicode character.

Value vs reference

When passing a variable by value, a copy of the variable is made, meaning that any changes made to the contents of the variable will not be reflected in the original variable. When passing a variable by reference, the memory address of the actual variable is passed to the function or variable, meaning that modifying the variable's contents will be reflected in the original variable. In JavaScript primitive data types are passed by value while objects are passed by reference.

Variable

A variable is a storage location, associated with an identifier and containing a value. The value of a variable can be referred using the identifier and can be altered during execution.

Viewport

A viewport is a polygonal (usually rectangular) area in computer graphics that is currently being viewed. In web development and design, it refers to the visible part of the document that is being viewed by the user in the browser window.

Vue

Vue.js is a progressive frontend framework for building user interfaces. Vue.js separates view and state, utilizing a virtual DOM to update the user interface.

WebAssembly

WebAssembly (WA) is a web standard that defines an assembly-like text format and corresponding binary format for executalbe code in web pages. WebAssembly is meant to complement JavaScript and improve its performance to match native code performance.

WebGL

WebGL stands for Web Graphics Library and is a JavaScript API that can be used for drawing interactive 2D and 3D graphics. WebGL is based on OpenGL and can be invoked within HTML <canvas> elements, which provide a rendering surface.

WebRTC

WebRTC stands for Web Real-Time Communication and is an API that can be used for video-chat, voice-calling and P2P-file-sharing web apps.

WebSockets

WebSockets is a protocol that allows for a persistent client-server TCP connection. The WebSocket protocol uses lower overheads, facilitating real-time data transfer between client and server.

XHTML

XHTML stands for EXtensible HyperText Markup Language and is a language used to structure web pages. XHTML is a reformulation of the HTML document structure as an application of XML.

XML

XML stands for eXtensible Markup Language and is a generic markup language specified by the W3C. XML documents are plaintext documents structured with user-defined tags, surrounded by <> and optionally extended with attributes.

Yarn

Yarn is a package manager made by Facebook. It can be used as an alternative to the npm package manager and is compatible with the public NPM registry.

\ No newline at end of file diff --git a/docs/index.html b/docs/index.html index 9015c3486..093437826 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,25 +1,364 @@ -30 seconds of code

logo 30 seconds of code

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

321
snippets

125
contributors

3694
commits

21618
stars

Our philosophy

The core goal of 30 seconds of code is to provide a quality resource for beginner and advanced JavaScript developers alike. We want to help improve the JavaScript ecosystem, by lowering the barrier of entry for newcomers and help seasoned veterans pick up new tricks and remember old ones. In order to achieve this, we have collected hundreds of snippets that can be of use in a wide range of situations. We welcome new contributors and we like fresh ideas, as long as the code is short and easy to grasp in about 30 seconds. The only catch, if you may, is that a few of our snippets are not perfectly optimized for large, enterprise applications and they might not be deemed production-ready.


In order for 30 seconds of code to be as accessible and useful as possible, all of the snippets in the collection are licensed under the CC0-1.0 License, meaning they are absolutely free to use in any project you like. If you like what we do, you can always credit us, but that is not mandatory.


Today's picks

Our sophisticated robot helpers pick new snippets from our collection daily, so that you can discover new snippets to enhance your projects:

mapKeys

Creates an object with keys generated by running the provided function for each key and the same values as the provided object.

Use Object.keys(obj) to iterate over the object's keys. Use Array.reduce() to create a new object with the same values and mapped keys using fn.

const mapKeys = (obj, fn) =>
-  Object.keys(obj).reduce((acc, k) => {
-    acc[fn(obj[k], k, obj)] = obj[k];
+Array - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Array

intermediate

all

Returns true if the provided predicate function returns true for all elements in a collection, false otherwise.

Use Array.every() to test if all elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default.

const all = (arr, fn = Boolean) => arr.every(fn);
+
all([4, 2, 3], x => x > 1); // true
+all([1, 2, 3]); // true
+
beginner

allEqual

Check if all elements are equal

Use Array.every() to check if all the elements of the array are the same as the first one.

const allEqual = arr => arr.every(val => val === arr[0]);
+
allEqual([1, 2, 3, 4, 5, 6]); // false
+allEqual([1, 1, 1, 1]); // true
+
intermediate

any

Returns true if the provided predicate function returns true for at least one element in a collection, false otherwise.

Use Array.some() to test if any elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default.

const any = (arr, fn = Boolean) => arr.some(fn);
+
any([0, 1, 2, 0], x => x >= 2); // true
+any([0, 0, 1, 0]); // true
+
intermediate

arrayToCSV

Converts a 2D array to a comma-separated values (CSV) string.

Use Array.map() and Array.join(delimiter) to combine individual 1D arrays (rows) into strings. Use Array.join('\n') to combine all rows into a CSV string, separating each row with a newline. Omit the second argument, delimiter, to use a default delimiter of ,.

const arrayToCSV = (arr, delimiter = ',') =>
+  arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
+
arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
+arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
+
intermediate

bifurcate

Splits values into two groups. If an element in filter is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.

Use Array.reduce() and Array.push() to add elements to groups, based on filter.

const bifurcate = (arr, filter) =>
+  arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
+
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]
+
intermediate

bifurcateBy

Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.

Use Array.reduce() and Array.push() to add elements to groups, based on the value returned by fn for each element.

const bifurcateBy = (arr, fn) =>
+  arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
+
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]
+
intermediate

chunk

Chunks an array into smaller arrays of a specified size.

Use Array.from() to create a new array, that fits the number of chunks that will be produced. Use Array.slice() to map each element of the new array to a chunk the length of size. If the original array can't be split evenly, the final chunk will contain the remaining elements.

const chunk = (arr, size) =>
+  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
+    arr.slice(i * size, i * size + size)
+  );
+
chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]
+
intermediate

compact

Removes falsey values from an array.

Use Array.filter() to filter out falsey values (false, null, 0, "", undefined, and NaN).

const compact = arr => arr.filter(Boolean);
+
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]
+
intermediate

countBy

Groups the elements of an array based on the given function and returns the count of elements in each group.

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.

const countBy = (arr, fn) =>
+  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
+    acc[val] = (acc[val] || 0) + 1;
     return acc;
   }, {});
-
mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }
-

pull

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 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)

const pull = (arr, ...args) => {
+
countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
+countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}
+
intermediate

countOccurrences

Counts the occurrences of a value in an array.

Use Array.reduce() to increment a counter each time you encounter the specific value inside the array.

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
+
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
+
intermediate

deepFlatten

Deep flattens an array.

Use recursion. Use Array.concat() with an empty array ([]) and the spread operator (...) to flatten an array. Recursively flatten each element that is an array.

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
+
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
+
intermediate

difference

Returns the difference between two arrays.

Create a Set from b, then use Array.filter() on a to only keep values not contained in b.

const difference = (a, b) => {
+  const s = new Set(b);
+  return a.filter(x => !s.has(x));
+};
+
difference([1, 2, 3], [1, 2, 4]); // [3]
+
intermediate

differenceBy

Returns the difference between two arrays, after applying the provided function to each array element of both.

Create a Set by applying fn to each element in b, then use Array.filter() in combination with fn on a to only keep values not contained in the previously created set.

const differenceBy = (a, b, fn) => {
+  const s = new Set(b.map(v => fn(v)));
+  return a.filter(x => !s.has(fn(x)));
+};
+
differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]
+differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]
+
intermediate

differenceWith

Filters out all values from an array for which the comparator function does not return true.

Use Array.filter() and Array.findIndex() to find the appropriate values.

const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
+
differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]
+
intermediate

drop

Returns a new array with n elements removed from the left.

Use Array.slice() to slice the remove the specified number of elements from the left.

const drop = (arr, n = 1) => arr.slice(n);
+
drop([1, 2, 3]); // [2,3]
+drop([1, 2, 3], 2); // [3]
+drop([1, 2, 3], 42); // []
+
intermediate

dropRight

Returns a new array with n elements removed from the right.

Use Array.slice() to slice the remove the specified number of elements from the right.

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); // []
+
intermediate

dropRightWhile

Removes elements from the end of an array until the passed function returns true. Returns the remaining elements in the array.

Loop through the array, using Array.slice() to drop the last element of the array until the returned value from the function is true. Returns the remaining elements.

const dropRightWhile = (arr, func) => {
+  while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
+  return arr;
+};
+
dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
+
intermediate

dropWhile

Removes elements in an array until the passed function returns true. Returns the remaining elements in the array.

Loop through the array, using Array.slice() to drop the first element of the array until the returned value from the function is true. Returns the remaining elements.

const dropWhile = (arr, func) => {
+  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
+  return arr;
+};
+
dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]
+
beginner

everyNth

Returns every nth element in an array.

Use Array.filter() to create a new array that contains every nth element of a given array.

const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
+
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
+
beginner

filterNonUnique

Filters out the non-unique values in an array.

Use Array.filter() for an array containing only the unique values.

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
+
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5]
+
intermediate

filterNonUniqueBy

Filters out the non-unique values in an array, based on a provided comparator function.

Use Array.filter() and Array.every() for an array containing only the unique values, based on the comparator function, fn. The comparator function takes four arguments: the values of the two elements being compared and their indexes.

const filterNonUniqueBy = (arr, fn) =>
+  arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));
+
filterNonUniqueBy(
+  [
+    { id: 0, value: 'a' },
+    { id: 1, value: 'b' },
+    { id: 2, value: 'c' },
+    { id: 1, value: 'd' },
+    { id: 0, value: 'e' }
+  ],
+  (a, b) => a.id == b.id
+); // [ { id: 2, value: 'c' } ]
+
intermediate

findLast

Returns the last element for which the provided function returns a truthy value.

Use Array.filter() to remove elements for which fn returns falsey values, Array.pop() to get the last one.

const findLast = (arr, fn) => arr.filter(fn).pop();
+
findLast([1, 2, 3, 4], n => n % 2 === 1); // 3
+
intermediate

findLastIndex

Returns the index of the last element for which the provided function returns a truthy value.

Use Array.map() to map each element to an array with its index and value. Use Array.filter() to remove elements for which fn returns falsey values, Array.pop() to get the last one.

const findLastIndex = (arr, fn) =>
+  arr
+    .map((val, i) => [i, val])
+    .filter(([i, val]) => fn(val, i, arr))
+    .pop()[0];
+
findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3)
+
intermediate

flatten

Flattens an array up to the specified depth.

Use recursion, decrementing depth by 1 for each level of depth. Use Array.reduce() and Array.concat() to merge elements or arrays. Base case, for depth equal to 1 stops recursion. Omit the second argument, depth to flatten only to a depth of 1 (single flatten).

const flatten = (arr, depth = 1) =>
+  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
+
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
+flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
+
intermediate

forEachRight

Executes a provided function once for each array element, starting from the array's last element.

Use Array.slice(0) to clone the given array, Array.reverse() to reverse it and Array.forEach() to iterate over the reversed array.

const forEachRight = (arr, callback) =>
+  arr
+    .slice(0)
+    .reverse()
+    .forEach(callback);
+
forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'
+
intermediate

groupBy

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.

const groupBy = (arr, fn) =>
+  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
+    acc[val] = (acc[val] || []).concat(arr[i]);
+    return acc;
+  }, {});
+
groupBy([6.1, 4.2, 6.3], Math.floor); // {4: [4.2], 6: [6.1, 6.3]}
+groupBy(['one', 'two', 'three'], 'length'); // {3: ['one', 'two'], 5: ['three']}
+
intermediate

Returns the head of a list.

Use arr[0] to return the first element of the passed array.

const head = arr => arr[0];
+
head([1, 2, 3]); // 1
+
intermediate

indexOfAll

Returns all indices of val in an array. If val never occurs, returns [].

Use Array.reduce() to loop over elements and store indices for matching elements. Return the array of indices.

const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);
+
indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
+indexOfAll([1, 2, 3], 4); // []
+
intermediate

initial

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.

const initial = arr => arr.slice(0, -1);
+
initial([1, 2, 3]); // [1,2]
+
intermediate

initialize2DArray

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 the value is not provided, default to null.

const initialize2DArray = (w, h, val = null) =>
+  Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));
+
initialize2DArray(2, 2, 0); // [[0,0], [0,0]]
+
intermediate

initializeArrayWithRange

Initializes an array containing the numbers in the specified range where start and end are inclusive with their common difference step.

Use Array.from() to create an array of the desired length, (end - start + 1)/step, and a map function to fill it with the desired values in the given range. You can omit start to use a default value of 0. You can omit step to use a default value of 1.

const initializeArrayWithRange = (end, start = 0, step = 1) =>
+  Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start);
+
initializeArrayWithRange(5); // [0,1,2,3,4,5]
+initializeArrayWithRange(7, 3); // [3,4,5,6,7]
+initializeArrayWithRange(9, 0, 2); // [0,2,4,6,8]
+
intermediate

initializeArrayWithRangeRight

Initializes an array containing the numbers in the specified range (in reverse) where start and end are inclusive with their common difference step.

Use Array.from(Math.ceil((end+1-start)/step)) to create an array of the desired length(the amounts of elements is equal to (end-start)/step or (end+1-start)/step for inclusive end), Array.map() to fill with the desired values in a range. You can omit start to use a default value of 0. You can omit step to use a default value of 1.

const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
+  Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(
+    (v, i, arr) => (arr.length - i - 1) * step + start
+  );
+
initializeArrayWithRangeRight(5); // [5,4,3,2,1,0]
+initializeArrayWithRangeRight(7, 3); // [7,6,5,4,3]
+initializeArrayWithRangeRight(9, 0, 2); // [8,6,4,2,0]
+
intermediate

initializeArrayWithValues

Initializes and fills an array with the specified values.

Use Array(n) to create an array of the desired length, fill(v) to fill it with the desired values. You can omit val to use a default value of 0.

const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
+
initializeArrayWithValues(5, 2); // [2,2,2,2,2]
+
intermediate

initializeNDArray

Create a n-dimensional array with given value.

Use recursion. Use Array.map() to generate rows where each is a new array initialized using initializeNDArray.

const initializeNDArray = (val, ...args) =>
+  args.length === 0
+    ? val
+    : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));
+
initializeNDArray(1, 3); // [1,1,1]
+initializeNDArray(5, 2, 2, 2); // [[[5,5],[5,5]],[[5,5],[5,5]]]
+
intermediate

intersection

Returns a list of elements that exist in both arrays.

Create a Set from b, then use Array.filter() on a to only keep values contained in b.

const intersection = (a, b) => {
+  const s = new Set(b);
+  return a.filter(x => s.has(x));
+};
+
intersection([1, 2, 3], [4, 3, 2]); // [2,3]
+
intermediate

intersectionBy

Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.

Create a Set by applying fn to all elements in b, then use Array.filter() on a to only keep elements, which produce values contained in b when fn is applied to them.

const intersectionBy = (a, b, fn) => {
+  const s = new Set(b.map(x => fn(x)));
+  return a.filter(x => s.has(fn(x)));
+};
+
intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
+
intermediate

intersectionWith

Returns a list of elements that exist in both arrays, using a provided comparator function.

Use Array.filter() and Array.findIndex() in combination with the provided comparator to determine intersecting values.

const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);
+
intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0]
+
intermediate

isSorted

Returns 1 if the array is sorted in ascending order, -1 if it is sorted in descending order or 0 if it is not sorted.

Calculate the ordering direction for the first two elements. Use Object.entries() to loop over array objects and compare them in pairs. Return 0 if the direction changes or the direction if the last element is reached.

const isSorted = arr => {
+  let direction = -(arr[0] - arr[1]);
+  for (let [i, val] of arr.entries()) {
+    direction = !direction ? -(arr[i - 1] - arr[i]) : direction;
+    if (i === arr.length - 1) return !direction ? 0 : direction;
+    else if ((val - arr[i + 1]) * direction > 0) return 0;
+  }
+};
+
isSorted([0, 1, 2, 2]); // 1
+isSorted([4, 3, 2]); // -1
+isSorted([4, 3, 5]); // 0
+
intermediate

join

Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.

Use Array.reduce() to combine elements into a string. Omit the second argument, separator, to use a default separator of ','. Omit the third argument, end, to use the same value as separator by default.

const join = (arr, separator = ',', end = separator) =>
+  arr.reduce(
+    (acc, val, i) =>
+      i === arr.length - 2
+        ? acc + val + end
+        : i === arr.length - 1
+          ? acc + val
+          : acc + val + separator,
+    ''
+  );
+
join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // "pen,pineapple,apple&pen"
+join(['pen', 'pineapple', 'apple', 'pen'], ','); // "pen,pineapple,apple,pen"
+join(['pen', 'pineapple', 'apple', 'pen']); // "pen,pineapple,apple,pen"
+
advanced

JSONtoCSV

Converts an array of objects to a comma-separated values (CSV) string that contains only the columns specified.

Use Array.join(demiliter) to combine all the names in columns to create the first row. Use Array.map() and Array.reduce() to create a row for each object, substituting non-existent values with empty strings and only mapping values in columns. Use Array.join('\n') to combine all rows into a string. Omit the third argument, delimiter, to use a default delimiter of ,.

const JSONtoCSV = (arr, columns, delimiter = ',') =>
+  [
+    columns.join(delimiter),
+    ...arr.map(obj =>
+      columns.reduce(
+        (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
+        ''
+      )
+    )
+  ].join('\n');
+
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"'
+JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"'
+
beginner

last

Returns the last element in an array.

Use arr.length - 1 to compute the index of the last element of the given array and returning it.

const last = arr => arr[arr.length - 1];
+
last([1, 2, 3]); // 3
+
intermediate

longestItem

Takes any number of iterable objects or objects with a length property and returns the longest one. If multiple objects have the same length, the first one will be returned. Returns undefined if no arguments are provided.

Use Array.reduce(), comparing the length of objects to find the longest one.

const longestItem = (val, ...vals) =>
+  [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a));
+
longestItem('this', 'is', 'a', 'testcase'); // 'testcase'
+longestItem(...['a', 'ab', 'abc']); // 'abc'
+longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd'
+longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
+longestItem([1, 2, 3], 'foobar'); // 'foobar'
+
advanced

mapObject

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 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).

const mapObject = (arr, fn) =>
+  (a => (
+    (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
+  ))();
+
const squareIt = arr => mapObject(arr, a => a * a);
+squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
+
beginner

maxN

Returns the n maximum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in descending order).

Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
+
maxN([1, 2, 3]); // [3]
+maxN([1, 2, 3], 2); // [3,2]
+
intermediate

minN

Returns the n minimum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in ascending order).

Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in ascending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
+
minN([1, 2, 3]); // [1]
+minN([1, 2, 3], 2); // [1,2]
+
intermediate

none

Returns true if the provided predicate function returns false for all elements in a collection, false otherwise.

Use Array.some() to test if any elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default.

const none = (arr, fn = Boolean) => !arr.some(fn);
+
none([0, 1, 3, 0], x => x == 2); // true
+none([0, 0, 0]); // true
+
beginner

nthElement

Returns the nth element of an array.

Use Array.slice() to get an array containing the nth element at the first place. If the index is out of bounds, return undefined. Omit the second argument, n, to get the first element of the array.

const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];
+
nthElement(['a', 'b', 'c'], 1); // 'b'
+nthElement(['a', 'b', 'b'], -3); // 'a'
+
beginner

offset

Moves the specified amount of elements to the end of the array.

Use Array.slice() twice to get the elements after the specified index and the elements before that. Use the spread operator(...) to combine the two into one array. If offset is negative, the elements will be moved from end to start.

const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];
+
offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
+offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]
+
intermediate

partition

Groups the elements into two arrays, depending on the provided function's truthiness for each element.

Use Array.reduce() to create an array of two arrays. Use Array.push() to add elements for which fn returns true to the first array and elements for which fn returns false to the second one.

const partition = (arr, fn) =>
+  arr.reduce(
+    (acc, val, i, arr) => {
+      acc[fn(val, i, arr) ? 0 : 1].push(val);
+      return acc;
+    },
+    [[], []]
+  );
+
const users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }];
+partition(users, o => o.active); // [[{ 'user': 'fred',    'age': 40, 'active': true }],[{ 'user': 'barney',  'age': 36, 'active': false }]]
+
intermediate

permutations

⚠️ WARNING: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations.

Generates all permutations of an array's elements (contains duplicates).

Use recursion. For each element in the given array, create all the partial permutations for the rest of its elements. Use Array.map() to combine the element with each partial permutation, then Array.reduce() to combine all permutations in one array. Base cases are for array length equal to 2 or 1.

const permutations = arr => {
+  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
+  return arr.reduce(
+    (acc, item, i) =>
+      acc.concat(
+        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
+      ),
+    []
+  );
+};
+
permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]
+
intermediate

pull

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 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)

const pull = (arr, ...args) => {
   let argState = Array.isArray(args[0]) ? args[0] : args;
   let pulled = arr.filter((v, i) => !argState.includes(v));
   arr.length = 0;
   pulled.forEach(v => arr.push(v));
 };
-
let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];
+
let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];
 pull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ]
-

reducedFilter

Filter an array of objects based on a condition while also filtering out unspecified keys.

Use Array.filter() to filter the array based on the predicate fn so that it returns the objects for which the condition returned a truthy value. On the filtered array, use Array.map() to return the new object using Array.reduce() to filter out the keys which were not supplied as the keys argument.

const reducedFilter = (data, keys, fn) =>
+
intermediate

pullAtIndex

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 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

const pullAtIndex = (arr, pullArr) => {
+  let removed = [];
+  let pulled = arr
+    .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))
+    .filter((v, i) => !pullArr.includes(i));
+  arr.length = 0;
+  pulled.forEach(v => arr.push(v));
+  return removed;
+};
+
let myArray = ['a', 'b', 'c', 'd'];
+let pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
+
intermediate

pullAtValue

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 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

const pullAtValue = (arr, pullArr) => {
+  let removed = [],
+    pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)),
+    mutateTo = arr.filter((v, i) => !pullArr.includes(v));
+  arr.length = 0;
+  mutateTo.forEach(v => arr.push(v));
+  return removed;
+};
+
let myArray = ['a', 'b', 'c', 'd'];
+let pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
+
advanced

pullBy

Mutates the original array to filter out the values specified, based on a given iterator function.

Check if the last argument provided in a function. Use Array.map() to apply the iterator function fn to all array 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 an array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.

const pullBy = (arr, ...args) => {
+  const length = args.length;
+  let fn = length > 1 ? args[length - 1] : undefined;
+  fn = typeof fn == 'function' ? (args.pop(), fn) : undefined;
+  let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val));
+  let pulled = arr.filter((v, i) => !argState.includes(fn(v)));
+  arr.length = 0;
+  pulled.forEach(v => arr.push(v));
+};
+
var myArray = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }];
+pullBy(myArray, [{ x: 1 }, { x: 3 }], o => o.x); // myArray = [{ x: 2 }]
+
intermediate

reducedFilter

Filter an array of objects based on a condition while also filtering out unspecified keys.

Use Array.filter() to filter the array based on the predicate fn so that it returns the objects for which the condition returned a truthy value. On the filtered array, use Array.map() to return the new object using Array.reduce() to filter out the keys which were not supplied as the keys argument.

const reducedFilter = (data, keys, fn) =>
   data.filter(fn).map(el =>
     keys.reduce((acc, key) => {
       acc[key] = el[key];
       return acc;
     }, {})
   );
-
const data = [
+
const data = [
   {
     id: 1,
     name: 'john',
@@ -33,79 +372,244 @@
 ];
 
 reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]
-

Getting started


Related projects

The idea behind 30 seconds of code has inspired some people to create similar collections in other programming languages and environments. Here are the ones we like the most:


How to contribute

Do you have a cool idea for a new snippet? Maybe some code you use often and is not part of our collection? Contributing to 30 seconds of code is as simple as 1,2,3,4!

1

Create

Start by creating a snippet, according to the snippet template. Make sure to follow these simple guidelines:

  • Your snippet title must be unique and the same as the name of the implemented function.
  • Use the snippet description to explain what your snippet does and how it works.
  • Try to keep the snippet's code short and to the point. Use modern techniques and features.
  • Remember to provide an example of how your snippet works.
  • Your snippet should solve a real-world problem, no matter how simple.
  • Never modify README.md or any of the HTML files.
2

Tag

Run npm run tagger from your terminal, then open the tag_database file and tag your snippet appropriately. Multitagging is also supported, just make sure the first tag you specify is on of the major tags and the one that is most relevant to the implemented function.

3

Test

You can optionally test your snippet to make our job easier. Simply run npm run tester to generate the test files for your snippet. Find the related folder for you snippet under the test directory and write some tests. Remember to run npm run tester again to make sure your tests are passing.

4

Pull request

If you have done everything mentioned above, you should now have an awesome snippet to add to our collection. Simply start a pull request and follow the guidelines provided. Remember to only submit one snippet per pull request, so that we can quickly evaluate and merge your code into the collection.

If you need additional pointers about writing a snippet, be sure to read the complete contribution guidelines.


\ No newline at end of file +
intermediate

reduceSuccessive

Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.

Use Array.reduce() to apply the given function to the given array, storing each new result.

const reduceSuccessive = (arr, fn, acc) =>
+  arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);
+
reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); // [0, 1, 3, 6, 10, 15, 21]
+
intermediate

reduceWhich

Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.

Use Array.reduce() in combination with the comparator function to get the appropriate element in the array. You can omit the second parameter, comparator, to use the default one that returns the minimum element in the array.

const reduceWhich = (arr, comparator = (a, b) => a - b) =>
+  arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));
+
reduceWhich([1, 3, 2]); // 1
+reduceWhich([1, 3, 2], (a, b) => b - a); // 3
+reduceWhich(
+  [{ name: 'Tom', age: 12 }, { name: 'Jack', age: 18 }, { name: 'Lucy', age: 9 }],
+  (a, b) => a.age - b.age
+); // {name: "Lucy", age: 9}
+
intermediate

reject

Takes a predicate and array, like Array.filter(), but only keeps x if pred(x) === false.

const reject = (pred, array) => array.filter((...args) => !pred(...args));
+
reject(x => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5]
+reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); // ['Pear', 'Kiwi']
+
intermediate

remove

Removes elements from an array for which the given function returns false.

Use Array.filter() to find array elements that return truthy values and Array.reduce() to remove elements using Array.splice(). The func is invoked with three arguments (value, index, array).

const remove = (arr, func) =>
+  Array.isArray(arr)
+    ? arr.filter(func).reduce((acc, val) => {
+        arr.splice(arr.indexOf(val), 1);
+        return acc.concat(val);
+      }, [])
+    : [];
+
remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4]
+
beginner

sample

Returns a random element from an array.

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.

const sample = arr => arr[Math.floor(Math.random() * arr.length)];
+
sample([3, 7, 9, 11]); // 9
+
intermediate

sampleSize

Gets n random elements at unique keys from array up to the size of array.

Shuffle the array using the Fisher-Yates algorithm. Use Array.slice() to get the first n elements. Omit the second argument, n to get only one element at random from the array.

const sampleSize = ([...arr], n = 1) => {
+  let m = arr.length;
+  while (m) {
+    const i = Math.floor(Math.random() * m--);
+    [arr[m], arr[i]] = [arr[i], arr[m]];
+  }
+  return arr.slice(0, n);
+};
+
sampleSize([1, 2, 3], 2); // [3,1]
+sampleSize([1, 2, 3], 4); // [2,3,1]
+
intermediate

shuffle

Randomizes the order of the values of an array, returning a new array.

Uses the Fisher-Yates algorithm to reorder the elements of the array.

const shuffle = ([...arr]) => {
+  let m = arr.length;
+  while (m) {
+    const i = Math.floor(Math.random() * m--);
+    [arr[m], arr[i]] = [arr[i], arr[m]];
+  }
+  return arr;
+};
+
const foo = [1, 2, 3];
+shuffle(foo); // [2,3,1], foo = [1,2,3]
+
beginner

similarity

Returns an array of elements that appear in both arrays.

Use Array.filter() to remove values that are not part of values, determined using Array.includes().

const similarity = (arr, values) => arr.filter(v => values.includes(v));
+
similarity([1, 2, 3], [1, 2, 4]); // [1,2]
+
intermediate

sortedIndex

Returns the lowest index at which value should be inserted into array in order to maintain its sort order.

Check if the array is sorted in descending order (loosely). Use Array.findIndex() to find the appropriate index where the element should be inserted.

const sortedIndex = (arr, n) => {
+  const isDescending = arr[0] > arr[arr.length - 1];
+  const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
+  return index === -1 ? arr.length : index;
+};
+
sortedIndex([5, 3, 2, 1], 4); // 1
+sortedIndex([30, 50], 40); // 1
+
intermediate

sortedIndexBy

Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.

Check if the array is sorted in descending order (loosely). Use Array.findIndex() to find the appropriate index where the element should be inserted, based on the iterator function fn.

const sortedIndexBy = (arr, n, fn) => {
+  const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
+  const val = fn(n);
+  const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el)));
+  return index === -1 ? arr.length : index;
+};
+
sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 0
+
intermediate

sortedLastIndex

Returns the highest index at which value should be inserted into array in order to maintain its sort order.

Check if the array is sorted in descending order (loosely). Use Array.reverse() and Array.findIndex() to find the appropriate last index where the element should be inserted.

const sortedLastIndex = (arr, n) => {
+  const isDescending = arr[0] > arr[arr.length - 1];
+  const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el));
+  return index === -1 ? 0 : arr.length - index;
+};
+
sortedLastIndex([10, 20, 30, 30, 40], 30); // 4
+
intermediate

sortedLastIndexBy

Returns the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.

Check if the array is sorted in descending order (loosely). Use Array.map() to apply the iterator function to all elements of the array. Use Array.reverse() and Array.findIndex() to find the appropriate last index where the element should be inserted, based on the provided iterator function.

const sortedLastIndexBy = (arr, n, fn) => {
+  const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
+  const val = fn(n);
+  const index = arr
+    .map(fn)
+    .reverse()
+    .findIndex(el => (isDescending ? val <= el : val >= el));
+  return index === -1 ? 0 : arr.length - index;
+};
+
sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 1
+
advanced

stableSort

Performs stable sorting of an array, preserving the initial indexes of items when their values are the same. Does not mutate the original array, but returns a new array instead.

Use Array.map() to pair each element of the input array with its corresponding index. Use Array.sort() and a compare function to sort the list, preserving their initial order if the items compared are equal. Use Array.map() to convert back to the initial array items.

const stableSort = (arr, compare) =>
+  arr
+    .map((item, index) => ({ item, index }))
+    .sort((a, b) => compare(a.item, b.item) || a.index - b.index)
+    .map(({ item }) => item);
+
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+const stable = stableSort(arr, () => 0); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+
intermediate

symmetricDifference

Returns the symmetric difference between two arrays, without filtering out duplicate values.

Create a Set from each array, then use Array.filter() on each of them to only keep values not contained in the other.

const symmetricDifference = (a, b) => {
+  const sA = new Set(a),
+    sB = new Set(b);
+  return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
+};
+
symmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]
+symmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 2, 3]
+
intermediate

symmetricDifferenceBy

Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.

Create a Set by applying fn to each array's elements, then use Array.filter() on each of them to only keep values not contained in the other.

const symmetricDifferenceBy = (a, b, fn) => {
+  const sA = new Set(a.map(v => fn(v))),
+    sB = new Set(b.map(v => fn(v)));
+  return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))];
+};
+
symmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ]
+
intermediate

symmetricDifferenceWith

Returns the symmetric difference between two arrays, using a provided function as a comparator.

Use Array.filter() and Array.findIndex() to find the appropriate values.

const symmetricDifferenceWith = (arr, val, comp) => [
+  ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1),
+  ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1)
+];
+
symmetricDifferenceWith(
+  [1, 1.2, 1.5, 3, 0],
+  [1.9, 3, 0, 3.9],
+  (a, b) => Math.round(a) === Math.round(b)
+); // [1, 1.2, 3.9]
+
beginner

tail

Returns all elements in an array except for the first one.

Return Array.slice(1) if the array's length is more than 1, otherwise, return the whole array.

const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
+
tail([1, 2, 3]); // [2,3]
+tail([1]); // [1]
+
intermediate

take

Returns an array with n elements removed from the beginning.

Use Array.slice() to create a slice of the array with n elements taken from the beginning.

const take = (arr, n = 1) => arr.slice(0, n);
+
take([1, 2, 3], 5); // [1, 2, 3]
+take([1, 2, 3], 0); // []
+
intermediate

takeRight

Returns an array with n elements removed from the end.

Use Array.slice() to create a slice of the array with n elements taken from the end.

const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
+
takeRight([1, 2, 3], 2); // [ 2, 3 ]
+takeRight([1, 2, 3]); // [3]
+
intermediate

takeRightWhile

Removes elements from the end of an array until the passed function returns true. Returns the removed elements.

Loop through the array, using a for...of loop over Array.keys() until the returned value from the function is true. Return the removed elements, using Array.reverse() and Array.slice().

const takeRightWhile = (arr, func) => {
+  for (let i of arr.reverse().keys())
+    if (func(arr[i])) return arr.reverse().slice(arr.length - i, arr.length);
+  return arr;
+};
+
takeRightWhile([1, 2, 3, 4], n => n < 3); // [3, 4]
+
intermediate

takeWhile

Removes elements in an array until the passed function returns true. Returns the removed elements.

Loop through the array, using a for...of loop over Array.entries() until the returned value from the function is true. Return the removed elements, using Array.slice().

const takeWhile = (arr, func) => {
+  for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i);
+  return arr;
+};
+
takeWhile([1, 2, 3, 4], n => n >= 3); // [1, 2]
+
intermediate

toHash

Reduces a given Array-like into a value hash (keyed data store).

Given an Iterable or Array-like structure, call Array.prototype.reduce.call() on the provided object to step over it and return an Object, keyed by the reference value.

const toHash = (object, key) =>
+  Array.prototype.reduce.call(
+    object,
+    (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc),
+    {}
+  );
+
toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 1: 1 }
+toHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }
+// A more in depth example:
+let users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }];
+let managers = [{ manager: 1, employees: [2, 3] }];
+// We use function here because we want a bindable reference, but a closure referencing the hash would work, too.
+managers.forEach(
+  manager =>
+    (manager.employees = manager.employees.map(function(id) {
+      return this[id];
+    }, toHash(users, 'id')))
+);
+managers; // [ { manager:1, employees: [ { id: 2, first: "Joe" }, { id: 3, first: "Moe" } ] } ]
+
intermediate

union

Returns every element that exists in any of the two arrays once.

Create a Set with all values of a and b and convert to an array.

const union = (a, b) => Array.from(new Set([...a, ...b]));
+
union([1, 2, 3], [4, 3, 2]); // [1,2,3,4]
+
intermediate

unionBy

Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.

Create a Set by applying all fn to all values of a. Create a Set from a and all elements in b whose value, after applying fn does not match a value in the previously created set. Return the last set converted to an array.

const unionBy = (a, b, fn) => {
+  const s = new Set(a.map(v => fn(v)));
+  return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))]));
+};
+
unionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2]
+
intermediate

unionWith

Returns every element that exists in any of the two arrays once, using a provided comparator function.

Create a Set with all values of a and values in b for which the comparator finds no matches in a, using Array.findIndex().

const unionWith = (a, b, comp) =>
+  Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]));
+
unionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2, 1.5, 3, 0, 3.9]
+
intermediate

uniqueElements

Returns all unique values of an array.

Use ES6 Set and the ...rest operator to discard all duplicated values.

const uniqueElements = arr => [...new Set(arr)];
+
uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5]
+
intermediate

uniqueElementsBy

Returns all unique values of an array, based on a provided comparator function.

Use Array.reduce() and Array.some() for an array containing only the first unique occurence of each value, based on the comparator function, fn. The comparator function takes two arguments: the values of the two elements being compared.

const uniqueElementsBy = (arr, fn) =>
+  arr.reduce((acc, v) => {
+    if (!acc.some(x => fn(v, x))) acc.push(v);
+    return acc;
+  }, []);
+
uniqueElementsBy(
+  [
+    { id: 0, value: 'a' },
+    { id: 1, value: 'b' },
+    { id: 2, value: 'c' },
+    { id: 1, value: 'd' },
+    { id: 0, value: 'e' }
+  ],
+  (a, b) => a.id == b.id
+); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ]
+
intermediate

uniqueElementsByRight

Returns all unique values of an array, based on a provided comparator function.

Use Array.reduce() and Array.some() for an array containing only the last unique occurence of each value, based on the comparator function, fn. The comparator function takes two arguments: the values of the two elements being compared.

const uniqueElementsByRight = (arr, fn) =>
+  arr.reduceRight((acc, v) => {
+    if (!acc.some(x => fn(v, x))) acc.push(v);
+    return acc;
+  }, []);
+
uniqueElementsByRight(
+  [
+    { id: 0, value: 'a' },
+    { id: 1, value: 'b' },
+    { id: 2, value: 'c' },
+    { id: 1, value: 'd' },
+    { id: 0, value: 'e' }
+  ],
+  (a, b) => a.id == b.id
+); // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ]
+
intermediate

uniqueSymmetricDifference

Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.

Use Array.filter() and Array.includes() on each array to remove values contained in the other, then create a Set from the results, removing duplicate values.

const uniqueSymmetricDifference = (a, b) => [
+  ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))])
+];
+
uniqueSymmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]
+uniqueSymmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 3]
+
intermediate

unzip

Creates an array of arrays, ungrouping the elements in an array produced by zip.

Use Math.max.apply() to get the longest subarray in the array, Array.map() to make each element an array. Use Array.reduce() and Array.forEach() to map grouped values to individual arrays.

const unzip = arr =>
+  arr.reduce(
+    (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
+    Array.from({
+      length: Math.max(...arr.map(x => x.length))
+    }).map(x => [])
+  );
+
unzip([['a', 1, true], ['b', 2, false]]); //[['a', 'b'], [1, 2], [true, false]]
+unzip([['a', 1, true], ['b', 2]]); //[['a', 'b'], [1, 2], [true]]
+
advanced

unzipWith

Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.

Use Math.max.apply() to get the longest subarray in the array, Array.map() to make each element an array. Use Array.reduce() and Array.forEach() to map grouped values to individual arrays. Use Array.map() and the spread operator (...) to apply fn to each individual group of elements.

const unzipWith = (arr, fn) =>
+  arr
+    .reduce(
+      (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
+      Array.from({
+        length: Math.max(...arr.map(x => x.length))
+      }).map(x => [])
+    )
+    .map(val => fn(...val));
+
unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)); // [3, 30, 300]
+
intermediate

without

Filters out the elements of an array, that have one of the specified values.

Use Array.filter() to create an array excluding(using !Array.includes()) all given values.

(For a snippet that mutates the original array see pull)

const without = (arr, ...args) => arr.filter(v => !args.includes(v));
+
without([2, 1, 2, 3], 1, 2); // [3]
+
intermediate

xProd

Creates a new array out of the two supplied by creating each possible pair from the arrays.

Use Array.reduce(), Array.map() and Array.concat() to produce every possible pair from the elements of the two arrays and save them in an array.

const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []);
+
xProd([1, 2], ['a', 'b']); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
+
intermediate

zip

Creates an array of elements, grouped based on the position in the original arrays.

Use Math.max.apply() to get the longest array in the arguments. Creates an array with that length as return value and use Array.from() with a map-function to create an array of grouped elements. If lengths of the argument-arrays vary, undefined is used where no value could be found.

const zip = (...arrays) => {
+  const maxLength = Math.max(...arrays.map(x => x.length));
+  return Array.from({ length: maxLength }).map((_, i) => {
+    return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);
+  });
+};
+
zip(['a', 'b'], [1, 2], [true, false]); // [['a', 1, true], ['b', 2, false]]
+zip(['a'], [1, 2], [true, false]); // [['a', 1, true], [undefined, 2, false]]
+
intermediate

zipObject

Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.

Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using Array.reduce().

const zipObject = (props, values) =>
+  props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});
+
zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined}
+zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}
+
advanced

zipWith

Creates an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined.

Check if the last argument provided is a function. Use Math.max() to get the longest array in the arguments. Creates an array with that length as return value and use Array.from() with a map-function to create an array of grouped elements. If lengths of the argument-arrays vary, undefined is used where no value could be found. The function is invoked with the elements of each group (...group).

const zipWith = (...array) => {
+  const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined;
+  return Array.from(
+    { length: Math.max(...array.map(a => a.length)) },
+    (_, i) => (fn ? fn(...array.map(a => a[i])) : array.map(a => a[i]))
+  );
+};
+
zipWith([1, 2], [10, 20], [100, 200], (a, b, c) => a + b + c); // [111,222]
+zipWith(
+  [1, 2, 3],
+  [10, 20],
+  [100, 200],
+  (a, b, c) => (a != null ? a : 'a') + (b != null ? b : 'b') + (c != null ? c : 'c')
+); // [111, 222, '3bc']
+
\ No newline at end of file diff --git a/docs/math.html b/docs/math.html index a3db3d026..edb086d33 100644 --- a/docs/math.html +++ b/docs/math.html @@ -1,6 +1,6 @@ -Math - 30 seconds of codeMath - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Math

approximatelyEqual

Checks if two numbers are approximately equal to each other.

Use Math.abs() to compare the absolute difference of the two values to epsilon. Omit the third parameter, epsilon, to use a default value of 0.001.

const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
-
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
-

average

Returns the average of two or more numbers.

Use Array.reduce() to add each value to an accumulator, initialized with a value of 0, divide by the length of the array.

const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
-
average(...[1, 2, 3]); // 2
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Math

intermediate

approximatelyEqual

Checks if two numbers are approximately equal to each other.

Use Math.abs() to compare the absolute difference of the two values to epsilon. Omit the third parameter, epsilon, to use a default value of 0.001.

const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
+
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
+
intermediate

average

Returns the average of two or more numbers.

Use Array.reduce() to add each value to an accumulator, initialized with a value of 0, divide by the length of the array.

const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
+
average(...[1, 2, 3]); // 2
 average(1, 2, 3); // 2
-

averageBy

Returns the average of an array, after mapping each element to a value using the provided function.

Use Array.map() to map each element to the value returned by fn, Array.reduce() to add each value to an accumulator, initialized with a value of 0, divide by the length of the array.

const averageBy = (arr, fn) =>
+
intermediate

averageBy

Returns the average of an array, after mapping each element to a value using the provided function.

Use Array.map() to map each element to the value returned by fn, Array.reduce() to add each value to an accumulator, initialized with a value of 0, divide by the length of the array.

const averageBy = (arr, fn) =>
   arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
   arr.length;
-
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
+
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
 averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
-

binomialCoefficient

Evaluates the binomial coefficient of two integers n and k.

Use Number.isNaN() to check if any of the two values is NaN. Check if k is less than 0, greater than or equal to n, equal to 1 or n - 1 and return the appropriate result. Check if n - k is less than k and switch their values accordingly. Loop from 2 through k and calculate the binomial coefficient. Use Math.round() to account for rounding errors in the calculation.

const binomialCoefficient = (n, k) => {
+
intermediate

binomialCoefficient

Evaluates the binomial coefficient of two integers n and k.

Use Number.isNaN() to check if any of the two values is NaN. Check if k is less than 0, greater than or equal to n, equal to 1 or n - 1 and return the appropriate result. Check if n - k is less than k and switch their values accordingly. Loop from 2 through k and calculate the binomial coefficient. Use Math.round() to account for rounding errors in the calculation.

const binomialCoefficient = (n, k) => {
   if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
   if (k < 0 || k > n) return 0;
   if (k === 0 || k === n) return 1;
@@ -99,17 +93,17 @@
   for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
   return Math.round(res);
 };
-
binomialCoefficient(8, 2); // 28
-

clampNumber

Clamps num within the inclusive range specified by the boundary values a and b.

If num falls within the range, return num. Otherwise, return the nearest number in the range.

const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
-
clampNumber(2, 3, 5); // 3
+
binomialCoefficient(8, 2); // 28
+
intermediate

clampNumber

Clamps num within the inclusive range specified by the boundary values a and b.

If num falls within the range, return num. Otherwise, return the nearest number in the range.

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

degreesToRads

Converts an angle from degrees to radians.

Use Math.PI and the degree to radian formula to convert the angle from degrees to radians.

const degreesToRads = deg => (deg * Math.PI) / 180.0;
-
degreesToRads(90.0); // ~1.5708
-

digitize

Converts a number to an array of digits.

Convert the number to a string, using the spread operator (...) to build an array. Use Array.map() and parseInt() to transform each value to an integer.

const digitize = n => [...`${n}`].map(i => parseInt(i));
-
digitize(123); // [1, 2, 3]
-

distance

Returns the distance between two points.

Use Math.hypot() to calculate the Euclidean distance between two points.

const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
-
distance(1, 1, 2, 3); // 2.23606797749979
-

eloadvanced

Computes the new ratings between two or more opponents using the Elo rating system. It takes an array of pre-ratings and returns an array containing post-ratings. The array should be ordered from best performer to worst performer (winner -> loser).

Use the exponent ** operator and math operators to compute the expected score (chance of winning). of each opponent and compute the new rating for each. Loop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion. Omit the second argument to use the default kFactor of 32.

const elo = ([...ratings], kFactor = 32, selfRating) => {
+
intermediate

degreesToRads

Converts an angle from degrees to radians.

Use Math.PI and the degree to radian formula to convert the angle from degrees to radians.

const degreesToRads = deg => (deg * Math.PI) / 180.0;
+
degreesToRads(90.0); // ~1.5708
+
intermediate

digitize

Converts a number to an array of digits.

Convert the number to a string, using the spread operator (...) to build an array. Use Array.map() and parseInt() to transform each value to an integer.

const digitize = n => [...`${n}`].map(i => parseInt(i));
+
digitize(123); // [1, 2, 3]
+
intermediate

distance

Returns the distance between two points.

Use Math.hypot() to calculate the Euclidean distance between two points.

const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
+
distance(1, 1, 2, 3); // 2.23606797749979
+
advanced

elo

Computes the new ratings between two or more opponents using the Elo rating system. It takes an array of pre-ratings and returns an array containing post-ratings. The array should be ordered from best performer to worst performer (winner -> loser).

Use the exponent ** operator and math operators to compute the expected score (chance of winning). of each opponent and compute the new rating for each. Loop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion. Omit the second argument to use the default kFactor of 32.

const elo = ([...ratings], kFactor = 32, selfRating) => {
   const [a, b] = ratings;
   const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));
   const newRating = (rating, i) =>
@@ -126,7 +120,7 @@
   }
   return ratings;
 };
-
// Standard 1v1s
+
// Standard 1v1s
 elo([1200, 1200]); // [1216, 1184]
 elo([1200, 1200], 64); // [1232, 1168]
 // 4 player FFA, all same rank
@@ -136,7 +130,7 @@ For teams, each rating can adjusted based on own team's average rating vs.
 average rating of opposing team, with the score being added to their
 own individual rating by supplying it as the third argument.
 */
-

factorial

Calculates the factorial of a number.

Use recursion. If n is less than or equal to 1, return 1. Otherwise, return the product of n and the factorial of n - 1. Throws an exception if n is a negative number.

const factorial = n =>
+
beginner

factorial

Calculates the factorial of a number.

Use recursion. If n is less than or equal to 1, return 1. Otherwise, return the product of n and the factorial of n - 1. Throws an exception if n is a negative number.

const factorial = n =>
   n < 0
     ? (() => {
         throw new TypeError('Negative numbers are not allowed!');
@@ -144,54 +138,54 @@ own individual rating by supplying it as the third argument.
     : n <= 1
       ? 1
       : n * factorial(n - 1);
-
factorial(6); // 720
-

fibonacci

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.

const fibonacci = n =>
+
factorial(6); // 720
+
beginner

fibonacci

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.

const fibonacci = n =>
   Array.from({ length: n }).reduce(
     (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
     []
   );
-
fibonacci(6); // [0, 1, 1, 2, 3, 5]
-

gcd

Calculates the greatest common divisor between two or more numbers/arrays.

The inner _gcd function uses recursion. Base case is when y equals 0. In this case, return x. Otherwise, return the GCD of y and the remainder of the division x/y.

const gcd = (...arr) => {
+
fibonacci(6); // [0, 1, 1, 2, 3, 5]
+
beginner

gcd

Calculates the greatest common divisor between two or more numbers/arrays.

The inner _gcd function uses recursion. Base case is when y equals 0. In this case, return x. Otherwise, return the GCD of y and the remainder of the division x/y.

const gcd = (...arr) => {
   const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
   return [...arr].reduce((a, b) => _gcd(a, b));
 };
-
gcd(8, 36); // 4
+
gcd(8, 36); // 4
 gcd(...[12, 8, 32]); // 4
-

geometricProgression

Initializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.

Use Array.from(), Math.log() and Math.floor() to create an array of the desired length, Array.map() to fill with the desired values in a range. Omit the second argument, start, to use a default value of 1. Omit the third argument, step, to use a default value of 2.

const geometricProgression = (end, start = 1, step = 2) =>
+
intermediate

geometricProgression

Initializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.

Use Array.from(), Math.log() and Math.floor() to create an array of the desired length, Array.map() to fill with the desired values in a range. Omit the second argument, start, to use a default value of 1. Omit the third argument, step, to use a default value of 2.

const geometricProgression = (end, start = 1, step = 2) =>
   Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(
     (v, i) => start * step ** i
   );
-
geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
+
geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
 geometricProgression(256, 3); // [3, 6, 12, 24, 48, 96, 192]
 geometricProgression(256, 1, 4); // [1, 4, 16, 64, 256]
-

hammingDistance

Calculates the Hamming distance between two values.

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 1s in the string, using match(/1/g).

const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
-
hammingDistance(2, 3); // 1
-

inRange

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 range is considered to be from 0 to start.

const inRange = (n, start, end = null) => {
+
intermediate

hammingDistance

Calculates the Hamming distance between two values.

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 1s in the string, using match(/1/g).

const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
+
hammingDistance(2, 3); // 1
+
intermediate

inRange

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 range is considered to be from 0 to start.

const inRange = (n, start, end = null) => {
   if (end && start > end) [end, start] = [start, end];
   return end == null ? n >= 0 && n < start : n >= start && n < end;
 };
-
inRange(3, 2, 5); // true
+
inRange(3, 2, 5); // true
 inRange(3, 4); // true
 inRange(2, 3, 5); // false
 inRange(3, 2); // false
-

isDivisible

Checks if the first numeric argument is divisible by the second one.

Use the modulo operator (%) to check if the remainder is equal to 0.

const isDivisible = (dividend, divisor) => dividend % divisor === 0;
-
isDivisible(6, 3); // true
-

isEven

Returns true if the given number is even, false otherwise.

Checks whether a number is odd or even using the modulo (%) operator. Returns true if the number is even, false if the number is odd.

const isEven = num => num % 2 === 0;
-
isEven(3); // false
-

isPrime

Checks if the provided integer is a prime number.

Check numbers from 2 to the square root of the given number. Return false if any of them divides the given number, else return true, unless the number is less than 2.

const isPrime = num => {
+
beginner

isDivisible

Checks if the first numeric argument is divisible by the second one.

Use the modulo operator (%) to check if the remainder is equal to 0.

const isDivisible = (dividend, divisor) => dividend % divisor === 0;
+
isDivisible(6, 3); // true
+
beginner

isEven

Returns true if the given number is even, false otherwise.

Checks whether a number is odd or even using the modulo (%) operator. Returns true if the number is even, false if the number is odd.

const isEven = num => num % 2 === 0;
+
isEven(3); // false
+
beginner

isPrime

Checks if the provided integer is a prime number.

Check numbers from 2 to the square root of the given number. Return false if any of them divides the given number, else return true, unless the number is less than 2.

const isPrime = num => {
   const boundary = Math.floor(Math.sqrt(num));
   for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
   return num >= 2;
 };
-
isPrime(11); // true
-

lcm

Returns the least common multiple of two or more numbers.

Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. The GCD formula uses recursion.

const lcm = (...arr) => {
+
isPrime(11); // true
+
beginner

lcm

Returns the least common multiple of two or more numbers.

Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. The GCD formula uses recursion.

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

luhnCheck

Implementation of the Luhn Algorithm used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.

Use String.split(''), Array.reverse() and Array.map() in combination with parseInt() to obtain an array of digits. Use Array.splice(0,1) to obtain the last digit. Use Array.reduce() to implement the Luhn Algorithm. Return true if sum is divisible by 10, false otherwise.

const luhnCheck = num => {
+
intermediate

luhnCheck

Implementation of the Luhn Algorithm used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.

Use String.split(''), Array.reverse() and Array.map() in combination with parseInt() to obtain an array of digits. Use Array.splice(0,1) to obtain the last digit. Use Array.reduce() to implement the Luhn Algorithm. Return true if sum is divisible by 10, false otherwise.

const luhnCheck = num => {
   let arr = (num + '')
     .split('')
     .reverse()
@@ -201,46 +195,46 @@ own individual rating by supplying it as the third argument.
   sum += lastDigit;
   return sum % 10 === 0;
 };
-
luhnCheck('4485275742308327'); // true
+
luhnCheck('4485275742308327'); // true
 luhnCheck(6011329933655299); //  false
 luhnCheck(123456789); // false
-

maxBy

Returns the maximum value of an array, after mapping each element to a value using the provided function.

Use Array.map() to map each element to the value returned by fn, Math.max() to get the maximum value.

const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
-
maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8
+
intermediate

maxBy

Returns the maximum value of an array, after mapping each element to a value using the provided function.

Use Array.map() to map each element to the value returned by fn, Math.max() to get the maximum value.

const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
+
maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8
 maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8
-

median

Returns the median of an array of numbers.

Find the middle of the array, use Array.sort() to sort the values. Return the number at the midpoint if length is odd, otherwise the average of the two middle numbers.

const median = arr => {
+
intermediate

median

Returns the median of an array of numbers.

Find the middle of the array, use Array.sort() to sort the values. Return the number at the midpoint if length is odd, otherwise the average of the two middle numbers.

const median = arr => {
   const mid = Math.floor(arr.length / 2),
     nums = [...arr].sort((a, b) => a - b);
   return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
 };
-
median([5, 6, 50, 1, -5]); // 5
-

minBy

Returns the minimum value of an array, after mapping each element to a value using the provided function.

Use Array.map() to map each element to the value returned by fn, Math.min() to get the maximum value.

const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
-
minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 2
+
median([5, 6, 50, 1, -5]); // 5
+
beginner

minBy

Returns the minimum value of an array, after mapping each element to a value using the provided function.

Use Array.map() to map each element to the value returned by fn, Math.min() to get the maximum value.

const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
+
minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 2
 minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 2
-

percentile

Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.

Use Array.reduce() to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.

const percentile = (arr, val) =>
+
intermediate

percentile

Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.

Use Array.reduce() to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.

const percentile = (arr, val) =>
   (100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length;
-
percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55
-

powerset

Returns the powerset of a given array of numbers.

Use Array.reduce() combined with Array.map() to iterate over elements and combine into an array containing all combinations.

const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
-
powerset([1, 2]); // [[], [1], [2], [2,1]]
-

primes

Generates primes up to a given number, using the Sieve of Eratosthenes.

Generate an array from 2 to the given number. Use Array.filter() to filter out the values divisible by any number from 2 to the square root of the provided number.

const primes = num => {
+
percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55
+
intermediate

powerset

Returns the powerset of a given array of numbers.

Use Array.reduce() combined with Array.map() to iterate over elements and combine into an array containing all combinations.

const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
+
powerset([1, 2]); // [[], [1], [2], [2,1]]
+
intermediate

primes

Generates primes up to a given number, using the Sieve of Eratosthenes.

Generate an array from 2 to the given number. Use Array.filter() to filter out the values divisible by any number from 2 to the square root of the provided number.

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

radsToDegrees

Converts an angle from radians to degrees.

Use Math.PI and the radian to degree formula to convert the angle from radians to degrees.

const radsToDegrees = rad => (rad * 180.0) / Math.PI;
-
radsToDegrees(Math.PI / 2); // 90
-

randomIntArrayInRange

Returns an array of n random integers in the specified range.

Use Array.from() to create an empty array of the specific length, Math.random() to generate a random number and map it to the desired range, using Math.floor() to make it an integer.

const randomIntArrayInRange = (min, max, n = 1) =>
+
primes(10); // [2,3,5,7]
+
intermediate

radsToDegrees

Converts an angle from radians to degrees.

Use Math.PI and the radian to degree formula to convert the angle from radians to degrees.

const radsToDegrees = rad => (rad * 180.0) / Math.PI;
+
radsToDegrees(Math.PI / 2); // 90
+
intermediate

randomIntArrayInRange

Returns an array of n random integers in the specified range.

Use Array.from() to create an empty array of the specific length, Math.random() to generate a random number and map it to the desired range, using Math.floor() to make it an integer.

const randomIntArrayInRange = (min, max, n = 1) =>
   Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
-
randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]
-

randomIntegerInRange

Returns a random integer in the specified range.

Use Math.random() to generate a random number and map it to the desired range, using Math.floor() to make it an integer.

const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
-
randomIntegerInRange(0, 5); // 2
-

randomNumberInRange

Returns a random number in the specified range.

Use Math.random() to generate a random value, map it to the desired range using multiplication.

const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
-
randomNumberInRange(2, 10); // 6.0211363285087005
-

round

Rounds a number to a specified amount of digits.

Use Math.round() and template literals to round the number to the specified number of digits. Omit the second argument, decimals to round to an integer.

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
-
round(1.005, 2); // 1.01
-

sdbm

Hashes the input string into a whole number.

Use String.split('') and Array.reduce() to create a hash of the input string, utilizing bit shifting.

const sdbm = str => {
+
randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]
+
beginner

randomIntegerInRange

Returns a random integer in the specified range.

Use Math.random() to generate a random number and map it to the desired range, using Math.floor() to make it an integer.

const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
+
randomIntegerInRange(0, 5); // 2
+
intermediate

randomNumberInRange

Returns a random number in the specified range.

Use Math.random() to generate a random value, map it to the desired range using multiplication.

const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
+
randomNumberInRange(2, 10); // 6.0211363285087005
+
intermediate

round

Rounds a number to a specified amount of digits.

Use Math.round() and template literals to round the number to the specified number of digits. Omit the second argument, decimals to round to an integer.

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
+
round(1.005, 2); // 1.01
+
intermediate

sdbm

Hashes the input string into a whole number.

Use String.split('') and Array.reduce() to create a hash of the input string, utilizing bit shifting.

const sdbm = str => {
   let arr = str.split('');
   return arr.reduce(
     (hashCode, currentVal) =>
@@ -248,32 +242,32 @@ own individual rating by supplying it as the third argument.
     0
   );
 };
-
sdbm('name'); // -3521204949
-

standardDeviation

Returns the standard deviation of an array of numbers.

Use Array.reduce() to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then determine the standard deviation. You can omit the second argument to get the sample standard deviation or set it to true to get the population standard deviation.

const standardDeviation = (arr, usePopulation = false) => {
+
sdbm('name'); // -3521204949
+
intermediate

standardDeviation

Returns the standard deviation of an array of numbers.

Use Array.reduce() to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then determine the standard deviation. You can omit the second argument to get the sample standard deviation or set it to true to get the population standard deviation.

const standardDeviation = (arr, usePopulation = false) => {
   const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;
   return Math.sqrt(
     arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) /
       (arr.length - (usePopulation ? 0 : 1))
   );
 };
-
standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample)
+
standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample)
 standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population)
-

sum

Returns the sum of two or more numbers/arrays.

Use Array.reduce() to add each value to an accumulator, initialized with a value of 0.

const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
-
sum(...[1, 2, 3, 4]); // 10
-

sumBy

Returns the sum of an array, after mapping each element to a value using the provided function.

Use Array.map() to map each element to the value returned by fn, Array.reduce() to add each value to an accumulator, initialized with a value of 0.

const sumBy = (arr, fn) =>
+
beginner

sum

Returns the sum of two or more numbers/arrays.

Use Array.reduce() to add each value to an accumulator, initialized with a value of 0.

const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
+
sum(...[1, 2, 3, 4]); // 10
+
intermediate

sumBy

Returns the sum of an array, after mapping each element to a value using the provided function.

Use Array.map() to map each element to the value returned by fn, Array.reduce() to add each value to an accumulator, initialized with a value of 0.

const sumBy = (arr, fn) =>
   arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0);
-
sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20
+
sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20
 sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20
-

sumPower

Returns the sum of the powers of all the numbers from start to end (both inclusive).

Use Array.fill() to create an array of all the numbers in the target range, Array.map() and the exponent operator (**) to raise them to power and Array.reduce() to add them together. Omit the second argument, power, to use a default power of 2. Omit the third argument, start, to use a default starting value of 1.

const sumPower = (end, power = 2, start = 1) =>
+
intermediate

sumPower

Returns the sum of the powers of all the numbers from start to end (both inclusive).

Use Array.fill() to create an array of all the numbers in the target range, Array.map() and the exponent operator (**) to raise them to power and Array.reduce() to add them together. Omit the second argument, power, to use a default power of 2. Omit the third argument, start, to use a default starting value of 1.

const sumPower = (end, power = 2, start = 1) =>
   Array(end + 1 - start)
     .fill(0)
     .map((x, i) => (i + start) ** power)
     .reduce((a, b) => a + b, 0);
-
sumPower(10); // 385
+
sumPower(10); // 385
 sumPower(10, 3); //3025
 sumPower(10, 3, 5); //2925
-

toSafeInteger

Converts a value to a safe integer.

Use Math.max() and Math.min() to find the closest safe value. Use Math.round() to convert to an integer.

const toSafeInteger = num =>
+
intermediate

toSafeInteger

Converts a value to a safe integer.

Use Math.max() and Math.min() to find the closest safe value. Use Math.round() to convert to an integer.

const toSafeInteger = num =>
   Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
-
toSafeInteger('3.2'); // 3
+
toSafeInteger('3.2'); // 3
 toSafeInteger(Infinity); // 9007199254740991
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/mini.css b/docs/mini.css deleted file mode 100644 index 1fcd44898..000000000 --- a/docs/mini.css +++ /dev/null @@ -1 +0,0 @@ -:root{--f-col:#111;--f-col2:#444;--b-col:#f8f8f8;--b-col2:#f0f0f0;--blq-col:#f57c00;--pre-col:#1565c0;--br-col:#aaa;--br-col2:#ddd;--h-ratio:1.19;--u-m:.5rem;--u-p:.5rem;--u-br-r:.125rem;--a-l-col:#0277bd;--a-v-col:#01579b}html{font-size:16px}a,b,del,em,i,ins,q,span,strong,u{font-size:1em}html,*{font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Ubuntu, "Helvetica Neue", Helvetica, sans-serif;line-height:1.5;-webkit-text-size-adjust:100%}*{font-size:1rem}body{margin:0;color:var(--f-col);background:var(--b-col)}details{display:block}summary{display:list-item}abbr[title]{border-bottom:none;text-decoration:underline dotted}input{overflow:visible}img{max-width:100%;height:auto}h1,h2,h3,h4,h5,h6{line-height:1.2;margin:calc(1.5 * var(--u-m)) var(--u-m);font-weight:500}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{color:var(--f-col2);display:block;margin-top:-.25rem}h1{font-size:calc(1rem * var(--h-ratio) * var(--h-ratio) * var(--h-ratio) * var(--h-ratio))}h2{font-size:calc(1rem * var(--h-ratio) * var(--h-ratio) * var(--h-ratio))}h3{font-size:calc(1rem * var(--h-ratio) * var(--h-ratio))}h4{font-size:calc(1rem * var(--h-ratio))}h5{font-size:1rem}h6{font-size:calc(1rem / var(--h-ratio))}p{margin:var(--u-m)}ol,ul{margin:var(--u-m);padding-left:calc(2 * var(--u-m))}b,strong{font-weight:700}hr{box-sizing:content-box;border:0;line-height:1.25em;margin:var(--u-m);height:.0625rem;background:linear-gradient(to right, transparent, var(--br-col) 20%, var(--br-col) 80%, transparent)}blockquote{display:block;position:relative;font-style:italic;color:var(--f-col2);margin:var(--u-m);padding:calc(3 * var(--u-p));border:.0625rem solid var(--br-col2);border-left:.375rem solid var(--blq-col);border-radius:0 var(--u-br-r) var(--u-br-r) 0}blockquote:before{position:absolute;top:calc(0rem - var(--u-p));left:0;font-family:sans-serif;font-size:3rem;font-weight:700;content:"\201c";color:var(--blq-col)}blockquote[cite]:after{font-style:normal;font-size:.75em;font-weight:700;content:"\a— " attr(cite);white-space:pre}code,kbd,pre,samp{font-family:Menlo, Consolas, monospace;font-size:.85em}code{background:var(--b-col2);border-radius:var(--u-br-r);padding:calc(var(--u-p) / 4) calc(var(--u-p) / 2)}kbd{background:var(--f-col);color:var(--b-col);border-radius:var(--u-br-r);padding:calc(var(--u-p) / 4) calc(var(--u-p) / 2)}pre{overflow:auto;background:var(--b-col2);padding:calc(1.5 * var(--u-p));margin:var(--u-m);border:.0625rem solid var(--br-col2);border-left:.25rem solid var(--pre-col);border-radius:0 var(--u-br-r) var(--u-br-r) 0}sup,sub,code,kbd{line-height:0;position:relative;vertical-align:baseline}small,sup,sub,figcaption{font-size:.75em}sup{top:-.5em}sub{bottom:-.25em}figure{margin:var(--u-m)}figcaption{color:var(--f-col2)}a{text-decoration:none}a:link{color:var(--a-l-col)}a:visited{color:var(--a-v-col)}a:hover,a:focus{text-decoration:underline}.container{margin:0 auto;padding:0 calc(1.5 * var(--u-p))}.row{box-sizing:border-box;display:flex;flex:0 1 auto;flex-flow:row wrap}.col-sm,[class^='col-sm-'],[class^='col-sm-o-']{flex:0 0 auto;padding:0 calc(var(--u-p) / 2)}.col-sm{max-width:100%;flex-grow:1;flex-basis:0}.col-sm-1{max-width:8.33333%;flex-basis:8.33333%}.col-sm-o-0{margin-left:0}.col-sm-2{max-width:16.66667%;flex-basis:16.66667%}.col-sm-o-1{margin-left:8.33333%}.col-sm-3{max-width:25%;flex-basis:25%}.col-sm-o-2{margin-left:16.66667%}.col-sm-4{max-width:33.33333%;flex-basis:33.33333%}.col-sm-o-3{margin-left:25%}.col-sm-5{max-width:41.66667%;flex-basis:41.66667%}.col-sm-o-4{margin-left:33.33333%}.col-sm-6{max-width:50%;flex-basis:50%}.col-sm-o-5{margin-left:41.66667%}.col-sm-7{max-width:58.33333%;flex-basis:58.33333%}.col-sm-o-6{margin-left:50%}.col-sm-8{max-width:66.66667%;flex-basis:66.66667%}.col-sm-o-7{margin-left:58.33333%}.col-sm-9{max-width:75%;flex-basis:75%}.col-sm-o-8{margin-left:66.66667%}.col-sm-10{max-width:83.33333%;flex-basis:83.33333%}.col-sm-o-9{margin-left:75%}.col-sm-11{max-width:91.66667%;flex-basis:91.66667%}.col-sm-o-10{margin-left:83.33333%}.col-sm-12{max-width:100%;flex-basis:100%}.col-sm-o-11{margin-left:91.66667%}.col-sm-n{order:initial}.col-sm-f{order:-999}.col-sm-l{order:999}@media screen and (min-width: 768px){.col-md,[class^='col-md-'],[class^='col-md-o-']{flex:0 0 auto;padding:0 calc(var(--u-p) / 2)}.col-md{max-width:100%;flex-grow:1;flex-basis:0}.col-md-1{max-width:8.33333%;flex-basis:8.33333%}.col-md-o-0{margin-left:0}.col-md-2{max-width:16.66667%;flex-basis:16.66667%}.col-md-o-1{margin-left:8.33333%}.col-md-3{max-width:25%;flex-basis:25%}.col-md-o-2{margin-left:16.66667%}.col-md-4{max-width:33.33333%;flex-basis:33.33333%}.col-md-o-3{margin-left:25%}.col-md-5{max-width:41.66667%;flex-basis:41.66667%}.col-md-o-4{margin-left:33.33333%}.col-md-6{max-width:50%;flex-basis:50%}.col-md-o-5{margin-left:41.66667%}.col-md-7{max-width:58.33333%;flex-basis:58.33333%}.col-md-o-6{margin-left:50%}.col-md-8{max-width:66.66667%;flex-basis:66.66667%}.col-md-o-7{margin-left:58.33333%}.col-md-9{max-width:75%;flex-basis:75%}.col-md-o-8{margin-left:66.66667%}.col-md-10{max-width:83.33333%;flex-basis:83.33333%}.col-md-o-9{margin-left:75%}.col-md-11{max-width:91.66667%;flex-basis:91.66667%}.col-md-o-10{margin-left:83.33333%}.col-md-12{max-width:100%;flex-basis:100%}.col-md-o-11{margin-left:91.66667%}.col-md-n{order:initial}.col-md-f{order:-999}.col-md-l{order:999}}@media screen and (min-width: 1280px){.col-lg,[class^='col-lg-'],[class^='col-lg-o-']{flex:0 0 auto;padding:0 calc(var(--u-p) / 2)}.col-lg{max-width:100%;flex-grow:1;flex-basis:0}.col-lg-1{max-width:8.33333%;flex-basis:8.33333%}.col-lg-o-0{margin-left:0}.col-lg-2{max-width:16.66667%;flex-basis:16.66667%}.col-lg-o-1{margin-left:8.33333%}.col-lg-3{max-width:25%;flex-basis:25%}.col-lg-o-2{margin-left:16.66667%}.col-lg-4{max-width:33.33333%;flex-basis:33.33333%}.col-lg-o-3{margin-left:25%}.col-lg-5{max-width:41.66667%;flex-basis:41.66667%}.col-lg-o-4{margin-left:33.33333%}.col-lg-6{max-width:50%;flex-basis:50%}.col-lg-o-5{margin-left:41.66667%}.col-lg-7{max-width:58.33333%;flex-basis:58.33333%}.col-lg-o-6{margin-left:50%}.col-lg-8{max-width:66.66667%;flex-basis:66.66667%}.col-lg-o-7{margin-left:58.33333%}.col-lg-9{max-width:75%;flex-basis:75%}.col-lg-o-8{margin-left:66.66667%}.col-lg-10{max-width:83.33333%;flex-basis:83.33333%}.col-lg-o-9{margin-left:75%}.col-lg-11{max-width:91.66667%;flex-basis:91.66667%}.col-lg-o-10{margin-left:83.33333%}.col-lg-12{max-width:100%;flex-basis:100%}.col-lg-o-11{margin-left:91.66667%}.col-lg-n{order:initial}.col-lg-f{order:-999}.col-lg-l{order:999}}:root{--cd-b-col:#f8f8f8;--cd-f-col:#111;--cd-br-col:#ddd}.card{display:flex;flex-direction:column;justify-content:space-between;align-self:center;position:relative;width:100%;background:var(--cd-b-col);color:var(--cd-f-col);border:.0625rem solid var(--cd-br-col);border-radius:var(--u-br-r);margin:var(--u-m);overflow:hidden}@media screen and (min-width: 320px){.card{max-width:320px}}.card>.section{background:var(--cd-b-col);color:var(--cd-f-col);box-sizing:border-box;margin:0;border:0;border-radius:0;border-bottom:.0625rem solid var(--cd-br-col);padding:var(--u-p);width:100%}.card>.section.media{height:200px;padding:0;-o-object-fit:cover;object-fit:cover}.card>.section:last-child{border-bottom:0}.card.fluid{max-width:100%;width:auto}.card>.section.double-padded{padding:calc(1.5 * var(--u-p))}.card{box-shadow:0 1.25rem 2.5rem -0.625rem rgba(0,32,64,0.1)}.card>h3.section.double-padded{padding:calc(3 * var(--u-p))}.card>.section.double-padded>p{margin:var(--u-m) calc(var(--u-m) / 2)}.card+.card{margin-top:calc(5 * var(--u-m))}:root{--frm-b-col:#f0f0f0;--frm-f-col:#111;--frm-br-col:#ddd;--in-b-col:#f8f8f8;--in-f-col:#111;--in-br-col:#ddd;--in-fc-col:#0288d1;--in-inv-col:#d32f2f;--btn-b-col:#e2e2e2;--btn-h-b-col:#dcdcdc;--btn-f-col:#212121;--btn-br-col:rgba(0,0,0,0);--btn-h-br-col:rgba(0,0,0,0);--btn-grp-br-col:rgba(124,124,124,0.54)}form{background:var(--frm-b-col);color:var(--frm-f-col);border:.0625rem solid var(--frm-br-col);border-radius:var(--u-br-r);margin:var(--u-m);padding:calc(2 * var(--u-p)) var(--u-p)}fieldset{border:.0625rem solid var(--frm-br-col);border-radius:var(--u-br-r);margin:calc(var(--u-m) / 4);padding:var(--u-p)}legend{box-sizing:border-box;display:table;max-width:100%;white-space:normal;font-weight:700;padding:calc(var(--u-p) / 2)}label{padding:calc(var(--u-p) / 2) var(--u-p)}.input-group{display:inline-block}.input-group.fluid{display:flex;align-items:center;justify-content:center}.input-group.fluid>input{max-width:100%;flex-grow:1;flex-basis:0px}@media screen and (max-width: 767px){.input-group.fluid{align-items:stretch;flex-direction:column}}.input-group.vertical{display:flex;align-items:stretch;flex-direction:column}.input-group.vertical>input{max-width:100%;flex-grow:1;flex-basis:0px}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}[type="search"]{-webkit-appearance:textfield;outline-offset:-2px}[type="search"]::-webkit-search-cancel-button,[type="search"]::-webkit-search-decoration{-webkit-appearance:none}input:not([type]),[type="text"],[type="email"],[type="number"],[type="search"],[type="password"],[type="url"],[type="tel"],[type="checkbox"],[type="radio"],textarea,select{box-sizing:border-box;background:var(--in-b-col);color:var(--in-f-col);border:.0625rem solid var(--in-br-col);border-radius:var(--u-br-r);margin:calc(var(--u-m) / 2);padding:var(--u-p) calc(1.5 * var(--u-p))}input:not([type="button"]):not([type="submit"]):not([type="reset"]):hover,input:not([type="button"]):not([type="submit"]):not([type="reset"]):focus,textarea:hover,textarea:focus,select:hover,select:focus{border-color:var(--in-fc-col);box-shadow:none}input:not([type="button"]):not([type="submit"]):not([type="reset"]):invalid,input:not([type="button"]):not([type="submit"]):not([type="reset"]):focus:invalid,textarea:invalid,textarea:focus:invalid,select:invalid,select:focus:invalid{border-color:var(--in-inv-col);box-shadow:none}input:not([type="button"]):not([type="submit"]):not([type="reset"])[readonly],textarea[readonly],select[readonly]{background:var(--b-col2)}select{max-width:100%}option{overflow:hidden;text-overflow:ellipsis}[type="checkbox"],[type="radio"]{-webkit-appearance:none;-moz-appearance:none;appearance:none;position:relative;height:calc(1rem + var(--u-p) / 2);width:calc(1rem + var(--u-p) / 2);vertical-align:text-bottom;padding:0;flex-basis:calc(1rem + var(--u-p) / 2) !important;flex-grow:0 !important}[type="checkbox"]:checked:before,[type="radio"]:checked:before{position:absolute}[type="checkbox"]:checked:before{content:'\2713';font-family:sans-serif;font-size:calc(1rem + var(--u-p) / 2);top:calc(0rem - var(--u-p));left:calc(var(--u-p) / 4)}[type="radio"]{border-radius:100%}[type="radio"]:checked:before{border-radius:100%;content:'';top:calc(.0625rem + var(--u-p) / 2);left:calc(.0625rem + var(--u-p) / 2);background:var(--in-f-col);width:0.5rem;height:0.5rem}:placeholder-shown{color:var(--in-f-col)}::-ms-placeholder{color:var(--in-f-col);opacity:0.54}button::-moz-focus-inner,[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner{border-style:none;padding:0}button,html [type="button"],[type="reset"],[type="submit"]{-webkit-appearance:button}button{overflow:visible;text-transform:none}button,[type="button"],[type="submit"],[type="reset"],a.button,label.button,.button,a[role="button"],label[role="button"],[role="button"]{display:inline-block;background:var(--btn-b-col);color:var(--btn-f-col);border:.0625rem solid var(--btn-br-col);border-radius:var(--u-br-r);padding:var(--u-p) calc(1.5 * var(--u-p));margin:var(--u-m);text-decoration:none;cursor:pointer;transition:background 0.3s}button:hover,button:focus,[type="button"]:hover,[type="button"]:focus,[type="submit"]:hover,[type="submit"]:focus,[type="reset"]:hover,[type="reset"]:focus,a.button:hover,a.button:focus,label.button:hover,label.button:focus,.button:hover,.button:focus,a[role="button"]:hover,a[role="button"]:focus,label[role="button"]:hover,label[role="button"]:focus,[role="button"]:hover,[role="button"]:focus{background:var(--btn-h-b-col);border-color:var(--btn-h-br-col)}input:disabled,input[disabled],textarea:disabled,textarea[disabled],select:disabled,select[disabled],button:disabled,button[disabled],.button:disabled,.button[disabled],[role="button"]:disabled,[role="button"][disabled]{cursor:not-allowed;opacity:.75}.button-group{display:flex;border:.0625rem solid var(--btn-grp-br-col);border-radius:var(--u-br-r);margin:var(--u-m)}.button-group>button,.button-group [type="button"],.button-group>[type="submit"],.button-group>[type="reset"],.button-group>.button,.button-group>[role="button"]{margin:0;max-width:100%;flex:1 1 auto;text-align:center;border:0;border-radius:0;box-shadow:none}.button-group>:not(:first-child){border-left:.0625rem solid var(--btn-grp-br-col)}@media screen and (max-width: 767px){.button-group{flex-direction:column}.button-group>:not(:first-child){border:0;border-top:.0625rem solid var(--btn-grp-br-col)}}button.primary,[type="button"].primary,[type="submit"].primary,[type="reset"].primary,.button.primary,[role="button"].primary{--btn-b-col:#1976d2;--btn-f-col:#f8f8f8}button.primary:hover,button.primary:focus,[type="button"].primary:hover,[type="button"].primary:focus,[type="submit"].primary:hover,[type="submit"].primary:focus,[type="reset"].primary:hover,[type="reset"].primary:focus,.button.primary:hover,.button.primary:focus,[role="button"].primary:hover,[role="button"].primary:focus{--btn-h-b-col:#1565c0}:root{--hd-b-col:#f8f8f8;--hd-hv-b-col:#f0f0f0;--hd-f-col:#444;--hd-br-col:#ddd;--nv-b-col:#f8f8f8;--nv-hv-b-col:#f0f0f0;--nv-f-col:#444;--nv-br-col:#ddd;--nv-ln-col:#0277bd;--ft-f-col:#444;--ft-b-col:#f8f8f8;--ft-br-col:#ddd;--ft-ln-col:#0277bd;--dr-b-col:#f8f8f8;--dr-hv-b-col:#f0f0f0;--dr-br-col:#ddd;--dr-cl-col:#444}header{height:3.1875rem;background:var(--hd-b-col);color:var(--hd-f-col);border-bottom:.0625rem solid var(--hd-br-col);padding:calc(var(--u-p) / 4) 0;white-space:nowrap;overflow-x:auto;overflow-y:hidden}header.row{box-sizing:content-box}header .logo{color:var(--hd-f-col);font-size:1.75rem;padding:var(--u-p) calc(2 * var(--u-p));text-decoration:none}header button,header [type="button"],header .button,header [role="button"]{box-sizing:border-box;position:relative;top:calc(0rem - var(--u-p) / 4);height:calc(3.1875rem + var(--u-p) / 2);background:var(--hd-b-col);line-height:calc(3.1875rem - var(--u-p) * 1.5);text-align:center;color:var(--hd-f-col);border:0;border-radius:0;margin:0;text-transform:uppercase}header button:hover,header button:focus,header [type="button"]:hover,header [type="button"]:focus,header .button:hover,header .button:focus,header [role="button"]:hover,header [role="button"]:focus{background:var(--hd-hv-b-col)}nav{background:var(--nv-b-col);color:var(--nv-f-col);border:.0625rem solid var(--nv-br-col);border-radius:var(--u-br-r);margin:var(--u-m)}nav *{padding:var(--u-p) calc(1.5 * var(--u-p))}nav a,nav a:visited{display:block;color:var(--nv-ln-col);border-radius:var(--u-br-r);transition:background 0.3s}nav a:hover,nav a:focus,nav a:visited:hover,nav a:visited:focus{text-decoration:none;background:var(--nv-hv-b-col)}nav .sublink-1{position:relative;margin-left:calc(2 * var(--u-p))}nav .sublink-1:before{position:absolute;left:calc(var(--u-p) - 1 * var(--u-p));top:-.0625rem;content:'';height:100%;border:.0625rem solid var(--nv-br-col);border-left:0}footer{background:var(--ft-b-col);color:var(--ft-f-col);border-top:.0625rem solid var(--ft-br-col);padding:calc(2 * var(--u-p)) var(--u-p);font-size:.875rem}footer a,footer a:visited{color:var(--ft-ln-col)}header.sticky{position:-webkit-sticky;position:sticky;z-index:1101;top:0}footer.sticky{position:-webkit-sticky;position:sticky;z-index:1101;bottom:0}.drawer-toggle:before{display:inline-block;position:relative;vertical-align:bottom;content:'\00a0\2261\00a0';font-family:sans-serif;font-size:1.5em}@media screen and (min-width: 768px){.drawer-toggle:not(.persistent){display:none}}[type="checkbox"].drawer{height:1px;width:1px;margin:-1px;overflow:hidden;position:absolute;clip:rect(0 0 0 0);-webkit-clip-path:inset(100%);clip-path:inset(100%)}[type="checkbox"].drawer+*{display:block;box-sizing:border-box;position:fixed;top:0;width:320px;height:100vh;overflow-y:auto;background:var(--dr-b-col);border:.0625rem solid var(--dr-br-col);border-radius:0;margin:0;z-index:1110;left:-320px;transition:left 0.3s}[type="checkbox"].drawer+* .drawer-close{position:absolute;top:var(--u-m);right:var(--u-m);z-index:1111;width:2rem;height:2rem;border-radius:var(--u-br-r);padding:var(--u-p);margin:0;cursor:pointer;transition:background 0.3s}[type="checkbox"].drawer+* .drawer-close:before{display:block;content:'\00D7';color:var(--dr-cl-col);position:relative;font-family:sans-serif;font-size:2rem;line-height:1;text-align:center}[type="checkbox"].drawer+* .drawer-close:hover,[type="checkbox"].drawer+* .drawer-close:focus{background:var(--dr-hv-b-col)}@media screen and (max-width: 320px){[type="checkbox"].drawer+*{width:100%}}[type="checkbox"].drawer:checked+*{left:0}@media screen and (min-width: 768px){[type="checkbox"].drawer:not(.persistent)+*{position:static;height:100%;z-index:1100}[type="checkbox"].drawer:not(.persistent)+* .drawer-close{display:none}}:root{--mrk-b-col:#424242;--mrk-f-col:#fafafa}mark{background:var(--mrk-b-col);color:var(--mrk-f-col);font-size:.5em;line-height:1em;border-radius:var(--u-br-r);padding:calc(var(--u-p) / 4) calc(var(--u-p) / 2)}mark.inline-block{display:inline-block;font-size:1em;line-height:1.5;padding:calc(var(--u-p) / 2) var(--u-p)}:root{--tst-b-col:#212121;--tst-f-col:#fafafa}.toast{position:fixed;bottom:calc(var(--u-m) * 3);left:50%;transform:translate(-50%, -50%);z-index:1111;color:var(--tst-f-col);background:var(--tst-b-col);border-radius:calc(var(--u-br-r) * 16);padding:var(--u-p) calc(var(--u-p) * 3)}div,main,nav{-webkit-overflow-scrolling:touch}.toast{bottom:calc(var(--u-m) / 2);opacity:1;transition:opacity 0.3s ease-in-out}mark{position:relative;top:-0.25rem;left:0.25rem}mark.secondary{--mrk-b-col:#d32f2f}mark.tertiary{--mrk-b-col:#308732}mark.tag{padding:calc(var(--u-p)/2) var(--u-p);border-radius:1em}code,pre,kbd,code *,pre *,kbd *,code[class*="language-"],pre[class*="language-"]{font-family:Menlo, Consolas, monospace !important}pre{border:0.0625rem solid var(--br-col2);border-radius:var(--u-br-r)}.search{font-size:0.875rem}header h1.logo{margin-top:-0.8rem;text-align:center;position:relative;top:0;transition:top 0.3s;color:#111}h1 a,h1 a:link,h1 a:visited{text-decoration:none;color:#111}h1 a:hover,h1 a:focus,h1 a:link:hover,h1 a:link:focus,h1 a:visited:hover,h1 a:visited:focus{text-decoration:none;color:#111}header #title{position:relative;top:-1rem}@media screen and (max-width: 768px){header #title{display:none}}header{background:linear-gradient(135deg, #ffae27 0%, #de496d 100%)}header h1 small{display:block;font-size:0.875rem;color:#888;margin-top:0.75rem}label#menu-toggle{position:absolute;left:0rem;top:0rem;width:3.4375rem}main{padding:0}:root{--clps-lbl-b-col:#e8e8e8;--clps-lbl-f-col:#212121;--clps-lbl-h-b-col:#f0f0f0;--clps-sel-lbl-b-col:#ececec;--clps-br-col:#ddd;--clps-cnt-b-col:#fafafa;--clps-sel-lbl-br-col:#0277bd}label.collapse{width:100%;display:inline-block;cursor:pointer;box-sizing:border-box;transition:background 0.3s;color:var(--clps-lbl-f-col);background:var(--clps-lbl-b-col);border:.0625rem solid var(--clps-br-col);padding:calc(1.5 * var(--u-p));border-radius:var(--u-br-r)}label.collapse:hover,label.collapse:focus{background:var(--clps-lbl-h-b-col)}label.collapse+pre{box-sizing:border-box;height:0;max-height:1px;overflow:auto;margin:0;border:0;padding:0;transition:max-height 0.3s}label.collapse.toggled{background:var(--clps-sel-lbl-b-col);border-bottom-color:var(--clps-sel-lbl-br-col);border-bottom-left-radius:0;border-bottom-right-radius:0}label.collapse.toggled+pre{border-top-left-radius:0;border-top-right-radius:0;position:relative;width:100%;height:auto;border:.0625rem solid var(--clps-br-col);border-top:0;padding:calc(2 * var(--u-p));max-height:400px}button.primary.clipboard-copy{width:100%;margin-left:0}button.primary.clipboard-copy>img{vertical-align:bottom}code[class*="language-"],pre[class*="language-"]{color:#222;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.8;-moz-tab-size:2;-o-tab-size:2;tab-size:2;-webkit-hypens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*="language-"]{padding:calc(2 * var(--u-p));overflow:auto;margin:var(--u-m) 0}pre[class*="language-"]::-moz-selection,pre[class*="language-"] ::-moz-selection,code[class*="language-"]::-moz-selection,code[class*="language-"] ::-moz-selection{background:#b3d4fc}pre[class*="language-"]::selection,pre[class*="language-"] ::selection,code[class*="language-"]::selection,code[class*="language-"] ::selection{background:#b3d4fc}:not(pre)>code[class*="language-"]{padding:.1em;border-radius:.3em;white-space:normal}.token.comment,.token.prolog,.token.doctype,.token.cdata{color:#7a8490}.token.punctuation{color:#666}.namespace{opacity:.7}.token.property,.token.tag,.token.boolean,.token.constant,.token.symbol,.token.deleted,.token.function{color:#005cc5}.token.number,.token.class-name{color:#832ed2}.token.selector,.token.attr-name,.token.string,.token.char,.token.builtin,.token.inserted{color:#067e36}.token.operator,.token.entity,.token.url,.language-css .token.string,.style .token.string,.token.atrule,.token.attr-value,.token.keyword{color:#d73a49}.token.regex{color:#097cab}.token.important,.token.variable{color:#e90}.token.important,.token.bold{font-weight:bold}.token.italic{font-style:italic}.token.entity{cursor:help}button.scroll-to-top{border-radius:100%;font-size:1.5rem;line-height:1;box-sizing:border-box;width:2.75rem;height:2.75rem;position:fixed;bottom:1rem;right:2rem;background:var(--b-col);box-shadow:0 0.25rem 0.25rem 0 rgba(0,0,0,0.125),0 0.125rem 0.125rem -0.125rem rgba(0,0,0,0.25)}button.scroll-to-top:hover,button.scroll-to-top:focus{background:var(--b-col2)}.card#disclaimer{position:fixed;bottom:0;z-index:1100;max-width:100vw;width:100vw;left:0;text-align:center;font-size:1.5rem;margin:0}@media screen and (min-width: 768px){.card#disclaimer{width:60vw;left:20vw;bottom:1rem}}@media screen and (min-width: 1280px){.card#disclaimer{width:40vw;left:30vw;bottom:1.5rem}}button#disclaimer-close{position:absolute;top:-0.5rem;right:-0.5rem;font-size:0.85rem;background:0}#splash{height:auto;padding-bottom:1.5rem;background:linear-gradient(135deg, #ffae27 0%, #de496d 100%)}#splash #logo{margin-top:0;margin-left:-0.5rem;padding-top:2rem;text-align:center;font-size:2.25rem;line-height:2}#splash #logo img{vertical-align:top;height:4.5rem}#splash #tagline{text-align:center;padding:0.5rem 25%}#splash #doc-link{text-align:center;margin-left:-0.5rem}#splash #doc-link>a{background:transparent;border:0.0625rem solid rgba(17,17,17,0.95);transition:all 0.3s}#splash #doc-link>a:hover,#splash #doc-link>a:focus{background:rgba(17,17,17,0.95);color:#e86957}@media screen and (max-width: 767px){#splash #logo{font-size:1.75rem}#splash #logo img{height:3.5rem}#splash #tagline{padding:0.25rem 17.5%;font-size:0.875rem}#splash #doc-link{font-size:0.875rem}}@media screen and (max-width: 383px){#splash #logo{font-size:1.5rem}#splash #logo img{height:3rem}#splash #tagline{padding:0.125rem 5%}}@media screen and (max-width: 479px){#splash #tagline #tagline-lg{display:none}}@media screen and (min-width: 768px){.col-md-offset-1{margin-left:8.33333%}}@media screen and (min-width: 1280px){.col-lg-offset-2{margin-left:16.66667%}}h2.index-section{border-left:0.3125rem solid #de4a6d;padding-left:0.625rem;margin-top:2rem}#license-icon{text-align:center}@media screen and (min-width: 768px){#license-icon{position:relative;top:calc(50% - 40px)}}#license-icon>svg{border:0.03125rem solid #444;border-radius:100%;padding:0.5rem;fill:#444}#license{vertical-align:middle}.no-padding{padding:0}#in-numbers{background:#111;padding-top:0.75rem;padding-bottom:0.75rem;color:#fff}#in-numbers svg{fill:#fff}@media screen and (min-width: 768px){#in-numbers svg{position:relative;top:20px;left:-34px;width:32px;height:32px}}#in-numbers p{overflow-wrap:break-word;margin-top:0;font-size:0.625rem;margin-bottom:0}@media screen and (min-width: 768px){#in-numbers p{position:relative;top:-24px;left:22px;font-size:0.75rem}}#snippet-count,#contrib-count,#commit-count,#star-count{font-size:1rem}@media screen and (min-width: 768px){#snippet-count,#contrib-count,#commit-count,#star-count{font-size:1.25rem}}ul#links{list-style:none;padding-left:0}ul#links li+li{padding-top:0.625rem}.pick:not(.selected){display:none}.card.pick{transition:all 0.6s;left:0}.card.pick+.card.pick{margin-top:0.5rem}.pick.selected{overflow:visible}.pick.selected button.next{position:absolute;top:50%;right:-1rem}.pick.selected button.next>svg{margin-right:-0.0625rem}#pick-slider{position:relative}button.previous{left:-1%}button.previous>svg{margin-left:-0.125rem}button.next{right:-1%}button.next>svg{margin-left:0.0625rem}button.previous,button.next{position:absolute;top:50%;border-radius:100%;background:#f8f8f8;border:0.03125rem solid #ddd;width:1.5rem;height:1.5rem;padding:0;margin:0;transition:all 0.3s;z-index:2000}button.previous>svg,button.next>svg{fill:#888;transition:all 0.3s}button.previous:hover,button.previous:focus,button.next:hover,button.next:focus{border-color:#aaa}button.previous:hover>svg,button.previous:focus>svg,button.next:hover>svg,button.next:focus>svg{fill:#444}.card.contributor{height:calc(100% - 1rem);justify-content:left}.card.contributor>.section.media{height:auto}.card.contributor>.section.button{font-size:0.75rem;font-weight:700;text-align:center;transition:color 0.3s}.card.contributor>.section.button:hover,.card.contributor>.section.button:focus{color:var(--a-l-col);background:#f8f8f8}.card.fluid.contribution-guideline{overflow:visible;margin-top:3rem;padding-bottom:0.25rem}.card.fluid.contribution-guideline h3{padding-top:0.5rem;text-align:center}.contribution-guideline+.contribution-guideline:before,.contribution-guideline+.contribution-guideline:after{content:"";position:relative;top:-2.75rem;width:0.375rem;height:0.375rem;background:#ddd;border:0.03125rem solid #d0d0d0;border-radius:100%;left:calc(50% - 0.1875rem);box-shadow:inset -0.03125rem -0.03125rem 0.03125rem rgba(0,0,0,0.05)}.contribution-guideline+.contribution-guideline:after{position:absolute;top:-1.875rem}.contribution-number{position:absolute;top:-1.125rem;left:calc(50% - 1.125rem);font-size:1.5rem;background:linear-gradient(135deg, #ffae27 0%, #de496d 100%);border:0.03125 solid #ddd;width:2.25rem;text-align:center;height:2.25rem;border-radius:100%;font-weight:700;color:#fff}body{overflow-x:hidden}label.button.drawer-toggle{background:transparent;color:#111}label.button.drawer-toggle:hover,label.button.drawer-toggle:focus{background:transparent}nav .input-group.vertical{position:sticky;top:0;z-index:10;background:#f8f8f8;border-bottom:0.0625rem solid var(--nv-br-col)} diff --git a/docs/mini/_contextual.scss b/docs/mini/_contextual.scss deleted file mode 100644 index 1dc2e66c9..000000000 --- a/docs/mini/_contextual.scss +++ /dev/null @@ -1,354 +0,0 @@ -/* - Definitions for contextual background elements, toasts and tooltips. -*/ -$mark-back-color: #0277bd !default; // Background color for -$mark-fore-color: #fafafa !default; // Text color for -$mark-font-size: 0.95em !default; // Font size for -$mark-line-height: 1em !default; // Line height for -$mark-inline-block-name: 'inline-block' !default;// Class name for inline-block -$_include-toast: true !default; // [Hidden] Should toasts be included? (boolean) -$toast-name: 'toast' !default; // Class name for toast component -$toast-back-color: #424242 !default; // Background color for toast component -$toast-fore-color: #fafafa !default; // Text color for toast component -$_include-tooltip: true !default; // [Hidden] Should tooltips be included? (boolean) -$tooltip-name: 'tooltip' !default; // Class name for tooltip component -$tooltip-bottom-name: 'bottom' !default; // Bottom tooltip class name -$tooltip-back-color: #212121 !default; // Background color for tooltip component -$tooltip-fore-color: #fafafa !default; // Text color for tooltip component -$_include-modal: true !default; // [Hidden] Should modal dialogs be included? (boolean) -$modal-name: 'modal' !default; // Class name for modal dialog component -$modal-overlay-color: rgba(0, 0, 0, 0.45) !default; // Overlay color for modal dialog component -$modal-close-name: 'modal-close' !default;// Class name for modal dialog close button -$modal-close-color: #444 !default; // Text color for the close button of the modal dialog component -$modal-close-hover-back-color: #f0f0f0 !default; // Background color for the close button of the modal dialog component (on hover/focus) -$modal-close-size: 1.75rem !default; // Font size for the close button of the modal dialog component -$_include-collapse: true !default; // [Hidden] Should collapse components be included? (boolean) -$collapse-name: 'collapse' !default; // Class name for collapse component -$collapse-label-height: 1.5rem !default; // Height for the labels in the collapse component -$collapse-content-max-height: 400px !default; // Max height for the content panes in the collapse component -$collapse-label-back-color: #e8e8e8 !default;// Background color for labels in the collapse component -$collapse-label-fore-color: #212121 !default;// Text color for labels in the collapse component -$collapse-label-hover-back-color:#f0f0f0 !default;// Background color for labels in the collapse component (hover) -$collapse-selected-label-back-color:#ececec !default;// Background color for selected labels in the collapse component -$collapse-border-color: #ddd !default; // Border color for collapse component -$collapse-selected-label-border-color: #0277bd !default; // Border color for collapse component's selected labels -$collapse-content-back-color: #fafafa !default; // Background color for collapse component's content panes -// CSS variable name definitions [exercise caution if modifying these] -$mark-back-color-var: '--mark-back-color' !default; -$mark-fore-color-var: '--mark-fore-color' !default; -$toast-back-color-var: '--toast-back-color' !default; -$toast-fore-color-var: '--toast-fore-color' !default; -$tooltip-back-color-var: '--tooltip-back-color' !default; -$tooltip-fore-color-var: '--tooltip-fore-color' !default; -$modal-overlay-color-var: '--modal-overlay-color' !default; -$modal-close-color-var: '--modal-close-color' !default; -$modal-close-hover-back-color-var: '--modal-close-hover-color' !default; -$collapse-label-back-color-var: '--collapse-label-back-color' !default; -$collapse-label-fore-color-var: '--collapse-label-fore-color' !default; -$collapse-label-hover-back-color-var: '--collapse-label-hover-back-color' !default; -$collapse-selected-label-back-color-var: '--collapse-selected-label-back-color' !default; -$collapse-border-color-var: '--collapse-border-color' !default; -$collapse-content-back-color-var: '--collapse-content-back-color' !default; -$collapse-selected-label-border-color-var: '--collapse-selected-label-border-color' !default; -// == Uncomment below code if this module is used on its own == -// -// $base-line-height: 1.5 !default; // Line height for most elements -// $universal-margin: 0.5rem !default; // Universal margin for the most elements -// $universal-padding: 0.5rem !default; // Universal padding for the most elements -// $universal-border-radius: 0.125rem !default; // Universal border-radius for most elements -// $universal-box-shadow: none !default; // Universal box-shadow for most elements -// $universal-margin-var: '--universal-margin' !default; -// $universal-padding-var: '--universal-padding' !default; -// $universal-border-radius-var: '--universal-border-radius' !default; -// $universal-box-shadow-var: '--universal-box-shadow' !default; -// :root { -// #{$universal-margin-var}: $universal-margin; -// #{$universal-padding-var}: $universal-padding; -// #{$universal-border-radius-var}: $universal-border-radius; -// @if $universal-box-shadow != none { -// #{$universal-box-shadow-var}: $universal-box-shadow; -// } -// } -// -// ============================================================ -// Check the `_contextual_mixins.scss` file to find this module's mixins. -@import '_contextual_mixins'; -/* Contextual module CSS variable definitions */ -:root { - #{$mark-back-color-var}: $mark-back-color; - #{$mark-fore-color-var}: $mark-fore-color; -} -// Default styling for mark. Use mixins for alternate styles. -mark { - background: var(#{$mark-back-color-var}); - color: var(#{$mark-fore-color-var}); - font-size: $mark-font-size; - line-height: $mark-line-height; - border-radius: var(#{$universal-border-radius-var}); - padding: calc(var(#{$universal-padding-var}) / 4) calc(var(#{$universal-padding-var}) / 2); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - &.#{$mark-inline-block-name} { - display: inline-block; - // This is hardcoded, as we want inline-block elements to be styled as normal pieces of text, instead of look small and weird. - font-size: 1em; - // Line height is reset to the normal line-height from `core`. Also hardcoded for same reasons. - line-height: $base-line-height; - padding: calc(var(#{$universal-padding-var}) / 2) var(#{$universal-padding-var}); - } -} -// Styling for toasts. - No border styling, I think it's unnecessary anyways. -@if $_include-toast { - :root { - #{$toast-back-color-var}: $toast-back-color; - #{$toast-fore-color-var}: $toast-fore-color; - } - .#{$toast-name} { - position: fixed; - bottom: calc(var(#{$universal-margin-var}) * 3); - left: 50%; - transform: translate(-50%, -50%); - z-index: 1111; - color: var(#{$toast-fore-color-var}); - background: var(#{$toast-back-color-var}); - border-radius: calc(var(#{$universal-border-radius-var}) * 16); - padding: var(#{$universal-padding-var}) calc(var(#{$universal-padding-var}) * 3); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - } -} -// Styling for tooltips. -@if $_include-tooltip { - :root { - #{$tooltip-back-color-var}: $tooltip-back-color; - #{$tooltip-fore-color-var}: $tooltip-fore-color; - } - .#{$tooltip-name} { - position: relative; - display: inline-block; - &:before, &:after { - position: absolute; - opacity: 0; - clip: rect(0 0 0 0); - -webkit-clip-path: inset(100%); - clip-path: inset(100%); - transition: all 0.3s; - // Remember to keep this index a lower value than the one used for stickies. - z-index: 1010; // Deals with certain problems when combined with cards and tables. - left: 50%; - } - &:not(.#{$tooltip-bottom-name}):before, &:not(.#{$tooltip-bottom-name}):after { // Top (default) tooltip styling - bottom: 75%; - } - &.#{$tooltip-bottom-name}:before, &.#{$tooltip-bottom-name}:after { // Bottom tooltip styling - top: 75%; - } - &:hover, &:focus { - &:before, &:after { - opacity: 1; - clip: auto; - -webkit-clip-path: inset(0%); - clip-path: inset(0%); - } - } - &:before { // This is the little tooltip triangle - content: ''; - background: transparent; - border: var(#{$universal-margin-var}) solid transparent; - // Newer browsers will center the tail properly - left: calc(50% - var(#{$universal-margin-var})); - } - &:not(.#{$tooltip-bottom-name}):before { // Top (default) tooltip styling - border-top-color: $tooltip-back-color; - } - &.#{$tooltip-bottom-name}:before { // Bottom tooltip styling - border-bottom-color: $tooltip-back-color; - } - &:after { // This is the actual tooltip's text block - content: attr(aria-label); - color: var(#{$tooltip-fore-color-var}); - background: var(#{$tooltip-back-color-var}); - border-radius: var(#{$universal-border-radius-var}); - padding: var(#{$universal-padding-var}); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - white-space: nowrap; - transform: translateX(-50%); - } - &:not(.#{$tooltip-bottom-name}):after { // Top (default) tooltip styling - margin-bottom: calc(2 * var(#{$universal-margin-var})); - } - &.#{$tooltip-bottom-name}:after { // Bottom tooltip styling - margin-top: calc(2 * var(#{$universal-margin-var})); - } - } -} -// Styling for modal dialogs. -@if $_include-modal { - :root { - #{$modal-overlay-color-var}: $modal-overlay-color; - #{$modal-close-color-var}: $modal-close-color; - #{$modal-close-hover-back-color-var}: $modal-close-hover-back-color; - } - [type="checkbox"].#{$modal-name} { - height: 1px; - width: 1px; - margin: -1px; - overflow: hidden; - position: absolute; - clip: rect(0 0 0 0); - -webkit-clip-path: inset(100%); - clip-path: inset(100%); - & + div { - position: fixed; - top: 0; - left: 0; - display: none; - width: 100vw; - height: 100vh; - background: var(#{$modal-overlay-color-var}); - & .card { - margin: 0 auto; - max-height: 50vh; - overflow: auto; - & .#{$modal-close-name} { - position: absolute; - top: 0; - right: 0; - width: $modal-close-size; - height: $modal-close-size; - border-radius: var(#{$universal-border-radius-var}); - padding: var(#{$universal-padding-var}); - margin: 0; - cursor: pointer; - transition: background 0.3s; - &:before { - display: block; - content: '\00D7'; - color: var(#{$modal-close-color-var}); - position: relative; - font-family: sans-serif; - font-size: $modal-close-size; - line-height: 1; - text-align: center; - } - &:hover, &:focus { - background: var(#{$modal-close-hover-back-color-var}); - } - } - } - } - &:checked + div { - display: flex; - flex: 0 1 auto; - z-index: 1200; - & .card { - & .#{$modal-close-name} { - z-index: 1211; - } - } - } - } -} -// Styling for collapse. -@if $_include-collapse { - :root { - #{$collapse-label-back-color-var}: $collapse-label-back-color; - #{$collapse-label-fore-color-var}: $collapse-label-fore-color; - #{$collapse-label-hover-back-color-var}: $collapse-label-hover-back-color; - #{$collapse-selected-label-back-color-var}: $collapse-selected-label-back-color; - #{$collapse-border-color-var}: $collapse-border-color; - #{$collapse-content-back-color-var} : $collapse-content-back-color; - #{$collapse-selected-label-border-color-var}: $collapse-selected-label-border-color; - } - .#{$collapse-name} { - width: calc(100% - 2 * var(#{$universal-margin-var})); - opacity: 1; - display: flex; - flex-direction: column; - margin: var(#{$universal-margin-var}); - border-radius: var(#{$universal-border-radius-var}); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - & > [type="radio"], & > [type="checkbox"] { - height: 1px; - width: 1px; - margin: -1px; - overflow: hidden; - position: absolute; - clip: rect(0 0 0 0); - -webkit-clip-path: inset(100%); - clip-path: inset(100%); - } - & > label { - flex-grow: 1; - display: inline-block; - height: $collapse-label-height; - cursor: pointer; - transition: background 0.3s; - color: var(#{$collapse-label-fore-color-var}); - background: var(#{$collapse-label-back-color-var}); - border: $__1px solid var(#{$collapse-border-color-var}); - padding: calc(1.5 * var(#{$universal-padding-var})); - &:hover, &:focus { - background: var(#{$collapse-label-hover-back-color-var}); - } - + div { - flex-basis: auto; - height: 1px; - width: 1px; - margin: -1px; - overflow: hidden; - position: absolute; - clip: rect(0 0 0 0); - -webkit-clip-path: inset(100%); - clip-path: inset(100%); - transition: max-height 0.3s; - max-height: 1px; // for transition - } - } - > :checked + label { - background: var(#{$collapse-selected-label-back-color-var}); - // border: 0.0625rem solid #bdbdbd; // var it - border-bottom-color: var(#{$collapse-selected-label-border-color-var}); - & + div { - box-sizing: border-box; - position: relative; - width: 100%; - height: auto; - overflow: auto; - margin: 0; - background: var(#{$collapse-content-back-color-var}); - border: $__1px solid var(#{$collapse-border-color-var}); - border-top: 0; - padding: var(#{$universal-padding-var}); - clip: auto; - -webkit-clip-path: inset(0%); - clip-path: inset(0%); - max-height: $collapse-content-max-height; - } - } - & > label:not(:first-of-type) { // Keep these down here, as it overrides some other styles. - border-top: 0; - } - & > label:first-of-type { - border-radius: var(#{$universal-border-radius-var}) var(#{$universal-border-radius-var}) 0 0; - } - & > label:last-of-type:not(:first-of-type) { - border-radius: 0 0 var(#{$universal-border-radius-var}) var(#{$universal-border-radius-var}); - } - & > label:last-of-type:first-of-type { - border-radius: var(#{$universal-border-radius-var}); - } - & > :checked:last-of-type:not(:first-of-type) + label { - border-radius: 0; - } - & > :checked:last-of-type + label + div { - border-radius: 0 0 var(#{$universal-border-radius-var}) var(#{$universal-border-radius-var}); - } - } -} diff --git a/docs/mini/_contextual_mixins.scss b/docs/mini/_contextual_mixins.scss deleted file mode 100644 index 8b004b9b5..000000000 --- a/docs/mini/_contextual_mixins.scss +++ /dev/null @@ -1,27 +0,0 @@ -// Contextual module's mixin definitions are here. For the module itself -// check `_contextual.scss`. -// Mark color variant mixin: -// $mark-alt-name: The name of the class used for the variant. -// $mark-alt-back-color: Background color for variant. -// $mark-alt-fore-color: Text color for variant. -@mixin make-mark-alt-color ($mark-alt-name, $mark-alt-back-color : $mark-back-color, - $mark-alt-fore-color : $mark-fore-color) { - mark.#{$mark-alt-name} { - @if $mark-alt-back-color != $mark-back-color { - #{$mark-back-color-var}: $mark-alt-back-color; - } - @if $mark-alt-fore-color != $mark-fore-color{ - #{$mark-fore-color-var}: $mark-alt-fore-color; - } - } -} -// Mark size variant mixin: -// $mark-alt-name: The name of the class used for the variant. -// $mark-alt-padding: The padding of the variant. -// $mark-alt-border-radius: The border radius of the variant. -@mixin make-mark-alt-size ($mark-alt-name, $mark-alt-padding, $mark-alt-border-radius) { - mark.#{$mark-alt-name} { - padding: $mark-alt-padding; - border-radius: $mark-alt-border-radius; - } -} diff --git a/docs/mini/_core.scss b/docs/mini/_core.scss deleted file mode 100644 index ccbc37661..000000000 --- a/docs/mini/_core.scss +++ /dev/null @@ -1,304 +0,0 @@ -/* - Browsers resets and base typography. -*/ - -// TODO: Add fluid type and test thoroughly -$base-root-font-size: 16px !default; // Root font sizing for all elements (`px` only) -$_apply-defaults-to-all: true !default; // [Hidden] Apply defaults to all elements? (boolean) -$__1px: (1px/$base-root-font-size) * 1rem !default; // [Calculated] Calculated rem value of `1px` -$base-font-family: '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Ubuntu, \"Helvetica Neue\", Helvetica, sans-serif' !default; // Font stack for all elements -$base-line-height: 1.5 !default; // Line height for most elements -$base-font-size: 1rem !default; // Font sizing for all elements -$_body-margin: 0 !default; // [Hidden] Margin for body -$fore-color: #111 !default; // Text & foreground color -$secondary-fore-color: #444 !default; // Secondary text & foreground color -$back-color: #f8f8f8 !default; // Background color -$secondary-back-color: #f0f0f0 !default; // Secondary background color -$blockquote-color: #f57c00 !default; //
sidebar and quotation color -$pre-color: #1565c0 !default; //
 sidebar color
-$border-color:            #aaa !default;        // Border color
-$secondary-border-color:  #ddd !default;        // Secondary border color
-$heading-line-height:     1.2 !default;         // Line height for headings
-$heading-ratio:           1.19 !default;        // Ratio for headings (strictly unitless)
-$subheading-font-size:    0.75em !default;      // Font sizing for  elements in headings
-$subheading-top-margin:   -0.25rem !default;    // Top margin of  elements in headings
-$universal-margin:        0.5rem !default;      // Universal margin for the most elements
-$universal-padding:       0.5rem !default;      // Universal padding for the most elements
-$universal-border-radius: 0.125rem !default;    // Universal border-radius for most elements
-$universal-box-shadow:    none !default;        // Universal box-shadow for most elements
-$small-font-size:         0.75em !default;      // Font sizing for  elements
-$heading-font-weight:     500 !default;         // Font weight for headings
-$bold-font-weight:        700 !default;         // Font weight for  and 
-$horizontal-rule-line-height:  1.25em !default; // 
line height -$blockquote-quotation-size: 3rem !default; // Font size for the quotation of
-$blockquote-cite-size: 0.75em !default; // Font size for the [cite] of
-$code-font-family: 'Menlo, Consolas, monospace' !default; // Font stack for code elements -$code-font-size: 0.85em; // Font size for , -$small-element-font-size: 0.75em !default; // Font size for , , -$sup-top: -0.5em !default; // top -$sub-bottom: -0.25em !default; // bottom -$a-link-color: #0277bd !default; // Color for :link -$a-visited-color: #01579b !default; // Color for :visited -// CSS variable name definitions [exercise caution if modifying these] -$fore-color-var: '--fore-color' !default; -$secondary-fore-color-var: '--secondary-fore-color' !default; -$back-color-var: '--back-color' !default; -$secondary-back-color-var: '--secondary-back-color' !default; -$blockquote-color-var: '--blockquote-color' !default; -$pre-color-var: '--pre-color' !default; -$border-color-var: '--border-color' !default; -$secondary-border-color-var: '--secondary-border-color' !default; -$heading-ratio-var: '--heading-ratio' !default; -$universal-margin-var: '--universal-margin' !default; -$universal-padding-var: '--universal-padding' !default; -$universal-border-radius-var: '--universal-border-radius' !default; -$universal-box-shadow-var: '--universal-box-shadow' !default; -$a-link-color-var: '--a-link-color' !default; -$a-visited-color-var: '--a-visited-color' !default; -/* Core module CSS variable definitions */ -:root { - #{$fore-color-var}: $fore-color; - #{$secondary-fore-color-var}: $secondary-fore-color; - #{$back-color-var}: $back-color; - #{$secondary-back-color-var}: $secondary-back-color; - #{$blockquote-color-var}: $blockquote-color; - #{$pre-color-var}: $pre-color; - #{$border-color-var}: $border-color; - #{$secondary-border-color-var}: $secondary-border-color; - #{$heading-ratio-var}: $heading-ratio; - #{$universal-margin-var}: $universal-margin; - #{$universal-padding-var}: $universal-padding; - #{$universal-border-radius-var}: $universal-border-radius; - #{$a-link-color-var} : $a-link-color; - #{$a-visited-color-var} : $a-visited-color; - @if $universal-box-shadow != none { - #{$universal-box-shadow-var}: $universal-box-shadow; - } -} -html { - font-size: $base-root-font-size; // Set root's font sizing. -} -a, b, del, em, i, ins, q, span, strong, u { - font-size: 1em; // Fix for elements inside headings not displaying properly. -} - -@if $_apply-defaults-to-all { - html, * { - font-family: #{$base-font-family}; - line-height: $base-line-height; - // Prevent adjustments of font size after orientation changes in mobile. - -webkit-text-size-adjust: 100%; - } - * { - font-size: $base-font-size; - } -} -@else { - html { - font-family: #{$base-font-family}; - line-height: $base-line-height; - // Prevent adjustments of font size after orientation changes in mobile. - -webkit-text-size-adjust: 100%; - } -} - -body { - margin: $_body-margin; - color: var(#{$fore-color-var}); - background: var(#{$back-color-var}); -} - -// Correct display for Edge & Firefox. -details { - display: block; -} - -// Correct display in all browsers. -summary { - display: list-item; -} - -// Abbreviations -abbr[title] { - border-bottom: none; // Remove bottom border in Firefox 39-. - text-decoration: underline dotted; // Opinionated style-fix for all browsers. -} - -// Show overflow in Edge. -input { - overflow: visible; -} - -// Make images responsive by default. -img { - max-width: 100%; - height: auto; -} - -h1, h2, h3, h4, h5, h6 { - line-height: $heading-line-height; - margin: calc(1.5 * var(#{$universal-margin-var})) var(#{$universal-margin-var}); - font-weight: $heading-font-weight; - small { - color: var(#{$secondary-fore-color-var}); - display: block; - @if $subheading-top-margin != 0 { - margin-top: $subheading-top-margin; - } - @if $subheading-font-size != $small-font-size { - font-size: $subheading-font-size; - } - } -} - -h1 { - font-size: calc(1rem * var(#{$heading-ratio-var}) * var(#{$heading-ratio-var}) * var(#{$heading-ratio-var}) * var(#{$heading-ratio-var})); -} -h2 { - font-size: calc(1rem * var(#{$heading-ratio-var}) * var(#{$heading-ratio-var}) * var(#{$heading-ratio-var})); -} -h3 { - font-size: calc(1rem * var(#{$heading-ratio-var}) * var(#{$heading-ratio-var})); -} -h4 { - font-size: calc(1rem * var(#{$heading-ratio-var})); -} -h5 { - font-size: 1rem; -} -h6 { - font-size: calc(1rem / var(#{$heading-ratio-var})); -} - -p { - margin: var(#{$universal-margin-var}); -} - -ol, ul { - margin: var(#{$universal-margin-var}); - padding-left: calc(2 * var(#{$universal-margin-var})); -} - -b, strong { - font-weight: $bold-font-weight; -} - -hr { - // Fixes and defaults for styling - box-sizing: content-box; - border: 0; - // Actual styling using variables - line-height: $horizontal-rule-line-height; - margin: var(#{$universal-margin-var}); - height: $__1px; - background: linear-gradient(to right, transparent, var(#{$border-color-var}) 20%, var(#{$border-color-var}) 80%, transparent); -} - -blockquote { // Doesn't have a back color by default, can be added manually. - display: block; - position: relative; - font-style: italic; - color: var(#{$secondary-fore-color-var}); - margin: var(#{$universal-margin-var}); - padding: calc(3 * var(#{$universal-padding-var})); - border: $__1px solid var(#{$secondary-border-color-var}); - border-left: 6*$__1px solid var(#{$blockquote-color-var}); - border-radius: 0 var(#{$universal-border-radius-var}) var(#{$universal-border-radius-var}) 0; - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - &:before { - position: absolute; - top: calc(0rem - var(#{$universal-padding-var})); - left: 0; - font-family: sans-serif; - font-size: $blockquote-quotation-size; - font-weight: 700; - content: "\201c"; - color: var(#{$blockquote-color-var}); - } - &[cite]:after{ - font-style: normal; - font-size: $blockquote-cite-size; - font-weight: 700; - content: "\a— " attr(cite); - white-space: pre; - } -} - -code, kbd, pre, samp { - font-family: #{$code-font-family}; // Display fix should be applied manually! - font-size: $code-font-size; -} - -code { // No border color by default and fore color is the default for text, can be altered manually. - background: var(#{$secondary-back-color-var}); - border-radius: var(#{$universal-border-radius-var}); - // This could be a bit counterintuitive and burden the codebase a bit, look into it again? - padding: calc(var(#{$universal-padding-var}) / 4) calc(var(#{$universal-padding-var}) / 2); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } -} - -kbd { // No border color by default, can be altered manually. - background: var(#{$fore-color-var}); - color: var(#{$back-color-var}); - border-radius: var(#{$universal-border-radius-var}); - // This could be a bit counterintuitive and burden the codebase a bit, look into it again? - padding: calc(var(#{$universal-padding-var}) / 4) calc(var(#{$universal-padding-var}) / 2); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } -} - -pre { // Fore color is the default, can be altered manually. - overflow: auto; // Responsiveness - background: var(#{$secondary-back-color-var}); - padding: calc(1.5 * var(#{$universal-padding-var})); - margin: var(#{$universal-margin-var}); - border: $__1px solid var(#{$secondary-border-color-var}); - border-left: 4*$__1px solid var(#{$pre-color-var}); - border-radius: 0 var(#{$universal-border-radius-var}) var(#{$universal-border-radius-var}) 0; - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } -} - -// Prevent elements from affecting the line height in all browsers. -sup, sub, code, kbd { - line-height: 0; - position: relative; - vertical-align: baseline; -} - -small, sup, sub, figcaption { - font-size: $small-element-font-size; -} - -sup { - top: $sup-top; -} -sub { - bottom: $sub-bottom; -} - -figure { - margin: var(#{$universal-margin-var}); -} -figcaption { - color: var(#{$secondary-fore-color-var}); -} - -a { - text-decoration: none; - &:link{ - color: var(#{$a-link-color-var}); - } - &:visited { - color: var(#{$a-visited-color-var}); - } - &:hover, &:focus { - text-decoration: underline; - } -} diff --git a/docs/mini/_input_control.scss b/docs/mini/_input_control.scss deleted file mode 100644 index 04635bac2..000000000 --- a/docs/mini/_input_control.scss +++ /dev/null @@ -1,317 +0,0 @@ -/* - Definitions for forms and input elements. -*/ -// Different elements are styled based on the same set of rules. -$input-group-name: 'input-group' !default; // Class name for input groups. -$_include-fluid-input-group: true !default; // [Hidden] Should fluid input groups be included? (boolean) -$input-group-fluid-name: 'fluid' !default; // Class name for fluid input groups. -$input-group-vertical-name: 'vertical' !default; // Class name for vertical input groups. -$input-group-mobile-breakpoint: 767px !default; // Breakpoint for fluid input group mobile view. -$button-class-name: 'button' !default; // Class name for elements styled as buttons. -$input-disabled-opacity: 0.75 !default; // Opacity for input elements when disabled. -$button-group-name: 'button-group' !default; // Class name for button groups. -$button-group-mobile-breakpoint: 767px !default; // Mobile breakpoint for button groups. -$form-back-color: #f0f0f0 !default; // Background color for forms. -$form-fore-color: #111 !default; // Text color for forms. -$form-border-color: #ddd !default; // Border color for forms. -$input-back-color: #f8f8f8 !default; // Background color for input elements. -$input-fore-color: #111 !default; // Text color for input elements. -$input-border-color: #ddd !default; // Border color for input elements. -$input-focus-color: #0288d1 !default; // Border color for focused input elements. -$input-invalid-color: #d32f2f !default; // Border color for invalid input elements. -$button-back-color: #e2e2e2 !default; // Background color for buttons. -$button-hover-back-color: #dcdcdc !default; // Background color for buttons (hover). -$button-fore-color: #212121 !default; // Text color for buttons. -$button-border-color: transparent !default; // Border color for buttons. -$button-hover-border-color: transparent !default; // Border color for buttons (hover). -$button-group-border-color: rgba(124,124,124, 0.54) !default; // Border color for button groups. -// CSS variable name definitions [exercise caution if modifying these] -$form-back-color-var: '--form-back-color' !default; -$form-fore-color-var: '--form-fore-color' !default; -$form-border-color-var: '--form-border-color' !default; -$input-back-color-var: '--input-back-color' !default; -$input-fore-color-var: '--input-fore-color' !default; -$input-border-color-var: '--input-border-color' !default; -$input-focus-color-var: '--input-focus-color' !default; -$input-invalid-color-var: '--input-invalid-color' !default; -$button-back-color-var: '--button-back-color' !default; -$button-hover-back-color-var: '--button-hover-back-color' !default; -$button-fore-color-var: '--button-fore-color' !default; -$button-border-color-var: '--button-border-color' !default; -$button-hover-border-color-var: '--button-hover-border-color' !default; -$button-group-border-color-var: '--button-group-border-color' !default; -// == Uncomment below code if this module is used on its own == -// -// $base-font-size: 1rem !default; // Font sizing for all elements -// $universal-margin: 0.5rem !default; // Universal margin for the most elements -// $universal-padding: 0.5rem !default; // Universal padding for the most elements -// $universal-border-radius: 0.125rem !default; // Universal border-radius for most elements -// $universal-box-shadow: none !default; // Universal box-shadow for most elements -// $universal-margin-var: '--universal-margin' !default; -// $universal-padding-var: '--universal-padding' !default; -// $universal-border-radius-var: '--universal-border-radius' !default; -// $universal-box-shadow-var: '--universal-box-shadow' !default; -// :root { -// #{$universal-margin-var}: $universal-margin; -// #{$universal-padding-var}: $universal-padding; -// #{$universal-border-radius-var}: $universal-border-radius; -// @if $universal-box-shadow != none { -// #{$universal-box-shadow-var}: $universal-box-shadow; -// } -// } -// -// ============================================================ -// Check the `_input_control_mixins.scss` file to find this module's mixins. -@import 'input_control_mixins'; -/* Input_control module CSS variable definitions */ -:root { - #{$form-back-color-var}: $form-back-color; - #{$form-fore-color-var}: $form-fore-color; - #{$form-border-color-var}: $form-border-color; - #{$input-back-color-var}: $input-back-color; - #{$input-fore-color-var}: $input-fore-color; - #{$input-border-color-var}: $input-border-color; - #{$input-focus-color-var}: $input-focus-color; - #{$input-invalid-color-var}: $input-invalid-color; - #{$button-back-color-var}: $button-back-color; - #{$button-hover-back-color-var}: $button-hover-back-color; - #{$button-fore-color-var}: $button-fore-color; - #{$button-border-color-var}: $button-border-color; - #{$button-hover-border-color-var}: $button-hover-border-color; - #{$button-group-border-color-var}: $button-group-border-color; -} -// Base form styling -form { // Text color is the default, this can be changed manually. - background: var(#{$form-back-color-var}); - color: var(#{$form-fore-color-var}); - border: $__1px solid var(#{$form-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); - margin: var(#{$universal-margin-var}); - padding: calc(2 * var(#{$universal-padding-var})) var(#{$universal-padding-var}); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } -} -// Fieldset styling -fieldset { - // Apply always to overwrite defaults for all of the below. - border: $__1px solid var(#{$form-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); - margin: calc(var(#{$universal-margin-var}) / 4); - padding: var(#{$universal-padding-var}); -} -// Legend styling. -legend { - // Edge fixes. - box-sizing: border-box; - display: table; - max-width: 100%; - white-space: normal; - // Actual styling. - font-weight: $bold-font-weight; - padding: calc(var(#{$universal-padding-var}) / 2); -} -// Label syling. - Basically just padding, but there might be more in the future. -label { - padding: calc(var(#{$universal-padding-var}) / 2) var(#{$universal-padding-var}); -} -// Input group styling. -.#{$input-group-name} { - display: inline-block; - // Fluid input groups - @if $_include-fluid-input-group { - &.#{$input-group-fluid-name} { - display: flex; - align-items: center; - justify-content: center; - & > input { - max-width: 100%; - flex-grow: 1; - flex-basis: 0px; - } - // On mobile - @media screen and (max-width: #{$input-group-mobile-breakpoint}) { - align-items: stretch; - flex-direction: column; - } - } - // Vertical input groups - &.#{$input-group-vertical-name} { - display: flex; - align-items: stretch; - flex-direction: column; - & > input { - max-width: 100%; - flex-grow: 1; - flex-basis: 0px; - } - } - } -} -// Correct the cursor style of increment and decrement buttons in Chrome. -[type="number"]::-webkit-inner-spin-button, [type="number"]::-webkit-outer-spin-button { - height: auto; -} -// Correct style in Chrome and Safari. -[type="search"] { - -webkit-appearance: textfield; - outline-offset: -2px; -} -// Correct style in Chrome and Safari. -[type="search"]::-webkit-search-cancel-button, -[type="search"]::-webkit-search-decoration { - -webkit-appearance: none; -} -// Common textual input styling. - Avoid using box-shadow with these. -input:not([type]), [type="text"], [type="email"], [type="number"], [type="search"], -[type="password"], [type="url"], [type="tel"], [type="checkbox"], [type="radio"], textarea, select { - box-sizing: border-box; - // Background, color and border should not be unassigned, as the browser defaults will apply. - background: var(#{$input-back-color-var}); - color: var(#{$input-fore-color-var}); - border: $__1px solid var(#{$input-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); - margin: calc(var(#{$universal-margin-var}) / 2); - padding: var(#{$universal-padding-var}) calc(1.5 * var(#{$universal-padding-var})); -} -// Hover, focus, disabled, readonly, invalid styling for common textual inputs. -input:not([type="button"]):not([type="submit"]):not([type="reset"]), textarea, select { - &:hover, &:focus { - border-color: var(#{$input-focus-color-var}); - box-shadow: none; - } - &:invalid, &:focus:invalid{ - border-color: var(#{$input-invalid-color-var}); - box-shadow: none; - } - &[readonly]{ - background: var(#{$secondary-back-color-var}); - } -} -// Fix for select and option elements overflowing their parent container. -select { - max-width: 100%; -} -option { - overflow: hidden; - text-overflow: ellipsis; -} -// Styling for checkboxes and radio buttons. -[type="checkbox"], [type="radio"] { - -webkit-appearance: none; - -moz-appearance: none; - appearance: none; - position: relative; - height: calc(#{$base-font-size} + var(#{$universal-padding-var}) / 2); - width: calc(#{$base-font-size} + var(#{$universal-padding-var}) / 2); - vertical-align: text-bottom; - padding: 0; // Remove padding added from previous styles. - flex-basis: calc(#{$base-font-size} + var(#{$universal-padding-var}) / 2) !important; // Override fluid input-group styling. - flex-grow: 0 !important; // Using with fluid input-groups is not recommended. - &:checked:before { - position: absolute; - } -} -[type="checkbox"] { - &:checked:before { - content: '\2713'; - font-family: sans-serif; - font-size: calc(#{$base-font-size} + var(#{$universal-padding-var}) / 2); - top: calc(0rem - var(#{$universal-padding-var})); - left: calc(var(#{$universal-padding-var}) / 4); - } -} -[type="radio"] { - border-radius: 100%; - &:checked:before { - border-radius: 100%; - content: ''; - top: calc(#{$__1px} + var(#{$universal-padding-var}) / 2); - left: calc(#{$__1px} + var(#{$universal-padding-var}) / 2); - background: var(#{$input-fore-color-var}); - width: 0.5rem; - height: 0.5rem; - } -} -// Placeholder styling (keep browser-specific definitions separated, they do not play well together). -:placeholder-shown { - color: var(#{$input-fore-color-var}); -} -::-ms-placeholder { - color: var(#{$input-fore-color-var}); - opacity: 0.54; -} -// Definitions for the button and button-like elements. -// Different elements are styled based on the same set of rules. -// Reset for Firefox focusing on button elements. -button::-moz-focus-inner, [type="button"]::-moz-focus-inner, [type="reset"]::-moz-focus-inner, [type="submit"]::-moz-focus-inner { - border-style: none; - padding: 0; -} -// Fixes for Android 4, iOS and Safari. -button, html [type="button"], [type="reset"], [type="submit"] { - -webkit-appearance: button; -} -// Other fixes. -button { - overflow: visible; // Show the overflow in IE. - text-transform: none; // Remove inheritance of text-transform in Edge, Firefox, and IE. -} -// Default styling -button, [type="button"], [type="submit"], [type="reset"], -a.#{$button-class-name}, label.#{$button-class-name}, .#{$button-class-name}, -a[role="button"], label[role="button"], [role="button"] { - display: inline-block; - background: var(#{$button-back-color-var}); - color: var(#{$button-fore-color-var}); - border: $__1px solid var(#{$button-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); - padding: var(#{$universal-padding-var}) calc(1.5 * var(#{$universal-padding-var})); - margin: var(#{$universal-margin-var}); - text-decoration: none; - cursor: pointer; - transition: background 0.3s; - &:hover, &:focus { - background: var(#{$button-hover-back-color-var}); - border-color: var(#{$button-hover-border-color-var}); - } -} -// Disabled styling for input and button elements. -input, textarea, select, button, .#{$button-class-name}, [role="button"] { - // .button[disabled] is actually higher specificity than a.button, so no need for more than that - &:disabled, &[disabled] { - cursor: not-allowed; - opacity: $input-disabled-opacity; - } -} -// Button group styling. -.#{$button-group-name} { - display: flex; - border: $__1px solid var(#{$button-group-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); - margin: var(#{$universal-margin-var}); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - & > button, [type="button"], & > [type="submit"], & > [type="reset"], - & > .#{$button-class-name}, & > [role="button"] { - margin: 0; - max-width: 100%; - flex: 1 1 auto; - text-align: center; - border: 0; - border-radius: 0; - box-shadow: none; - } - & > :not(:first-child) { - border-left: $__1px solid var(#{$button-group-border-color-var}); - } - // Responsiveness for button groups - @media screen and (max-width: #{$button-group-mobile-breakpoint}) { - flex-direction: column; - & > :not(:first-child) { - border: 0; // Reapply to remove the left border from elements. - border-top: $__1px solid var(#{$button-group-border-color-var}); - } - } -} diff --git a/docs/mini/_input_control_mixins.scss b/docs/mini/_input_control_mixins.scss deleted file mode 100644 index 4afba1cb8..000000000 --- a/docs/mini/_input_control_mixins.scss +++ /dev/null @@ -1,46 +0,0 @@ -// Input_control module's mixin definitions are here. For the module itself -// check `_input_control.scss`. -// Button color variant mixin: -// $button-alt-name: The name of the class used for the button variant. -// $button-alt-back-color: Background color for button variant. -// $button-alt-hover-back-color: Background color for button variant (hover). -// $button-alt-fore-color: Text color for button variant. -// $button-alt-border-color: Border color for button variant. -// $button-alt-hover-border-color: Border color for button variant (hover). -@mixin make-button-alt-color ($button-alt-name, $button-alt-back-color : $button-back-color, - $button-alt-hover-back-color : $button-hover-back-color, $button-alt-fore-color : $button-fore-color, - $button-alt-border-color : $button-border-color, $button-alt-hover-border-color : $button-hover-border-color) { - button, [type="button"], [type="submit"], [type="reset"], .#{$button-class-name}, [role="button"] { - &.#{$button-alt-name} { - @if $button-alt-back-color != $button-back-color { - #{$button-back-color-var}: $button-alt-back-color; - } - @if $button-alt-fore-color != $button-fore-color{ - #{$button-fore-color-var}: $button-alt-fore-color; - } - @if $button-alt-border-color != $button-border-color{ - #{$button-border-color-var}: $button-alt-border-color; - } - &:hover, &:focus { - @if $button-alt-hover-back-color != $button-hover-back-color{ - #{$button-hover-back-color-var}: $button-alt-hover-back-color; - } - @if $button-alt-hover-border-color != $button-hover-border-color{ - #{$button-hover-border-color-var}: $button-alt-hover-border-color; - } - } - } - } -} -// Button size variant mixin: -// $button-alt-name: The name of the class used for the button variant. -// $button-alt-padding: The padding of the button variant. -// $button-alt-margin The margin of the button variant. -@mixin make-button-alt-size ($button-alt-name, $button-alt-padding, $button-alt-margin) { - button, [type="button"], [type="submit"], [type="reset"], .#{$button-class-name}, [role="button"] { - &.#{$button-alt-name} { - padding: $button-alt-padding; - margin: $button-alt-margin; - } - } -} diff --git a/docs/mini/_layout.scss b/docs/mini/_layout.scss deleted file mode 100644 index df2dc8bad..000000000 --- a/docs/mini/_layout.scss +++ /dev/null @@ -1,199 +0,0 @@ -/* - Definitions for the grid system, cards and containers. -*/ -// The grid system uses the flexbox module, meaning it might be incompatible with certain browsers. -$_include-parent-layout: true !default; // [Hidden] Flag for rows defining column layouts (`true`/`false`). -$grid-column-count: 12 !default; // Number of columns in the grid (integer value only). -$grid-container-name: 'container' !default; // Class name for the grid system container. -$grid-row-name: 'row' !default; // Class name for the grid system rows. -$grid-row-parent-layout-prefix:'cols' !default; // Class name prefix for the grid's row parents. -$grid-column-prefix: 'col' !default; // Class name prefix for the grid's columns. -$grid-column-offset-suffix: 'offset' !default; // Class name suffix for the grid's offsets. -$grid-order-normal-suffix: 'normal' !default; // Class name suffix for grid columns with normal priority. -$grid-order-first-suffix: 'first' !default; // Class name suffix for grid columns with highest priority. -$grid-order-last-suffix: 'last' !default; // Class name suffix for grid columns with lowest priorty. -$grid-small-prefix: 'sm' !default; // Small screen class prefix for grid. -$grid-medium-prefix: 'md' !default; // Medium screen class prefix for grid. -$grid-large-prefix: 'lg' !default; // Large screen class prefix for grid. -$grid-medium-breakpoint: 768px !default; // Medium screen breakpoint for grid. -$grid-large-breakpoint: 1280px !default; // Large screen breakpoint for grid. -$card-name: 'card' !default; // Class name for the cards. -$card-section-name: 'section' !default; // Class name for the cards' sections. -$card-section-media-name: 'media' !default; // Class name for the cards' sections (media cotent). -$card-normal-width: 320px !default; // Width for normal cards. -$card-section-media-height: 200px !default; // Height for cards' media sections. -$card-fore-color: #111 !default; // Text color for the cards. -$card-back-color: #f8f8f8 !default; // Background color for the cards. -$card-border-color: #ddd !default; // Border color for the cards. -// CSS variable name definitions [exercise caution if modifying these] -$card-fore-color-var: '--card-fore-color' !default; -$card-back-color-var: '--card-back-color' !default; -$card-border-color-var: '--card-border-color' !default; -// == Uncomment below code if this module is used on its own == -// -// $universal-margin: 0.5rem !default; // Universal margin for the most elements -// $universal-padding: 0.5rem !default; // Universal padding for the most elements -// $universal-border-radius: 0.125rem !default; // Universal border-radius for most elements -// $universal-box-shadow: none !default; // Universal box-shadow for most elements -// $universal-margin-var: '--universal-margin' !default; -// $universal-padding-var: '--universal-padding' !default; -// $universal-border-radius-var: '--universal-border-radius' !default; -// $universal-box-shadow-var: '--universal-box-shadow' !default; -// :root { -// #{$universal-margin-var}: $universal-margin; -// #{$universal-padding-var}: $universal-padding; -// #{$universal-border-radius-var}: $universal-border-radius; -// @if $universal-box-shadow != none { -// #{$universal-box-shadow-var}: $universal-box-shadow; -// } -// } -// -// ============================================================ -// Check the `_layout_mixins.scss` file to find this module's mixins. -@import 'layout_mixins'; -// Fluid grid system container definition. -.#{$grid-container-name} { - margin: 0 auto; - padding: 0 calc(1.5 * var(#{$universal-padding-var})); -} -// Grid row definition. -.#{$grid-row-name} { - box-sizing: border-box; - display: flex; - flex: 0 1 auto; - flex-flow: row wrap; -} -// Inline mixin, used to generate class definitions for each grid step. -@mixin generate-grid-size ($size-prefix){ - @if $_include-parent-layout { - .#{$grid-column-prefix}-#{$size-prefix}, - [class^='#{$grid-column-prefix}-#{$size-prefix}-'], - [class^='#{$grid-column-prefix}-#{$size-prefix}-#{$grid-column-offset-suffix}-'], - .#{$grid-row-name}[class*='#{$grid-row-parent-layout-prefix}-#{$size-prefix}-'] > * { - box-sizing: border-box; - flex: 0 0 auto; - padding: 0 calc(var(#{$universal-padding-var}) / 2); - } - // Grid column specific definition for flexible column. - .#{$grid-column-prefix}-#{$size-prefix}, - .#{$grid-row-name}.#{$grid-row-parent-layout-prefix}-#{$size-prefix} > * { - max-width: 100%; - flex-grow: 1; - flex-basis: 0; - } - } - @else { - // Grid column generic definitions. - .#{$grid-column-prefix}-#{$size-prefix}, - [class^='#{$grid-column-prefix}-#{$size-prefix}-'], - [class^='#{$grid-column-prefix}-#{$size-prefix}-#{$grid-column-offset-suffix}-'] { - flex: 0 0 auto; - padding: 0 calc(var(#{$universal-padding-var}) / 2); - } - // Grid column specific definition for flexible column. - .#{$grid-column-prefix}-#{$size-prefix} { - max-width: 100%; - flex-grow: 1; - flex-basis: 0; - } - } - // Grid column specific definitions for predefined columns. - @for $i from 1 through $grid-column-count { - @if $_include-parent-layout { - .#{$grid-column-prefix}-#{$size-prefix}-#{$i}, - .#{$grid-row-name}.#{$grid-row-parent-layout-prefix}-#{$size-prefix}-#{$i} > * { - max-width: #{($i * 100% / $grid-column-count)}; - flex-basis: #{($i * 100% / $grid-column-count)}; - } - } - @else { - .#{$grid-column-prefix}-#{$size-prefix}-#{$i} { - max-width: #{($i * 100% / $grid-column-count)}; - flex-basis: #{($i * 100% / $grid-column-count)}; - } - } - // Offest definitions. - .#{$grid-column-prefix}-#{$size-prefix}-#{$grid-column-offset-suffix}-#{($i - 1)} { - @if ($i - 1) == 0 { - margin-left: 0; - } - @else { - margin-left: #{(($i - 1) * 100% / $grid-column-count)}; - } - } - } - // Reordering definitions. - .#{$grid-column-prefix}-#{$size-prefix}-#{$grid-order-normal-suffix} { - order: initial; - } - .#{$grid-column-prefix}-#{$size-prefix}-#{$grid-order-first-suffix} { - order: -999; - } - .#{$grid-column-prefix}-#{$size-prefix}-#{$grid-order-last-suffix} { - order: 999; - } -} -// Definitions for smaller screens. -@include generate-grid-size($grid-small-prefix); -// Definitions for medium screens. -@media screen and (min-width: #{$grid-medium-breakpoint}){ - @include generate-grid-size($grid-medium-prefix); -} -// Definitions for large screens. -@media screen and (min-width: #{$grid-large-breakpoint}){ - @include generate-grid-size($grid-large-prefix); -} -/* Card component CSS variable definitions */ -:root { - #{$card-back-color-var}: $card-back-color; - #{$card-fore-color-var}: $card-fore-color; - #{$card-border-color-var}: $card-border-color; -} -// Card styling -.#{$card-name} { - // New syntax - display: flex; - flex-direction: column; - justify-content: space-between; - align-self: center; - position: relative; - width: 100%; - // Actual styling for the cards - background: var(#{$card-back-color-var}); - color: var(#{$card-fore-color-var}); - border: $__1px solid var(#{$card-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); - margin: var(#{$universal-margin-var}); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - overflow: hidden; // Hide overflow from section borders - // Responsiveness (if the screen is larger than card, set max-width) - @media screen and (min-width: #{$card-normal-width}) { - max-width: $card-normal-width; - } - // Card sections - & > .#{$card-section-name} { - // Reapply background and foreground colors, so that mixins can be applied properly. - background: var(#{$card-back-color-var}); - color: var(#{$card-fore-color-var}); - box-sizing: border-box; - margin: 0; - border: 0; // Clean borders and radiuses for any element-based sections - border-radius: 0; // Clean borders and radiuses for any element-based sections - border-bottom: $__1px solid var(#{$card-border-color-var}); - padding: var(#{$universal-padding-var}); - width: 100%; - // Card media sections - &.#{$card-section-media-name} { - height: $card-section-media-height; - padding: 0; - -o-object-fit: cover; - object-fit: cover; - } - } - // Card sections - last - & > .#{$card-section-name}:last-child { - border-bottom: 0; // Clean the extra border for last section - } -} diff --git a/docs/mini/_layout_mixins.scss b/docs/mini/_layout_mixins.scss deleted file mode 100644 index b8eac1ba0..000000000 --- a/docs/mini/_layout_mixins.scss +++ /dev/null @@ -1,62 +0,0 @@ -// Layout (card) module's mixin definitions are here. For the module itself -// check `_layout.scss`. -// Mixin for alternate card sizes: -// $card-alt-size-name: The name of the class used for the alternate size card. -// $card-alt-size-width: The width of the alternate size card. -@mixin make-card-alt-size ($card-alt-size-name, $card-alt-size-width) { - @if type-of($card-alt-size-width) == 'number' and unit($card-alt-size-width) == '%' { - .#{$card-name}.#{$card-alt-size-name} { - max-width: $card-alt-size-width; - width: auto; - } - } - @else { - @media screen and (min-width: #{$card-alt-size-width}) { - .#{$card-name}.#{$card-alt-size-name} { - max-width: $card-alt-size-width; - } - } - } -} -// Mixin for alternate cards (card color variants): -// $card-alt-name: The name of the class used for the alternate card. -// $card-alt-back-color: The background color of the alternate card. -// $card-alt-fore-color: The text color of the alternate card. -// $card-alt-border-color: The border style of the alternate card. -@mixin make-card-alt-color ($card-alt-name, $card-alt-back-color : $card-back-color, - $card-alt-fore-color : $card-fore-color, $card-alt-border-color : $card-border-color) { - .#{$card-name}.#{$card-alt-name} { - @if $card-alt-back-color != $card-back-color { - #{$card-back-color-var}: $card-alt-back-color; - } - @if $card-alt-fore-color != $card-fore-color { - #{$card-fore-color-var}: $card-alt-fore-color; - } - @if $card-alt-border-color != $card-border-color { - #{$card-border-color-var}: $card-alt-border-color; - } - } -} -// Mixin for alternate card sections (card section color variants): -// $card-section-alt-name: The name of the class used for the alternate card section. -// $card-section-alt-back-color: The background color of the alternate card section. -// $card-section-alt-fore-color: The text color of the alternate card section. -@mixin make-card-section-alt-color ($card-section-alt-name, $card-section-alt-back-color : $card-back-color, - $card-section-alt-fore-color : $card-fore-color) { - .#{$card-name} > .#{$card-section-name}.#{$card-section-alt-name} { - @if $card-section-alt-back-color != $card-back-color { - #{$card-back-color-var}: $card-section-alt-back-color; - } - @if $card-section-alt-fore-color != $card-fore-color { - #{$card-fore-color-var}: $card-section-alt-fore-color; - } - } -} -// Mixin for alternate card sections (card section padding variants): -// $card-section-alt-name: The name of the class used for the alternate card section. -// $card-section-alt-padding: The padding of the alternate card section. -@mixin make-card-section-alt-style ($card-section-alt-name, $card-section-alt-padding) { - .#{$card-name} > .#{$card-section-name}.#{$card-section-alt-name} { - padding: $card-section-alt-padding; - } -} diff --git a/docs/mini/_navigation.scss b/docs/mini/_navigation.scss deleted file mode 100644 index 6c905bf7d..000000000 --- a/docs/mini/_navigation.scss +++ /dev/null @@ -1,315 +0,0 @@ -/* - Definitions for navigation elements. -*/ -// Different elements are styled based on the same set of rules. -$header-height: 3.1875rem !default; // Height of the header element. -$header-back-color: #f8f8f8 !default; // Background color for the header element. -$header-hover-back-color: #f0f0f0 !default; // Background color for the header element (hover). -$header-fore-color: #444 !default; // Text color for the header element. -$header-border-color: #ddd !default; // Border color for the header element. -$nav-back-color: #f8f8f8 !default; // Background color for the nav element. -$nav-hover-back-color: #f0f0f0 !default; // Background color for the nav element (hover). -$nav-fore-color: #444 !default; // Text color for the nav element. -$nav-border-color: #ddd !default; // Border color for the nav element. -$nav-link-color: #0277bd !default; // Color for link in the nav element. -$footer-fore-color: #444 !default; // Text color for the footer element. -$footer-back-color: #f8f8f8 !default; // Background color for footer nav element. -$footer-border-color: #ddd !default; // Border color for the footer element. -$footer-link-color: #0277bd !default; // Color for link in the footer element. -$drawer-back-color: #f8f8f8 !default; // Background color for the drawer component. -$drawer-border-color: #ddd !default; // Border color for the drawer component. -$drawer-hover-back-color: #f0f0f0 !default; // Background color for the drawer component's close (hover). -$drawer-close-color: #444 !default; // Color of the close element for the drawer component. -$_header-only-bottom-border: true !default; // [Hidden] Apply styling only to the bottom border of header? (boolean) -$_header-links-uppercase: true !default; // [Hidden] Should header links and buttons be uppercase? (boolean) -$header-logo-name: 'logo' !default; // Class name for the header logo element. -$header-logo-font-size: 1.75rem !default; // Font ize for the header logo element. -$nav-sublink-prefix: 'sublink' !default; // Prefix for the subcategory tabs in nav. -$nav-sublink-depth: 2 !default; // Amount of subcategory classes to add. -$_footer-only-top-border: true !default; // [Hidden] Apply styling only to the top border of footer? (boolean) -$footer-font-size: 0.875rem !default; // Font size for text in footer element. -$sticky-name: 'sticky' !default; // Class name for sticky headers and footers. -$drawer-name: 'drawer' !default; // Class name for the drawer component. -$drawer-toggle-name: 'drawer-toggle' !default; // Class name for the drawer component's toggle. -$drawer-toggle-font-size: 1.5em !default; // Font size for the drawer component's toggle. (prefer em units) -$drawer-mobile-breakpoint: 768px !default; // Mobile breakpoint for the drawer component. -$_drawer-right: true !default; // [Hidden] Should the drawer appear on the right side of the screen? -$drawer-persistent-name: 'persistent' !default; // Class name for the persisten variant of the drawer component. -$drawer-width: 320px !default; // Width of the drawer component. -$drawer-close-name: 'drawer-close' !default; // Class name of the close element for the drawer component. -$drawer-close-size: 2rem !default; // Size of the close element for the drawer component. -$drawer-icons-color: #212121 !default; // Color for the icons used in the drawer component. -// CSS variable name definitions [exercise caution if modifying these] -$header-fore-color-var: '--header-fore-color' !default; -$header-back-color-var: '--header-back-color' !default; -$header-hover-back-color-var: '--header-hover-back-color' !default; -$header-border-color-var: '--header-border-color' !default; -$nav-fore-color-var: '--nav-fore-color' !default; -$nav-back-color-var: '--nav-back-color' !default; -$nav-hover-back-color-var: '--nav-hover-back-color' !default; -$nav-border-color-var: '--nav-border-color' !default; -$nav-link-color-var: '--nav-link-color' !default; -$footer-fore-color-var: '--footer-fore-color' !default; -$footer-back-color-var: '--footer-back-color' !default; -$footer-border-color-var: '--footer-border-color' !default; -$footer-link-color-var: '--footer-link-color' !default; -$drawer-back-color-var: '--drawer-back-color' !default; -$drawer-border-color-var: '--drawer-border-color' !default; -$drawer-hover-back-color-var: '--drawer-hover-back-color' !default; -$drawer-close-color-var: '--drawer-close-color' !default; -// == Uncomment below code if this module is used on its own == -// -// $universal-margin: 0.5rem !default; // Universal margin for the most elements -// $universal-padding: 0.5rem !default; // Universal padding for the most elements -// $universal-border-radius: 0.125rem !default; // Universal border-radius for most elements -// $universal-box-shadow: none !default; // Universal box-shadow for most elements -// $universal-margin-var: '--universal-margin' !default; -// $universal-padding-var: '--universal-padding' !default; -// $universal-border-radius-var: '--universal-border-radius' !default; -// $universal-box-shadow-var: '--universal-box-shadow' !default; -// :root { -// #{$universal-margin-var}: $universal-margin; -// #{$universal-padding-var}: $universal-padding; -// #{$universal-border-radius-var}: $universal-border-radius; -// @if $universal-box-shadow != none { -// #{$universal-box-shadow-var}: $universal-box-shadow; -// } -// } -// -// ============================================================ -/* Navigation module CSS variable definitions */ -:root { - #{$header-back-color-var}: $header-back-color; - #{$header-hover-back-color-var}: $header-hover-back-color; - #{$header-fore-color-var}: $header-fore-color; - #{$header-border-color-var}: $header-border-color; - #{$nav-back-color-var}: $nav-back-color; - #{$nav-hover-back-color-var}: $nav-hover-back-color; - #{$nav-fore-color-var}: $nav-fore-color; - #{$nav-border-color-var}: $nav-border-color; - #{$nav-link-color-var}: $nav-link-color; - #{$footer-fore-color-var}: $footer-fore-color; - #{$footer-back-color-var}: $footer-back-color; - #{$footer-border-color-var}: $footer-border-color; - #{$footer-link-color-var}: $footer-link-color; - #{$drawer-back-color-var}: $drawer-back-color; - #{$drawer-hover-back-color-var}: $drawer-hover-back-color; - #{$drawer-border-color-var}: $drawer-border-color; - #{$drawer-close-color-var}: $drawer-close-color; -} -// Header styling. - No box-shadow as it causes lots of weird bugs in Chrome. No margin as it shouldn't have any. -header { - height: $header-height; - background: var(#{$header-back-color-var}); // Always apply background color to avoid shine through - color: var(#{$header-fore-color-var}); - @if $_header-only-bottom-border { - border-bottom: $__1px solid var(#{$header-border-color-var}); - } - @else { - border: $__1px solid var(#{$header-border-color-var}); - } - padding: calc(var(#{$universal-padding-var}) / 4) 0; - // Responsiveness for smaller displays, scrolls horizontally. - white-space: nowrap; - overflow-x: auto; - overflow-y: hidden; - // Fix for responsive header, using the grid system's row and column alignment. - &.#{$grid-row-name} { - box-sizing: content-box; - } - // Header logo styling. - .#{$header-logo-name} { - color: var(#{$header-fore-color-var}); - font-size: $header-logo-font-size; - padding: var(#{$universal-padding-var}) calc(2 * var(#{$universal-padding-var})); - text-decoration: none; - } - // Link styling. - button, [type="button"], .#{$button-class-name}, [role="button"] { - box-sizing: border-box; - position: relative; - top: calc(0rem - var(#{$universal-padding-var}) / 4); // Use universal-padding to offset the padding of the header. - height: calc(#{$header-height} + var(#{$universal-padding-var}) / 2); // Fill header. - background: var(#{$header-back-color-var}); // Apply color regardless to override styling from other things. - line-height: calc(#{$header-height} - var(#{$universal-padding-var}) * 1.5); - text-align: center; - color: var(#{$header-fore-color-var}); - border: 0; - border-radius: 0; - margin: 0; - @if $_header-links-uppercase { - text-transform: uppercase; - } - &:hover, &:focus { - background: var(#{$header-hover-back-color-var}); - } - } -} -// Navigation sidebar styling. -nav { - background: var(#{$nav-back-color-var}); - color: var(#{$nav-fore-color-var}); - border: $__1px solid var(#{$nav-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); - margin: var(#{$universal-margin-var}); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - * { - padding: var(#{$universal-padding-var}) calc(1.5 * var(#{$universal-padding-var})); - } - a, a:visited { - display: block; - color: var(#{$nav-link-color-var}); // Apply regardless to de-stylize visited links. - border-radius: var(#{$universal-border-radius-var}); - transition: background 0.3s; - &:hover, &:focus { - text-decoration: none; - background: var(#{$nav-hover-back-color-var}); - } - } - // Subcategories in navigation. - @for $i from 1 through $nav-sublink-depth { - .#{$nav-sublink-prefix}-#{$i} { - position: relative; - margin-left: calc(#{$i * 2} * var(#{$universal-padding-var})); - &:before { - position: absolute; - left: calc(var(#{$universal-padding-var}) - #{1 + ($i - 1)*2} * var(#{$universal-padding-var})); - top: -#{$__1px}; - content: ''; - height: 100%; - border: $__1px solid var(#{$nav-border-color-var}); - border-left: 0; - } - } - } -} -// Footer styling. -footer { - background: var(#{$footer-back-color-var}); // Always apply background color to avoid shine through - color: var(#{$footer-fore-color-var}); - @if $_footer-only-top-border { - border-top: $__1px solid var(#{$footer-border-color-var}); - } - @else { - border: $__1px solid var(#{$footer-border-color-var}); - } - // margin: $footer-margin; - padding: calc(2 * var(#{$universal-padding-var})) var(#{$universal-padding-var}); - font-size: $footer-font-size; - a, a:visited { - color: var(#{$footer-link-color-var}); - } -} -// Definitions for sticky headers and footers. -header.#{$sticky-name} { - position: -webkit-sticky; // One of the rare instances where prefixes are necessary. - position: sticky; - z-index: 1101; // Deals with certain problems when combined with cards and tables. - top: 0; -} -footer.#{$sticky-name} { - position: -webkit-sticky; // One of the rare instances where prefixes are necessary. - position: sticky; - z-index: 1101; // Deals with certain problems when combined with cards and tables. - bottom: 0; -} -// Responsive drawer component. -.#{$drawer-toggle-name} { - &:before { // No color specified, should use the color of its surroundings! - display: inline-block; - position: relative; - vertical-align: bottom; - content: '\00a0\2261\00a0'; // Spaces ensure compatibility with buttons that have text and that textless buttons will have some extra padding. - font-family: sans-serif; - font-size: $drawer-toggle-font-size; // Almost hardcoded, should be fully compatible with its surroundings. - } - @media screen and (min-width: #{$drawer-mobile-breakpoint}){ - &:not(.#{$drawer-persistent-name}) { - display: none; - } - } -} -[type="checkbox"].#{$drawer-name} { - height: 1px; - width: 1px; - margin: -1px; - overflow: hidden; - position: absolute; - clip: rect(0 0 0 0); - -webkit-clip-path: inset(100%); - clip-path: inset(100%); - + * { - display: block; - box-sizing: border-box; - position: fixed; - top: 0; - width: $drawer-width; - height: 100vh; - overflow-y: auto; - background: var(#{$drawer-back-color-var}); - border: $__1px solid var(#{$drawer-border-color-var}); - border-radius: 0; // Set to 0 to override the value from `nav`. - margin: 0; // Set to 0 to override the value from `nav`. - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - z-index: 1110; - @if $_drawer-right { - right: -$drawer-width; - transition: right 0.3s; - } - @else { - left: -$drawer-width; - transition: left 0.3s; - } - & .#{$drawer-close-name} { - position: absolute; - top: var(#{$universal-margin-var}); - right: var(#{$universal-margin-var}); - z-index: 1111; - width: $drawer-close-size; - height: $drawer-close-size; - border-radius: var(#{$universal-border-radius-var}); - padding: var(#{$universal-padding-var}); - margin: 0; // Fixes the offset from label - cursor: pointer; - transition: background 0.3s; - &:before { // Transparent background unless hovered over. Does not block text behind it. - display: block; - content: '\00D7'; - color: var(#{$drawer-close-color-var}); - position: relative; - font-family: sans-serif; - font-size: $drawer-close-size; - line-height: 1; // Setting to 1 seems to center the 'X' properly. - text-align: center; - } - &:hover, &:focus { - background: var(#{$drawer-hover-back-color-var}); - } - } - @media screen and (max-width: #{$drawer-width}) { - width: 100%; - } - } - &:checked + * { - @if $_drawer-right { - right: 0; - } - @else { - left: 0; - } - } - @media screen and (min-width: #{$drawer-mobile-breakpoint}){ - &:not(.#{$drawer-persistent-name}) + * { - position: static; - height: 100%; - z-index: 1100; - & .#{$drawer-close-name} { - display: none; - } - } - } -} diff --git a/docs/mini/_progress.scss b/docs/mini/_progress.scss deleted file mode 100644 index acbc87516..000000000 --- a/docs/mini/_progress.scss +++ /dev/null @@ -1,113 +0,0 @@ -/* - Definitions for progress elements and spinners. -*/ -$progress-back-color: #ddd !default; // Background color of . -$progress-fore-color: #555 !default; // Foreground color of . -$progress-height: 0.75rem !default; // Height of . -$progress-max-value: 1000 !default; // Arithmetic max value of - use integer values. -$progress-inline-name: 'inline' !default; // Class name for inline elements. -$progress-inline-width: 60% !default; // Width of inline elements. -$_include-spinner-donut: true !default; // [Hidden] Should spinner donuts be included? (boolean) -$spinner-donut-name: 'spinner' !default; // Class name for spinner donuts -$spinner-donut-size: 1.25rem !default; // Size of the spinner donuts -$spinner-donut-border-thickness: 0.25rem !default; // Border thickness for spinner donuts -$spinner-donut-back-color: #ddd !default; // Background color for spinner donuts -$spinner-donut-fore-color: #555 !default; // Foreground color for spinner donuts -// CSS variable name definitions [exercise caution if modifying these] -$progress-back-color-var: '--progress-back-color' !default; -$progress-fore-color-var: '--progress-fore-color' !default; -$spinner-donut-back-color-var: '--spinner-back-color' !default; -$spinner-donut-fore-color-var: '--spinner-fore-color' !default; -// == Uncomment below code if this module is used on its own == -// -// $universal-margin: 0.5rem !default; // Universal margin for the most elements -// $universal-border-radius: 0.125rem !default; // Universal border-radius for most elements -// $universal-box-shadow: none !default; // Universal box-shadow for most elements -// $universal-margin-var: '--universal-margin' !default; -// $universal-border-radius-var: '--universal-border-radius' !default; -// $universal-box-shadow-var: '--universal-box-shadow' !default; -// :root { -// #{$universal-margin-var}: $universal-margin; -// #{$universal-border-radius-var}: $universal-border-radius; -// @if $universal-box-shadow != none { -// #{$universal-box-shadow-var}: $universal-box-shadow; -// } -// } -// -// ============================================================ -// Check the `_progress_mixins.scss` file to find this module's mixins. -@import '_progress_mixins'; -/* Progess module CSS variable definitions */ -:root { - #{$progress-back-color-var}: $progress-back-color; - #{$progress-fore-color-var}: $progress-fore-color; -} -// Default styling for progress. Use mixins for alternate styles -progress { - display: block; - vertical-align: baseline; // Correct vertical alignment in some browsers. - -webkit-appearance: none; - -moz-appearance: none; - appearance: none; - height: $progress-height; - width: calc(100% - 2 * var(#{$universal-margin-var})); - margin: var(#{$universal-margin-var}); - border: 0; // Removes default border - border-radius: calc(2 * var(#{$universal-border-radius-var})); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - background: var(#{$progress-back-color-var}); - color: var(#{$progress-fore-color-var}); - // Foreground color on webkit browsers - &::-webkit-progress-value { - background: var(#{$progress-fore-color-var}); - border-top-left-radius: calc(2 * var(#{$universal-border-radius-var})); - border-bottom-left-radius: calc(2 * var(#{$universal-border-radius-var})); - } - // Background color on webkit browser - &::-webkit-progress-bar { - background: var(#{$progress-back-color}); - } - // Foreground color on Firefox - &::-moz-progress-bar { - background: var(#{$progress-fore-color-var}); - border-top-left-radius: calc(2 * var(#{$universal-border-radius-var})); - border-bottom-left-radius: calc(2 * var(#{$universal-border-radius-var})); - } - &[value="#{$progress-max-value}"] { - &::-webkit-progress-value { - border-radius: calc(2 * var(#{$universal-border-radius-var})); - } - &::-moz-progress-bar { - border-radius: calc(2 * var(#{$universal-border-radius-var})); - } - } - &.#{$progress-inline-name} { - display: inline-block; - vertical-align: middle; // Align progress bar vertically to look better with text next to it. - width: $progress-inline-width; - } -} -// Style for donut spinner -@if $_include-spinner-donut { - :root { - #{$spinner-donut-back-color-var}: $spinner-donut-back-color; - #{$spinner-donut-fore-color-var}: $spinner-donut-fore-color; - } - // Donut spinner animation - @keyframes spinner-donut-anim { - 0% { transform: rotate(0deg); } - 100% { transform: rotate(360deg);} - } - .#{$spinner-donut-name} { - display: inline-block; - margin: var(#{$universal-margin-var}); - border: $spinner-donut-border-thickness solid var(#{$spinner-donut-back-color-var}); - border-left: $spinner-donut-border-thickness solid var(#{$spinner-donut-fore-color-var}); - border-radius: 50%; - width: $spinner-donut-size; - height: $spinner-donut-size; - animation: spinner-donut-anim 1.2s linear infinite; - } -} diff --git a/docs/mini/_progress_mixins.scss b/docs/mini/_progress_mixins.scss deleted file mode 100644 index 212344389..000000000 --- a/docs/mini/_progress_mixins.scss +++ /dev/null @@ -1,32 +0,0 @@ -// Progress module's mixin definitions are here. For the module itself -// check `progress.scss`. -// Progress color variant mixin: -// $progress-alt-name: The name of the class used for the variant. -// $progress-alt-fore-color: Foregound color for variant. -// $progress-alt-back-color: Background color for variant. -@mixin make-progress-alt-color ($progress-alt-name, $progress-alt-fore-color : $progress-fore-color, - $progress-alt-back-color : $progress-back-color) { - progress.#{$progress-alt-name} { - @if $progress-alt-fore-color != $progress-fore-color{ - #{$progress-fore-color-var}: $progress-alt-fore-color; - } - @if $progress-alt-back-color != $progress-back-color { - #{$progress-back-color-var}: $progress-alt-back-color; - } - } -} -// Spinner donut color variant mixin: -// $spinner-donut-alt-name: The name of the class used for the spinner donut variant. -// $spinner-donut-alt-fore-color: Text color for spinner donut variant. -// $spinner-donut-alt-back-color: Background color for spinner donut variant. -@mixin make-spinner-donut-alt-color ($spinner-donut-alt-name, $spinner-donut-alt-fore-color : $spinner-donut-fore-color, - $spinner-donut-alt-back-color : $spinner-donut-back-color) { - .#{$spinner-donut-name}.#{$spinner-donut-alt-name} { - @if $spinner-donut-alt-fore-color != $spinner-donut-fore-color{ - #{$spinner-donut-fore-color-var}: $spinner-donut-alt-fore-color; - } - @if $spinner-donut-alt-back-color != $spinner-donut-back-color { - #{$spinner-donut-back-color-var}: $spinner-donut-alt-back-color; - } - } -} diff --git a/docs/mini/_table.scss b/docs/mini/_table.scss deleted file mode 100644 index 3f8a27d3d..000000000 --- a/docs/mini/_table.scss +++ /dev/null @@ -1,321 +0,0 @@ -/* - Definitions for the responsive table component. -*/ -// The tables use the common table elements and syntax. -/* -$table-mobile-breakpoint: 767px !default; // Breakpoint for table mobile view. -$table-mobile-card-spacing: 10px !default; // Space between cards - mobile view. -$table-mobile-card-label: 'data-label' !default;// Attribute used to replace column headers in mobile view. -$table-not-responsive-name: 'preset' !default; // Class name for table non-responsive view. -$include-horizontal-table: true !default; // Should horizontal tables be included? (`true`/`false`) -$table-horizontal-name: 'horizontal' !default;// Class name for table horizontal view. -$include-scrollable-table: true !default; // Should scrollable tables be included? (`true`/`false`) -$table-scrollable-name: 'scrollable' !default;// Class name for table scrollable view. -$table-scrollable-height: 400px !default; // Height for table scrollable view. -$include-striped-table: true !default; // [Hidden flag] Should striped tables be included? (`true`/`false`) -$table-striped-name: 'striped' !default; // Class name for striped table. -// External variables' defaults are used only if you import this module on its own, without the rest of the framework. -$back-color: white !default; // [External variable - core] Background color for everything. -$fore-color: black !default; // [External variable - core] Foreground color for everything. -*/ -$table-mobile-breakpoint: 768px !default; -$table-max-height: 400px !default; -$table-caption-font-size: 1.5rem !default; -$table-mobile-card-label: 'data-label' !default; -$table-mobile-label-font-weight: 600 !default; - -$table-border-color: #aaa !default; -$table-border-separator-color: #666 !default; - -$_include-horizontal-table: true !default; -$table-horizontal-name: 'horizontal' !default; - -// CSS variable name definitions [exercise caution if modifying these] -$table-border-color-var: '--table-border-color' !default; -$table-border-separator-color-var: '--table-border-separator-color' !default; -// == Uncomment below code if this module is used on its own == -// -// $universal-margin: 0.5rem !default; // Universal margin for the most elements -// $universal-padding: 0.5rem !default; // Universal padding for the most elements -// $universal-border-radius: 0.125rem !default; // Universal border-radius for most elements -// $universal-box-shadow: none !default; // Universal box-shadow for most elements -// $universal-margin-var: '--universal-margin' !default; -// $universal-padding-var: '--universal-padding' !default; -// $universal-border-radius-var: '--universal-border-radius' !default; -// $universal-box-shadow-var: '--universal-box-shadow' !default; -// :root { -// #{$universal-margin-var}: $universal-margin; -// #{$universal-padding-var}: $universal-padding; -// #{$universal-border-radius-var}: $universal-border-radius; -// @if $universal-box-shadow != none { -// #{$universal-box-shadow-var}: $universal-box-shadow; -// } -// } -// -// ============================================================ -/* Table module CSS variable definitions. */ -:root { - #{$table-border-color-var}: $table-border-color; - #{$table-border-separator-color-var}: $table-border-separator-color; -} -// Desktop view. -table { - border-collapse: separate; - border-spacing: 0; - margin: 0; - display: flex; - flex: 0 1 auto; - flex-flow: row wrap; - padding: var(#{$universal-padding-var}); - padding-top: 0; - @if not($_include-horizontal-table) { - overflow: auto; - max-height: $table-max-height; - } - caption { - font-size: $table-caption-font-size; - margin: calc(2 * var(#{$universal-margin-var})) 0; - max-width: 100%; - flex: 0 0 100%; - } - thead, tbody { - display: flex; - flex-flow: row wrap; - border: $__1px solid var(#{$table-border-color-var}); - @if not($_include-horizontal-table) { - max-width: 100%; - flex: 0 0 100%; - } - } - thead { - z-index: 999; // Fixes the visibility of the element. - border-radius: var(#{$universal-border-radius-var}) var(#{$universal-border-radius-var}) 0 0; - border-bottom: $__1px solid var(#{$table-border-separator-color-var}); // var This - @if not($_include-horizontal-table) { - position: sticky; - top: 0; - } - } - tbody { - border-top: 0; - margin-top: calc(0 - var(#{$universal-margin-var})); // might be useless - border-radius: 0 0 var(--universal-border-radius) var(--universal-border-radius); - } - tr { - display: flex; - padding: 0; // Apply always to overwrite default. - @if not($_include-horizontal-table) { - flex-flow: row wrap; - flex: 0 0 100%; - } - } - th, td { - padding: calc(2 * var(#{$universal-padding-var})); // Apply always to overwrite default. - @if not($_include-horizontal-table) { - flex: 1 0 0%; - overflow: hidden; - text-overflow: ellipsis; - } - } - th { - text-align: left; - background: #e6e6e6; // use vars - color: #111; // vars - } - td { - background: #fafafa; // use variables, this is a test (body) - border-top: $__1px solid var(#{$table-border-color-var}); - } - @if not($_include-horizontal-table) { - tbody tr:first-child td { - border-top: 0; - } - } -} -// Styling for horizntal tables -@if $_include-horizontal-table { - table:not(.#{$table-horizontal-name}) { - overflow: auto; - max-height: $table-max-height; - thead, tbody { - max-width: 100%; - flex: 0 0 100%; - } - tr { - flex-flow: row wrap; - flex: 0 0 100%; - } - th, td { - flex: 1 0 0%; - overflow: hidden; - text-overflow: ellipsis; - } - thead { - position: sticky; - top: 0; - } - tbody tr:first-child td { - border-top: 0; - } - } - table.#{$table-horizontal-name} { - border: 0; - thead, tbody { - border: 0; - flex-flow: row nowrap; - } - tbody { - overflow: auto; - justify-content: space-between; - flex: 1 0 0; - margin-left: calc( 4 * var(#{$universal-margin-var})); - padding-bottom: calc(var(#{$universal-padding-var}) / 4); - } - tr { - flex-direction: column; - flex: 1 0 auto; - } - th, td { - width: 100%; - border: 0; - border-bottom: $__1px solid var(#{$table-border-color-var}); - &:not(:first-child){ - border-top: 0; - } - } - th { - text-align: right; - border-left: $__1px solid var(#{$table-border-color-var}); - border-right: $__1px solid var(#{$table-border-separator-color-var}); - } - thead { - tr:first-child { - padding-left: 0; - } - } - th:first-child, td:first-child { - border-top: $__1px solid var(#{$table-border-color-var}); - } - tbody tr:last-child td { - border-right: 1px solid #aaa; - &:first-child{ - border-top-right-radius: 0.25rem; - } - &:last-child{ - border-bottom-right-radius: 0.25rem; - } - } - thead tr:first-child th { - &:first-child{ - border-top-left-radius: 0.25rem; - } - &:last-child{ - border-bottom-left-radius: 0.25rem; - } - } - } -} -// Mobile -@media screen and (max-width: #{$table-mobile-breakpoint - 1px}){ - @if $_include-horizontal-table { - table, table.#{$table-horizontal-name} { - border-collapse: collapse; - border: 0; - width: 100%; - display: table; - // Accessibility (element is not visible, but screen readers read it normally) - thead, th { - border: 0; - height: 1px; - width: 1px; - margin: -1px; - overflow: hidden; - padding: 0; - position: absolute; - clip: rect(0 0 0 0); - -webkit-clip-path: inset(100%); - clip-path: inset(100%); - } - tbody { - display: table-row-group; - } - tr { - display: block; - border: $__1px solid var(#{$table-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - background: #fafafa; // use variables, this is a test (body) - padding: var(#{$universal-padding-var}); - margin: var(#{$universal-margin-var}); - margin-bottom: calc(2 * var(#{$universal-margin-var})); - } - th, td { - width: auto; - } - td { - display: block; - border: 0; - text-align: right; - } - td:before { - content: attr(#{$table-mobile-card-label}); - float: left; - font-weight: $table-mobile-label-font-weight; - } - th:first-child, td:first-child { - border-top: 0; - } - tbody tr:last-child td { - border-right: 0; - } - } - } - @else { - table { - border-collapse: collapse; - border: 0; - width: 100%; - display: table; - // Accessibility (element is not visible, but screen readers read it normally) - thead, th { - border: 0; - height: 1px; - width: 1px; - margin: -1px; - overflow: hidden; - padding: 0; - position: absolute; - clip: rect(0 0 0 0); - -webkit-clip-path: inset(100%); - clip-path: inset(100%); - } - tbody { - display: table-row-group; - } - tr { - display: block; - border: $__1px solid var(#{$table-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); - @if $universal-box-shadow != none { - box-shadow: var(#{$universal-box-shadow-var}); - } - background: #fafafa; // use variables, this is a test (body) - padding: var(#{$universal-padding-var}); - margin: var(#{$universal-margin-var}); - margin-bottom: calc(2 * var(#{$universal-margin-var})); - } - td { - display: block; - border: 0; - text-align: right; - } - td:before { - content: attr(#{$table-mobile-card-label}); - float: left; - font-weight: $table-mobile-label-font-weight; - } - } - } -} diff --git a/docs/mini/flavor.scss b/docs/mini/flavor.scss deleted file mode 100644 index eedca2286..000000000 --- a/docs/mini/flavor.scss +++ /dev/null @@ -1,791 +0,0 @@ -// This is a flavor file. Duplicate it and edit it to create your own flavor. Read instructions carefully. -// Single-line comments, starting with '//' will not be included in your final CSS file. Multiline comments, -// structured like the flavor description below, will be included in your final CSS file. -/* - Flavor name: Default (mini-default) - Author: Angelos Chalaris (chalarangelo@gmail.com) - Maintainers: Angelos Chalaris - mini.css version: v3.0.0-alpha.2 -*/ - -$fore-color-var: '--f-col'; -$secondary-fore-color-var: '--f-col2'; -$back-color-var: '--b-col'; -$secondary-back-color-var: '--b-col2'; -$blockquote-color-var: '--blq-col'; -$pre-color-var: '--pre-col'; -$border-color-var: '--br-col'; -$secondary-border-color-var: '--br-col2'; -$heading-ratio-var: '--h-ratio'; -$universal-margin-var: '--u-m'; -$universal-padding-var: '--u-p'; -$universal-border-radius-var: '--u-br-r'; -$universal-box-shadow-var: '--u-bx-shd'; -$a-link-color-var: '--a-l-col'; -$a-visited-color-var: '--a-v-col'; - -$code-font-size: 0.8125em; - -@import 'core'; - -$grid-container-name: 'container'; -$grid-row-name: 'row'; -$grid-row-parent-layout-prefix:'cols'; -$grid-column-prefix: 'col'; -$grid-column-offset-suffix: 'o'; -$grid-order-normal-suffix: 'n'; -$grid-order-first-suffix: 'f'; -$grid-order-last-suffix: 'l'; -$grid-small-prefix: 'sm'; -$grid-medium-prefix: 'md'; -$grid-large-prefix: 'lg'; - -$card-fore-color-var: '--cd-f-col'; -$card-back-color-var: '--cd-b-col'; -$card-border-color-var: '--cd-br-col'; - -$_include-parent-layout: false; - -@import 'layout'; - -/* - Custom elements for card elements. -*/ - -$card-fluid-name: 'fluid'; // Class name for fluid cards. -$card-fluid-width: 100%; // Width for fluid cards. -@include make-card-alt-size ($card-fluid-name, $card-fluid-width); - -$card-section-double-padded-name: 'double-padded'; // Class name for card double-padded section variant. -$card-section-double-padded-padding: calc(1.5 * var(#{$universal-padding-var})); // Padding for card sectiondouble-padded section variant. -@include make-card-section-alt-style($card-section-double-padded-name, $card-section-double-padded-padding); - -.#{$card-name} { - box-shadow: 0 1.25rem 2.5rem -0.625rem rgba(0, 32, 64, 0.1); -} - -.#{$card-name} > h3.#{$card-section-name}.#{$card-section-double-padded-name} { - padding: calc(3 * var(#{$universal-padding-var})); -} - -.#{$card-name} > .#{$card-section-name}.#{$card-section-double-padded-name} > p { - margin: var(#{$universal-margin-var}) calc(var(#{$universal-margin-var}) / 2); -} - -.#{$card-name} + .#{$card-name} { - margin-top: calc(5 * var(#{$universal-margin-var})); -} - -$form-back-color-var: '--frm-b-col'; -$form-fore-color-var: '--frm-f-col'; -$form-border-color-var: '--frm-br-col'; -$input-back-color-var: '--in-b-col'; -$input-fore-color-var: '--in-f-col'; -$input-border-color-var: '--in-br-col'; -$input-focus-color-var: '--in-fc-col'; -$input-invalid-color-var: '--in-inv-col'; -$button-back-color-var: '--btn-b-col'; -$button-hover-back-color-var: '--btn-h-b-col'; -$button-fore-color-var: '--btn-f-col'; -$button-border-color-var: '--btn-br-col'; -$button-hover-border-color-var: '--btn-h-br-col'; -$button-group-border-color-var: '--btn-grp-br-col'; - - -$_include-fluid-input-group: true; - -@import 'input_control'; - -/* - Custom elements for forms and input elements. -*/ -$button-primary-name: 'primary'; // Class name for primary button color variant. -$button-primary-back-color: #1976d2; // Background color for primary button color variant. -$button-primary-hover-back-color:#1565c0; // Background color for primary button color variant (hover). -$button-primary-fore-color: #f8f8f8; // Text color for primary button color variant. -@include make-button-alt-color ($button-primary-name, $button-primary-back-color, $button-primary-hover-back-color, $button-primary-fore-color); - - -$header-fore-color-var: '--hd-f-col'; -$header-back-color-var: '--hd-b-col'; -$header-hover-back-color-var: '--hd-hv-b-col'; -$header-border-color-var: '--hd-br-col'; -$nav-fore-color-var: '--nv-f-col'; -$nav-back-color-var: '--nv-b-col'; -$nav-hover-back-color-var: '--nv-hv-b-col'; -$nav-border-color-var: '--nv-br-col'; -$nav-link-color-var: '--nv-ln-col'; -$footer-fore-color-var: '--ft-f-col'; -$footer-back-color-var: '--ft-b-col'; -$footer-border-color-var: '--ft-br-col'; -$footer-link-color-var: '--ft-ln-col'; -$drawer-back-color-var: '--dr-b-col'; -$drawer-border-color-var: '--dr-br-col'; -$drawer-hover-back-color-var: '--dr-hv-b-col'; -$drawer-close-color-var: '--dr-cl-col'; - - -$nav-sublink-depth: 1; - -$_drawer-right: false; - -@import 'navigation'; - -$mark-back-color: #424242; -$mark-font-size: 0.5em; - -$toast-back-color: #212121; - -$mark-back-color-var: '--mrk-b-col'; -$mark-fore-color-var: '--mrk-f-col'; -$toast-back-color-var: '--tst-b-col'; -$toast-fore-color-var: '--tst-f-col'; -$tooltip-back-color-var: '--tltp-b-col'; -$tooltip-fore-color-var: '--tltp-f-col'; -$modal-overlay-color-var: '--mdl-ov-col'; -$modal-close-color-var: '--mdl-cl-col'; -$modal-close-hover-back-color-var: '--mdl-cl-h-col'; -$collapse-label-back-color-var: '--clps-lbl-b-col'; -$collapse-label-fore-color-var: '--clps-lbl-f-col'; -$collapse-label-hover-back-color-var: '--clps-lbl-h-b-col'; -$collapse-selected-label-back-color-var: '--clps-sel-lbl-b-col'; -$collapse-border-color-var: '--clps-br-col'; -$collapse-content-back-color-var: '--clps-cnt-b-col'; -$collapse-selected-label-border-color-var: '--clps-sel-lbl-br-col'; - -$_include-modal: false; -$_include-tooltip: false; -$_include-collapse: false; - -@import 'contextual'; - -div,main,nav{ - -webkit-overflow-scrolling: touch; -} -.#{$toast-name} { - bottom: calc(var(#{$universal-margin-var}) / 2); - opacity: 1; - transition: opacity 0.3s ease-in-out; -} - -mark { - position: relative; - top: -0.25rem; - left: 0.25rem; -} - -/* - Custom elements for contextual background elements, toasts and tooltips. -*/ -$mark-secondary-name: 'secondary'; // Class name for secondary color variant. -$mark-secondary-back-color: #d32f2f; // Background color for secondary color variant. -@include make-mark-alt-color ($mark-secondary-name, $mark-secondary-back-color); - -$mark-tertiary-name: 'tertiary'; // Class name for tertiary color variant. -$mark-tertiary-back-color: #308732; // Background color for tertiary color variant. -@include make-mark-alt-color ($mark-tertiary-name, $mark-tertiary-back-color); - -$mark-tag-name: 'tag'; // Class name, padding and border radius for tag size variant. -$mark-tag-padding: calc(var(#{$universal-padding-var})/2) var(#{$universal-padding-var}); -$mark-tag-border-radius: 1em; -@include make-mark-alt-size ($mark-tag-name, $mark-tag-padding, $mark-tag-border-radius); - -// Website-specific styles -code, pre, kbd, code *, pre *, kbd *, code[class*="language-"], pre[class*="language-"] { - font-family: Menlo, Consolas, monospace !important; -} -pre { - border: 0.0625rem solid var(#{$secondary-border-color-var}); - border-radius: var(#{$universal-border-radius-var}); -} - -.search { - font-size: 0.875rem; -} - -header h1.logo { - margin-top: -0.8rem; - text-align:center; - position: relative; - top: 0; - transition: top 0.3s; - color: #111; -} - -h1 a, h1 a:link, h1 a:visited { - text-decoration:none; - color: #111; - &:hover, &:focus { - text-decoration:none; - color: #111; - } -} - -header #title { - position:relative; - top: -1rem; - @media screen and (max-width: 768px) { display: none; } -} - -header { - background: linear-gradient( - 135deg, - rgba(255, 174, 39, 1) 0%, - rgba(222, 73, 109, 1) 100% - ); -} - -header h1 small { - display:block; - font-size: 0.875rem; - color: #888; - margin-top: 0.75rem; -} - -label#menu-toggle { - position: absolute; - left: 0rem; - top: 0rem; - width: 3.4375rem; -} - -main { - padding: 0; -} - -:root { - #{$collapse-label-back-color-var}: $collapse-label-back-color; - #{$collapse-label-fore-color-var}: $collapse-label-fore-color; - #{$collapse-label-hover-back-color-var}: $collapse-label-hover-back-color; - #{$collapse-selected-label-back-color-var}: $collapse-selected-label-back-color; - #{$collapse-border-color-var}: $collapse-border-color; - #{$collapse-content-back-color-var} : $collapse-content-back-color; - #{$collapse-selected-label-border-color-var}: $collapse-selected-label-border-color; -} -label.#{$collapse-name} { - width: 100%; - display: inline-block; - cursor: pointer; - box-sizing: border-box; - transition: background 0.3s; - color: var(#{$collapse-label-fore-color-var}); - background: var(#{$collapse-label-back-color-var}); - border: $__1px solid var(#{$collapse-border-color-var}); - padding: calc(1.5 * var(#{$universal-padding-var})); - border-radius: var(#{$universal-border-radius-var}); - &:hover, &:focus { - background: var(#{$collapse-label-hover-back-color-var}); - } - + pre { - box-sizing: border-box; - height: 0; - max-height: 1px; - overflow: auto; - margin: 0; - border: 0; - padding: 0; - transition: max-height 0.3s; - } - &.toggled { - background: var(#{$collapse-selected-label-back-color-var}); - border-bottom-color: var(#{$collapse-selected-label-border-color-var}); - border-bottom-left-radius: 0; - border-bottom-right-radius: 0; - + pre { - border-top-left-radius: 0; - border-top-right-radius: 0; - position: relative; - width: 100%; - height: auto; - border: $__1px solid var(#{$collapse-border-color-var}); - border-top: 0; - padding: calc(2 * var(#{$universal-padding-var})); - max-height: $collapse-content-max-height; - } - } -} - -button.primary.clipboard-copy { - width: 100%; - margin-left: 0; - > img { - vertical-align: bottom; - } -} - -code[class*="language-"], -pre[class*="language-"] { - color: #222; - text-align: left; - white-space: pre; - word-spacing: normal; - word-break: normal; - word-wrap: normal; - line-height: 1.8; - - -moz-tab-size: 2; - -o-tab-size: 2; - tab-size: 2; - - -webkit-hypens: none; - -moz-hyphens: none; - -ms-hyphens: none; - hyphens: none; -} - -pre[class*="language-"] { - padding: calc(2 * var(#{$universal-padding-var})); - overflow: auto; - margin: var(#{$universal-margin-var}) 0; -} - - -pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, -code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { - background: #b3d4fc; -} - -pre[class*="language-"]::selection, pre[class*="language-"] ::selection, -code[class*="language-"]::selection, code[class*="language-"] ::selection { - background: #b3d4fc; -} - -:not(pre) > code[class*="language-"] { - padding: .1em; - border-radius: .3em; - white-space: normal; -} - -.token.comment, -.token.prolog, -.token.doctype, -.token.cdata { - color: #7a8490; -} - -.token.punctuation { - color: #666; -} - -.namespace { - opacity: .7; -} - -.token.property, -.token.tag, -.token.boolean, -.token.constant, -.token.symbol, -.token.deleted, -.token.function { - color: #005cc5; -} - - -.token.number, -.token.class-name { - color: #832ed2; -} - -.token.selector, -.token.attr-name, -.token.string, -.token.char, -.token.builtin, -.token.inserted { - color: #067e36; -} - -.token.operator, -.token.entity, -.token.url, -.language-css .token.string, -.style .token.string, -.token.atrule, -.token.attr-value, -.token.keyword { - color: #d73a49; -} - -.token.regex { - color: #097cab; -} -.token.important, -.token.variable { - color: #e90; -} - -.token.important, -.token.bold { - font-weight: bold; -} -.token.italic { - font-style: italic; -} - -.token.entity { - cursor: help; -} - -button.scroll-to-top { - border-radius: 100%; - font-size: 1.5rem; - line-height: 1; - box-sizing: border-box; - width: 2.75rem; - height: 2.75rem; - position: fixed; - bottom: 1rem; - right: 2rem; - background: var(#{$back-color-var}); - box-shadow: 0 .25rem .25rem 0 rgba(0,0,0,0.125),0 .125rem .125rem -.125rem rgba(0,0,0,0.25); - &:hover, &:focus { - background: var(#{$secondary-back-color-var}); - } -} - -.#{$card-name}#disclaimer { - position: fixed; - bottom: 0; - z-index: 1100; - max-width: 100vw; - width: 100vw; - left: 0; - text-align: center; - font-size: 1.5rem; - margin: 0; - @media screen and (min-width: 768px){ - width: 60vw; - left: 20vw; - bottom: 1rem; - } - @media screen and (min-width: 1280px){ - width: 40vw; - left: 30vw; - bottom: 1.5rem; - } -} - -button#disclaimer-close{ - position: absolute; - top: -0.5rem; - right: -0.5rem; - font-size: 0.85rem; - background: 0; -} - -// New styles for landing page - -#splash { - height: auto; - padding-bottom: 1.5rem; - background: linear-gradient( - 135deg, - rgba(255, 174, 39, 1) 0%, - rgba(222, 73, 109, 1) 100% - ); - #logo { - margin-top: 0; - margin-left: -0.5rem; - padding-top: 2rem; - text-align: center; - font-size: 2.25rem; - line-height: 2; - img { - vertical-align: top; - height: 4.5rem; - } - } - #tagline { - text-align: center; - padding: 0.5rem 25%; - } - #doc-link { - text-align: center; - margin-left: -0.5rem; - > a { - background: transparent; - border: 0.0625rem solid rgba(17, 17, 17, 0.95); - transition: all 0.3s; - &:hover, - &:focus { - background: rgba(17, 17, 17, 0.95); - color: #e86957; - } - } - } - @media screen and (max-width: 767px) { - #logo { - font-size: 1.75rem; - img { - height: 3.5rem; - } - } - #tagline { - padding: 0.25rem 17.5%; - font-size: 0.875rem; - } - #doc-link { - font-size: 0.875rem; - } - } - @media screen and (max-width: 383px) { - #logo { - font-size: 1.5rem; - img { - height: 3rem; - } - } - #tagline { - padding: 0.125rem 5%; - } - } - @media screen and (max-width: 479px) { - #tagline #tagline-lg { - display: none; - } - } -} - -@media screen and (min-width: 768px) { - .col-md-offset-1 { - margin-left: 8.33333%; - } -} - -@media screen and (min-width: 1280px) { - .col-lg-offset-2 { - margin-left: 16.66667%; - } -} - -h2.index-section { - border-left: 0.3125rem solid #de4a6d; - padding-left: 0.625rem; - margin-top: 2rem; -} - -#license-icon { - text-align: center; - @media screen and (min-width: 768px) { - position: relative; - top: calc(50% - 40px); - } - > svg { - border: 0.03125rem solid #444; - border-radius: 100%; - padding: 0.5rem; - fill: #444; - } -} - -#license { - vertical-align: middle; -} - -.no-padding { - padding: 0; -} - -#in-numbers { - background: #111; //#3f88c5; //#e15554; - padding-top: 0.75rem; - padding-bottom: 0.75rem; - color: #fff; - svg { - fill: #fff; - @media screen and (min-width: 768px) { - position: relative; - top: 20px; - left: -34px; - width: 32px; - height: 32px; - } - } - p { - overflow-wrap: break-word; - @media screen and (min-width: 768px) { - position: relative; - top: -24px; - left: 22px; - font-size: 0.75rem; - } - margin-top: 0; - font-size: 0.625rem; - margin-bottom: 0; - } -} - -#snippet-count, -#contrib-count, -#commit-count, -#star-count { - font-size: 1rem; - @media screen and (min-width: 768px) { - font-size: 1.25rem; - } -} - -ul#links { - list-style: none; - padding-left: 0; - li + li { - padding-top: 0.625rem; - } -} - -.pick:not(.selected) { - display: none; -} - -.card.pick { - transition: all 0.6s; - left: 0; -} - -.card.pick + .card.pick { - margin-top: 0.5rem; -} - -.pick.selected { - overflow: visible; - button.next { - position: absolute; - top: 50%; - right: -1rem; - > svg { - margin-right: -0.0625rem; - } - } -} - -#pick-slider { - position: relative; -} - -button.previous { - left: -1%; - > svg { - margin-left: -0.125rem; - } -} -button.next { - right: -1%; - > svg { - margin-left: 0.0625rem; - } -} - -button.previous, -button.next { - position: absolute; - top: 50%; - border-radius: 100%; - background: #f8f8f8; - border: 0.03125rem solid #ddd; - width: 1.5rem; - height: 1.5rem; - padding: 0; - margin: 0; - transition: all 0.3s; - z-index: 2000; - > svg { - fill: #888; - transition: all 0.3s; - } - &:hover, - &:focus { - border-color: #aaa; - > svg { - fill: #444; - } - } -} - -.card.contributor { - height: calc(100% - 1rem); - justify-content: left; - > .section.media { - height: auto; - } - > .section.button { - font-size: 0.75rem; - font-weight: 700; - text-align: center; - transition: color 0.3s; - &:hover, - &:focus { - color: var(--a-l-col); - background: #f8f8f8; - } - } -} - -.card.fluid.contribution-guideline { - overflow: visible; - margin-top: 3rem; - padding-bottom: 0.25rem; - h3 { - padding-top: 0.5rem; - text-align: center; - } -} - -.contribution-guideline + .contribution-guideline { - &:before, - &:after { - content: ""; - position: relative; - top: -2.75rem; - width: 0.375rem; - height: 0.375rem; - background: #ddd; - border: 0.03125rem solid #d0d0d0; - border-radius: 100%; - left: calc(50% - 0.1875rem); - box-shadow: inset -0.03125rem -0.03125rem 0.03125rem rgba(0, 0, 0, 0.05); - } - &:after { - position: absolute; - top: - 1.875rem; - } -} - -.contribution-number { - position: absolute; - top: -1.125rem; - left: calc(50% - 1.125rem); - font-size: 1.5rem; - background: linear-gradient( - 135deg, - rgba(255, 174, 39, 1) 0%, - rgba(222, 73, 109, 1) 100% - ); - border: 0.03125 solid #ddd; - width: 2.25rem; - text-align: center; - height: 2.25rem; - border-radius: 100%; - font-weight: 700; - color: #fff; -} - -body { - overflow-x: hidden; -} - -label.button.drawer-toggle { - background: transparent; - color: #111; - &:hover, &:focus { - background: transparent; - } -} - -nav .input-group.vertical { - position: sticky; - top: 0; - z-index: 10; - background: #f8f8f8; - border-bottom: 0.0625rem solid var(--nv-br-col); -} diff --git a/docs/node.html b/docs/node.html index d17685100..6075611c5 100644 --- a/docs/node.html +++ b/docs/node.html @@ -1,6 +1,6 @@ -Node - 30 seconds of codeNode - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Node

atob

Decodes a string of data which has been encoded using base-64 encoding.

Create a Buffer for the given string with base-64 encoding and use Buffer.toString('binary') to return the decoded string.

const atob = str => new Buffer(str, 'base64').toString('binary');
-
atob('Zm9vYmFy'); // 'foobar'
-

btoa

Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.

Create a Buffer for the given string with binary encoding and use Buffer.toString('base64') to return the encoded string.

const btoa = str => new Buffer(str, 'binary').toString('base64');
-
btoa('foobar'); // 'Zm9vYmFy'
-

colorize

Add special characters to text to print in color in the console (combined with console.log()).

Use template literals and special characters to add the appropriate color code to the string output. For background colors, add a special character that resets the background color at the end of the string.

const colorize = (...args) => ({
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Node

intermediate

atob

Decodes a string of data which has been encoded using base-64 encoding.

Create a Buffer for the given string with base-64 encoding and use Buffer.toString('binary') to return the decoded string.

const atob = str => new Buffer(str, 'base64').toString('binary');
+
atob('Zm9vYmFy'); // 'foobar'
+
intermediate

btoa

Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.

Create a Buffer for the given string with binary encoding and use Buffer.toString('base64') to return the encoded string.

const btoa = str => new Buffer(str, 'binary').toString('base64');
+
btoa('foobar'); // 'Zm9vYmFy'
+
intermediate

colorize

Add special characters to text to print in color in the console (combined with console.log()).

Use template literals and special characters to add the appropriate color code to the string output. For background colors, add a special character that resets the background color at the end of the string.

const colorize = (...args) => ({
   black: `\x1b[30m${args.join(' ')}`,
   red: `\x1b[31m${args.join(' ')}`,
   green: `\x1b[32m${args.join(' ')}`,
@@ -101,16 +95,16 @@
   bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`,
   bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m`
 });
-
console.log(colorize('foo').red); // 'foo' (red letters)
+
console.log(colorize('foo').red); // 'foo' (red letters)
 console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background)
 console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite); // 'foo bar' (first word in yellow letters, second word in green letters, white background for both)
-

hasFlags

Check if the current process's arguments contain the specified flags.

Use Array.every() and Array.includes() to check if process.argv contains all the specified flags. Use a regular expression to test if the specified flags are prefixed with - or -- and prefix them accordingly.

const hasFlags = (...flags) =>
+
intermediate

hasFlags

Check if the current process's arguments contain the specified flags.

Use Array.every() and Array.includes() to check if process.argv contains all the specified flags. Use a regular expression to test if the specified flags are prefixed with - or -- and prefix them accordingly.

const hasFlags = (...flags) =>
   flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
-
// node myScript.js -s --test --cool=true
+
// node myScript.js -s --test --cool=true
 hasFlags('-s'); // true
 hasFlags('--test', 'cool=true', '-s'); // true
 hasFlags('special'); // false
-

hashNode

Creates a hash for a value using the SHA-256 algorithm. Returns a promise.

Use crypto API to create a hash for the given value.

const crypto = require('crypto');
+
intermediate

hashNode

Creates a hash for a value using the SHA-256 algorithm. Returns a promise.

Use crypto API to create a hash for the given value.

const crypto = require('crypto');
 const hashNode = val =>
   new Promise(resolve =>
     setTimeout(
@@ -124,20 +118,20 @@ console.log<
       0
     )
   );
-
hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
-

isTravisCI

Checks if the current environment is Travis CI.

Checks if the current environment has the TRAVIS and CI environment variables (reference).

const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
-
isTravisCI(); // true (if code is running on Travis CI)
-

JSONToFile

Writes a JSON object to a file.

Use fs.writeFile(), template literals and JSON.stringify() to write a json object to a .json file.

const fs = require('fs');
+
hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
+
intermediate

isTravisCI

Checks if the current environment is Travis CI.

Checks if the current environment has the TRAVIS and CI environment variables (reference).

const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
+
isTravisCI(); // true (if code is running on Travis CI)
+
intermediate

JSONToFile

Writes a JSON object to a file.

Use fs.writeFile(), template literals and JSON.stringify() to write a json object to a .json file.

const fs = require('fs');
 const JSONToFile = (obj, filename) =>
   fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
-
JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
-

readFileLines

Returns an array of lines from the specified file.

Use readFileSync function in fs node package to create a Buffer from a file. convert buffer to string using toString(encoding) function. creating an array from contents of file by spliting file content line by line (each \n).

const fs = require('fs');
+
JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
+
intermediate

readFileLines

Returns an array of lines from the specified file.

Use readFileSync function in fs node package to create a Buffer from a file. convert buffer to string using toString(encoding) function. creating an array from contents of file by spliting file content line by line (each \n).

const fs = require('fs');
 const readFileLines = filename =>
   fs
     .readFileSync(filename)
     .toString('UTF8')
     .split('\n');
-
/*
+
/*
 contents of test.txt :
   line1
   line2
@@ -146,12 +140,12 @@ contents of test.txt :
 */
 let arr = readFileLines('test.txt');
 console.log(arr); // ['line1', 'line2', 'line3']
-

untildify

Converts a tilde path to an absolute path.

Use String.replace() with a regular expression and OS.homedir() to replace the ~ in the start of the path with the home directory.

const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
-
untildify('~/node'); // '/Users/aUser/node'
-

UUIDGeneratorNode

Generates a UUID in Node.JS.

Use crypto API to generate a UUID, compliant with RFC4122 version 4.

const crypto = require('crypto');
+
intermediate

untildify

Converts a tilde path to an absolute path.

Use String.replace() with a regular expression and OS.homedir() to replace the ~ in the start of the path with the home directory.

const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
+
untildify('~/node'); // '/Users/aUser/node'
+
intermediate

UUIDGeneratorNode

Generates a UUID in Node.JS.

Use crypto API to generate a UUID, compliant with RFC4122 version 4.

const crypto = require('crypto');
 const UUIDGeneratorNode = () =>
   ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
     (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
   );
-
UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'
-
\ No newline at end of file +
UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'
+
\ No newline at end of file diff --git a/docs/object.html b/docs/object.html index 3616d2754..d5fa46d48 100644 --- a/docs/object.html +++ b/docs/object.html @@ -1,6 +1,6 @@ -Object - 30 seconds of codeObject - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Object

bindAll

Binds methods of an object to the object itself, overwriting the existing method.

Use Array.forEach() to return a function that uses Function.apply() to apply the given context (obj) to fn for each function specified.

const bindAll = (obj, ...fns) =>
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Object

intermediate

bindAll

Binds methods of an object to the object itself, overwriting the existing method.

Use Array.forEach() to return a function that uses Function.apply() to apply the given context (obj) to fn for each function specified.

const bindAll = (obj, ...fns) =>
   fns.forEach(
     fn => (
       (f = obj[fn]),
@@ -88,7 +82,7 @@
       })
     )
   );
-
var view = {
+
var view = {
   label: 'docs',
   click: function() {
     console.log('clicked ' + this.label);
@@ -96,36 +90,36 @@
 };
 bindAll(view, 'click');
 jQuery(element).on('click', view.click); // Logs 'clicked docs' when clicked.
-

deepClone

Creates a deep clone of an object.

Use recursion. Use Object.assign() and an empty object ({}) to create a shallow clone of the original. Use Object.keys() and Array.forEach() to determine which key-value pairs need to be deep cloned.

const deepClone = obj => {
+
intermediate

deepClone

Creates a deep clone of an object.

Use recursion. Use Object.assign() and an empty object ({}) to create a shallow clone of the original. Use Object.keys() and Array.forEach() to determine which key-value pairs need to be deep cloned.

const deepClone = obj => {
   let clone = Object.assign({}, obj);
   Object.keys(clone).forEach(
     key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
   );
   return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;
 };
-
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
+
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
 const b = deepClone(a); // a !== b, a.obj !== b.obj
-

deepFreeze

Deep freezes an object.

Calls Object.freeze(obj) recursively on all unfrozen properties of passed object that are instanceof object.

const deepFreeze = obj =>
+
intermediate

deepFreeze

Deep freezes an object.

Calls Object.freeze(obj) recursively on all unfrozen properties of passed object that are instanceof object.

const deepFreeze = obj =>
   Object.keys(obj).forEach(
     prop =>
       !obj[prop] instanceof Object || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
   ) || Object.freeze(obj);
-
'use strict';
+
'use strict';
 
 const o = deepFreeze([1, [2, 3]]);
 
 o[0] = 3; // not allowed
 o[1][0] = 4; // not allowed as well
-

defaults

Assigns default values for all properties in an object that are undefined.

Use Object.assign() to create a new empty object and copy the original one to maintain key order, use Array.reverse() and the spread operator ... to combine the default values from left to right, finally use obj again to overwrite properties that originally had a value.

const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
-
defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }
-

dig

Returns the target value in a nested JSON object, based on the given key.

Use the in operator to check if target exists in obj. If found, return the value of obj[target], otherwise use Object.values(obj) and Array.reduce() to recursively call dig on each nested object until the first matching key/value pair is found.

const dig = (obj, target) =>
+
intermediate

defaults

Assigns default values for all properties in an object that are undefined.

Use Object.assign() to create a new empty object and copy the original one to maintain key order, use Array.reverse() and the spread operator ... to combine the default values from left to right, finally use obj again to overwrite properties that originally had a value.

const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
+
defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }
+
intermediate

dig

Returns the target value in a nested JSON object, based on the given key.

Use the in operator to check if target exists in obj. If found, return the value of obj[target], otherwise use Object.values(obj) and Array.reduce() to recursively call dig on each nested object until the first matching key/value pair is found.

const dig = (obj, target) =>
   target in obj
     ? obj[target]
     : Object.values(obj).reduce((acc, val) => {
         if (acc !== undefined) return acc;
         if (typeof val === 'object') return dig(val, target);
       }, undefined);
-
const data = {
+
const data = {
   level1: {
     level2: {
       level3: 'some data'
@@ -134,7 +128,7 @@ o[1
 dig(data, 'level3'); // 'some data'
 dig(data, 'level4'); // undefined
-

equalsadvanced

Performs a deep comparison between two values to determine if they are equivalent.

Check if the two values are identical, if they are both Date objects with the same time, using Date.getTime() or if they are both non-object values with an equivalent value (strict comparison). Check if only one value is null or undefined or if their prototypes differ. If none of the above conditions are met, use Object.keys() to check if both values have the same number of keys, then use Array.every() to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.

const equals = (a, b) => {
+
advanced

equals

Performs a deep comparison between two values to determine if they are equivalent.

Check if the two values are identical, if they are both Date objects with the same time, using Date.getTime() or if they are both non-object values with an equivalent value (strict comparison). Check if only one value is null or undefined or if their prototypes differ. If none of the above conditions are met, use Object.keys() to check if both values have the same number of keys, then use Array.every() to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.

const equals = (a, b) => {
   if (a === b) return true;
   if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
   if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
@@ -144,9 +138,9 @@ o[1if (keys.length !== Object.keys(b).length) return false;
   return keys.every(k => equals(a[k], b[k]));
 };
-
equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
-

findKey

Returns the first key that satisfies the provided testing function. Otherwise undefined is returned.

Use Object.keys(obj) to get all the properties of the object, Array.find() to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.

const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
-
findKey(
+
equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
+
intermediate

findKey

Returns the first key that satisfies the provided testing function. Otherwise undefined is returned.

Use Object.keys(obj) to get all the properties of the object, Array.find() to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.

const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
+
findKey(
   {
     barney: { age: 36, active: true },
     fred: { age: 40, active: false },
@@ -154,11 +148,11 @@ o[1
   o => o['active']
 ); // 'barney'
-

findLastKey

Returns the last key that satisfies the provided testing function. Otherwise undefined is returned.

Use Object.keys(obj) to get all the properties of the object, Array.reverse() to reverse their order and Array.find() to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.

const findLastKey = (obj, fn) =>
+
intermediate

findLastKey

Returns the last key that satisfies the provided testing function. Otherwise undefined is returned.

Use Object.keys(obj) to get all the properties of the object, Array.reverse() to reverse their order and Array.find() to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.

const findLastKey = (obj, fn) =>
   Object.keys(obj)
     .reverse()
     .find(key => fn(obj[key], key, obj));
-
findLastKey(
+
findLastKey(
   {
     barney: { age: 36, active: true },
     fred: { age: 40, active: false },
@@ -166,34 +160,34 @@ o[1
   o => o['active']
 ); // 'pebbles'
-

flattenObject

Flatten an object with the paths for keys.

Use recursion. Use Object.keys(obj) combined with Array.reduce() to convert every leaf node to a flattened path node. If the value of a key is an object, the function calls itself with the appropriate prefix to create the path using Object.assign(). Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object. You should always omit the second argument, prefix, unless you want every key to have a prefix.

const flattenObject = (obj, prefix = '') =>
+
intermediate

flattenObject

Flatten an object with the paths for keys.

Use recursion. Use Object.keys(obj) combined with Array.reduce() to convert every leaf node to a flattened path node. If the value of a key is an object, the function calls itself with the appropriate prefix to create the path using Object.assign(). Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object. You should always omit the second argument, prefix, unless you want every key to have a prefix.

const flattenObject = (obj, prefix = '') =>
   Object.keys(obj).reduce((acc, k) => {
     const pre = prefix.length ? prefix + '.' : '';
     if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));
     else acc[pre + k] = obj[k];
     return acc;
   }, {});
-
flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }
-

forOwn

Iterates over all own properties of an object, running a callback for each one.

Use Object.keys(obj) to get all the properties of the object, Array.forEach() to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.

const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
-
forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1
-

forOwnRight

Iterates over all own properties of an object in reverse, running a callback for each one.

Use Object.keys(obj) to get all the properties of the object, Array.reverse() to reverse their order and Array.forEach() to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.

const forOwnRight = (obj, fn) =>
+
flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }
+
intermediate

forOwn

Iterates over all own properties of an object, running a callback for each one.

Use Object.keys(obj) to get all the properties of the object, Array.forEach() to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.

const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
+
forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1
+
intermediate

forOwnRight

Iterates over all own properties of an object in reverse, running a callback for each one.

Use Object.keys(obj) to get all the properties of the object, Array.reverse() to reverse their order and Array.forEach() to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.

const forOwnRight = (obj, fn) =>
   Object.keys(obj)
     .reverse()
     .forEach(key => fn(obj[key], key, obj));
-
forOwnRight({ foo: 'bar', a: 1 }, v => console.log(v)); // 1, 'bar'
-

functions

Returns an array of function property names from own (and optionally inherited) enumerable properties of an object.

Use Object.keys(obj) to iterate over the object's own properties. If inherited is true, use Object.get.PrototypeOf(obj) to also get the object's inherited properties. Use Array.filter() to keep only those properties that are functions. Omit the second argument, inherited, to not include inherited properties by default.

const functions = (obj, inherited = false) =>
+
forOwnRight({ foo: 'bar', a: 1 }, v => console.log(v)); // 1, 'bar'
+
intermediate

functions

Returns an array of function property names from own (and optionally inherited) enumerable properties of an object.

Use Object.keys(obj) to iterate over the object's own properties. If inherited is true, use Object.get.PrototypeOf(obj) to also get the object's inherited properties. Use Array.filter() to keep only those properties that are functions. Omit the second argument, inherited, to not include inherited properties by default.

const functions = (obj, inherited = false) =>
   (inherited
     ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))]
     : Object.keys(obj)
   ).filter(key => typeof obj[key] === 'function');
-
function Foo() {
+
function Foo() {
   this.a = () => 1;
   this.b = () => 2;
 }
 Foo.prototype.c = () => 3;
 functions(new Foo()); // ['a', 'b']
 functions(new Foo(), true); // ['a', 'b', 'c']
-

get

Retrieve a set of properties indicated by the given selectors from an object.

Use Array.map() for each selector, String.replace() to replace square brackets with dots, String.split('.') to split each selector, Array.filter() to remove empty values and Array.reduce() to get the value indicated by it.

const get = (from, ...selectors) =>
+
intermediate

get

Retrieve a set of properties indicated by the given selectors from an object.

Use Array.map() for each selector, String.replace() to replace square brackets with dots, String.split('.') to split each selector, Array.filter() to remove empty values and Array.reduce() to get the value indicated by it.

const get = (from, ...selectors) =>
   [...selectors].map(s =>
     s
       .replace(/\[([^\[\]]*)\]/g, '.$1.')
@@ -201,58 +195,58 @@ Foo.prototypefilter(t => t !== '')
       .reduce((prev, cur) => prev && prev[cur], from)
   );
-
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
+
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
 get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']
-

invertKeyValues

Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.

Use Object.keys() and Array.reduce() to invert the key-value pairs of an object and apply the function provided (if any). Omit the second argument, fn, to get the inverted keys without applying a function to them.

const invertKeyValues = (obj, fn) =>
+
intermediate

invertKeyValues

Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.

Use Object.keys() and Array.reduce() to invert the key-value pairs of an object and apply the function provided (if any). Omit the second argument, fn, to get the inverted keys without applying a function to them.

const invertKeyValues = (obj, fn) =>
   Object.keys(obj).reduce((acc, key) => {
     const val = fn ? fn(obj[key]) : obj[key];
     acc[val] = acc[val] || [];
     acc[val].push(key);
     return acc;
   }, {});
-
invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] }
+
invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] }
 invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value); // { group1: [ 'a', 'c' ], group2: [ 'b' ] }
-

lowercaseKeys

Creates a new object from the specified object, where all the keys are in lowercase.

Use Object.keys() and Array.reduce() to create a new object from the specified object. Convert each key in the original object to lowercase, using String.toLowerCase().

const lowercaseKeys = obj =>
+
intermediate

lowercaseKeys

Creates a new object from the specified object, where all the keys are in lowercase.

Use Object.keys() and Array.reduce() to create a new object from the specified object. Convert each key in the original object to lowercase, using String.toLowerCase().

const lowercaseKeys = obj =>
   Object.keys(obj).reduce((acc, key) => {
     acc[key.toLowerCase()] = obj[key];
     return acc;
   }, {});
-
const myObj = { Name: 'Adam', sUrnAME: 'Smith' };
+
const myObj = { Name: 'Adam', sUrnAME: 'Smith' };
 const myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'};
-

mapKeys

Creates an object with keys generated by running the provided function for each key and the same values as the provided object.

Use Object.keys(obj) to iterate over the object's keys. Use Array.reduce() to create a new object with the same values and mapped keys using fn.

const mapKeys = (obj, fn) =>
+
intermediate

mapKeys

Creates an object with keys generated by running the provided function for each key and the same values as the provided object.

Use Object.keys(obj) to iterate over the object's keys. Use Array.reduce() to create a new object with the same values and mapped keys using fn.

const mapKeys = (obj, fn) =>
   Object.keys(obj).reduce((acc, k) => {
     acc[fn(obj[k], k, obj)] = obj[k];
     return acc;
   }, {});
-
mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }
-

mapValues

Creates an object with the same keys as the provided object and values generated by running the provided function for each value.

Use Object.keys(obj) to iterate over the object's keys. Use Array.reduce() to create a new object with the same keys and mapped values using fn.

const mapValues = (obj, fn) =>
+
mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }
+
intermediate

mapValues

Creates an object with the same keys as the provided object and values generated by running the provided function for each value.

Use Object.keys(obj) to iterate over the object's keys. Use Array.reduce() to create a new object with the same keys and mapped values using fn.

const mapValues = (obj, fn) =>
   Object.keys(obj).reduce((acc, k) => {
     acc[k] = fn(obj[k], k, obj);
     return acc;
   }, {});
-
const users = {
+
const users = {
   fred: { user: 'fred', age: 40 },
   pebbles: { user: 'pebbles', age: 1 }
 };
 mapValues(users, u => u.age); // { fred: 40, pebbles: 1 }
-

matches

Compares two objects to determine if the first one contains equivalent property values to the second one.

Use Object.keys(source) to get all the keys of the second object, then Array.every(), Object.hasOwnProperty() and strict comparison to determine if all keys exist in the first object and have the same values.

const matches = (obj, source) =>
+
intermediate

matches

Compares two objects to determine if the first one contains equivalent property values to the second one.

Use Object.keys(source) to get all the keys of the second object, then Array.every(), Object.hasOwnProperty() and strict comparison to determine if all keys exist in the first object and have the same values.

const matches = (obj, source) =>
   Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
-
matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true
+
matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true
 matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false
-

matchesWith

Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.

Use Object.keys(source) to get all the keys of the second object, then Array.every(), Object.hasOwnProperty() and the provided function to determine if all keys exist in the first object and have equivalent values. If no function is provided, the values will be compared using the equality operator.

const matchesWith = (obj, source, fn) =>
+
intermediate

matchesWith

Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.

Use Object.keys(source) to get all the keys of the second object, then Array.every(), Object.hasOwnProperty() and the provided function to determine if all keys exist in the first object and have equivalent values. If no function is provided, the values will be compared using the equality operator.

const matchesWith = (obj, source, fn) =>
   Object.keys(source).every(
     key =>
       obj.hasOwnProperty(key) && fn
         ? fn(obj[key], source[key], key, obj, source)
         : obj[key] == source[key]
   );
-
const isGreeting = val => /^h(?:i|ello)$/.test(val);
+
const isGreeting = val => /^h(?:i|ello)$/.test(val);
 matchesWith(
   { greeting: 'hello' },
   { greeting: 'hi' },
   (oV, sV) => isGreeting(oV) && isGreeting(sV)
 ); // true
-

merge

Creates a new object from the combination of two or more objects.

Use Array.reduce() combined with Object.keys(obj) to iterate over all objects and keys. Use hasOwnProperty() and Array.concat() to append values for keys existing in multiple objects.

const merge = (...objs) =>
+
intermediate

merge

Creates a new object from the combination of two or more objects.

Use Array.reduce() combined with Object.keys(obj) to iterate over all objects and keys. Use hasOwnProperty() and Array.concat() to append values for keys existing in multiple objects.

const merge = (...objs) =>
   [...objs].reduce(
     (acc, obj) =>
       Object.keys(obj).reduce((a, k) => {
@@ -261,7 +255,7 @@ Foo.prototypeShow examples
const object = {
+
const object = {
   a: [{ x: 2 }, { y: 4 }],
   b: 1
 };
@@ -271,11 +265,11 @@ Foo.prototype: 'foo'
 };
 merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }
-

nest

Given a flat array of objects linked to one another, it will nest them recursively. Useful for nesting comments, such as the ones on reddit.com.

Use recursion. Use Array.filter() to filter the items where the id matches the link, then Array.map() to map each one to a new object that has a children property which recursively nests the items based on which ones are children of the current item. Omit the second argument, id, to default to null which indicates the object is not linked to another one (i.e. it is a top level object). Omit the third argument, link, to use 'parent_id' as the default property which links the object to another one by its id.

const nest = (items, id = null, link = 'parent_id') =>
+
intermediate

nest

Given a flat array of objects linked to one another, it will nest them recursively. Useful for nesting comments, such as the ones on reddit.com.

Use recursion. Use Array.filter() to filter the items where the id matches the link, then Array.map() to map each one to a new object that has a children property which recursively nests the items based on which ones are children of the current item. Omit the second argument, id, to default to null which indicates the object is not linked to another one (i.e. it is a top level object). Omit the third argument, link, to use 'parent_id' as the default property which links the object to another one by its id.

const nest = (items, id = null, link = 'parent_id') =>
   items
     .filter(item => item[link] === id)
     .map(item => ({ ...item, children: nest(items, item.id) }));
-
// One top level comment
+
// One top level comment
 const comments = [
   { id: 1, parent_id: null },
   { id: 2, parent_id: 1 },
@@ -284,21 +278,21 @@ Foo.prototype: 5, parent_id: 4 }
 ];
 const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]
-

objectFromPairs

Creates an object from the given key-value pairs.

Use Array.reduce() to create and combine key-value pairs.

const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {});
-
objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}
-

objectToPairs

Creates an array of key-value pair arrays from an object.

Use Object.keys() and Array.map() to iterate over the object's keys and produce an array with key-value pairs.

const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
-
objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]]
-

omit

Omits the key-value pairs corresponding to the given keys from an object.

Use Object.keys(obj), Array.filter() and Array.includes() to remove the provided keys. Use Array.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.

const omit = (obj, arr) =>
+
intermediate

objectFromPairs

Creates an object from the given key-value pairs.

Use Array.reduce() to create and combine key-value pairs.

const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {});
+
objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}
+
intermediate

objectToPairs

Creates an array of key-value pair arrays from an object.

Use Object.keys() and Array.map() to iterate over the object's keys and produce an array with key-value pairs.

const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
+
objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]]
+
intermediate

omit

Omits the key-value pairs corresponding to the given keys from an object.

Use Object.keys(obj), Array.filter() and Array.includes() to remove the provided keys. Use Array.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.

const omit = (obj, arr) =>
   Object.keys(obj)
     .filter(k => !arr.includes(k))
     .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
-
omit({ a: 1, b: '2', c: 3 }, ['b']); // { 'a': 1, 'c': 3 }
-

omitBy

Creates an object composed of the properties the given function returns falsey for. The function is invoked with two arguments: (value, key).

Use Object.keys(obj) and Array.filter()to remove the keys for which fn returns a truthy value. Use Array.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.

const omitBy = (obj, fn) =>
+
omit({ a: 1, b: '2', c: 3 }, ['b']); // { 'a': 1, 'c': 3 }
+
intermediate

omitBy

Creates an object composed of the properties the given function returns falsey for. The function is invoked with two arguments: (value, key).

Use Object.keys(obj) and Array.filter()to remove the keys for which fn returns a truthy value. Use Array.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.

const omitBy = (obj, fn) =>
   Object.keys(obj)
     .filter(k => !fn(obj[k], k))
     .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
-
omitBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { b: '2' }
-

orderBy

Returns a sorted array of objects ordered by properties and orders.

Uses Array.sort(), Array.reduce() on the props array with a default value of 0, use array destructuring to swap the properties position depending on the order passed. If no orders array is passed it sort by 'asc' by default.

const orderBy = (arr, props, orders) =>
+
omitBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { b: '2' }
+
intermediate

orderBy

Returns a sorted array of objects ordered by properties and orders.

Uses Array.sort(), Array.reduce() on the props array with a default value of 0, use array destructuring to swap the properties position depending on the order passed. If no orders array is passed it sort by 'asc' by default.

const orderBy = (arr, props, orders) =>
   [...arr].sort((a, b) =>
     props.reduce((acc, prop, i) => {
       if (acc === 0) {
@@ -308,18 +302,18 @@ Foo.prototypereturn acc;
     }, 0)
   );
-
const users = [{ name: 'fred', age: 48 }, { name: 'barney', age: 36 }, { name: 'fred', age: 40 }];
+
const users = [{ name: 'fred', age: 48 }, { name: 'barney', age: 36 }, { name: 'fred', age: 40 }];
 orderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
 orderBy(users, ['name', 'age']); // [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
-

pick

Picks the key-value pairs corresponding to the given keys from an object.

Use Array.reduce() to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object.

const pick = (obj, arr) =>
+
intermediate

pick

Picks the key-value pairs corresponding to the given keys from an object.

Use Array.reduce() to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object.

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 }
-

pickBy

Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key).

Use Object.keys(obj) and Array.filter()to remove the keys for which fn returns a falsey value. Use Array.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.

const pickBy = (obj, fn) =>
+
pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
+
intermediate

pickBy

Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key).

Use Object.keys(obj) and Array.filter()to remove the keys for which fn returns a falsey value. Use Array.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.

const pickBy = (obj, fn) =>
   Object.keys(obj)
     .filter(k => fn(obj[k], k))
     .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
-
pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 }
-

renameKeys

Replaces the names of multiple object keys with the values provided.

Use Object.keys() in combination with Array.reduce() and the spread operator (...) to get the object's keys and rename them according to keysMap.

const renameKeys = (keysMap, obj) =>
+
pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 }
+
intermediate

renameKeys

Replaces the names of multiple object keys with the values provided.

Use Object.keys() in combination with Array.reduce() and the spread operator (...) to get the object's keys and rename them according to keysMap.

const renameKeys = (keysMap, obj) =>
   Object.keys(obj).reduce(
     (acc, key) => ({
       ...acc,
@@ -327,12 +321,12 @@ Foo.prototypeShow examples
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
+
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
 renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
-

shallowClone

Creates a shallow clone of an object.

Use Object.assign() and an empty object ({}) to create a shallow clone of the original.

const shallowClone = obj => Object.assign({}, obj);
-
const a = { x: true, y: 1 };
+
intermediate

shallowClone

Creates a shallow clone of an object.

Use Object.assign() and an empty object ({}) to create a shallow clone of the original.

const shallowClone = obj => Object.assign({}, obj);
+
const a = { x: true, y: 1 };
 const b = shallowClone(a); // a !== b
-

size

Get size of arrays, objects or strings.

Get type of val (array, object or string). Use length property for arrays. Use length or size value if available or number of keys for objects. Use size of a Blob object created from val for strings.

Split strings into array of characters with split('') and return its length.

const size = val =>
+
intermediate

size

Get size of arrays, objects or strings.

Get type of val (array, object or string). Use length property for arrays. Use length or size value if available or number of keys for objects. Use size of a Blob object created from val for strings.

Split strings into array of characters with split('') and return its length.

const size = val =>
   Array.isArray(val)
     ? val.length
     : val && typeof val === 'object'
@@ -340,11 +334,11 @@ Foo.prototype: typeof val === 'string'
         ? new Blob([val]).size
         : 0;
-
size([1, 2, 3, 4, 5]); // 5
+
size([1, 2, 3, 4, 5]); // 5
 size('size'); // 4
 size({ one: 1, two: 2, three: 3 }); // 3
-

transform

Applies a function against an accumulator and each key in the object (from left to right).

Use Object.keys(obj) to iterate over each key in the object, Array.reduce() to call the apply the specified function against the given accumulator.

const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
-
transform(
+
intermediate

transform

Applies a function against an accumulator and each key in the object (from left to right).

Use Object.keys(obj) to iterate over each key in the object, Array.reduce() to call the apply the specified function against the given accumulator.

const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
+
transform(
   { a: 1, b: 2, c: 1 },
   (r, v, k) => {
     (r[v] || (r[v] = [])).push(k);
@@ -352,9 +346,9 @@ Foo.prototype// { '1': ['a', 'c'], '2': ['b'] }
-

truthCheckCollection

Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).

Use Array.every() to check if each passed object has the specified property and if it returns a truthy value.

const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
-
truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true
-

unflattenObjectadvanced

Unflatten an object with the paths for keys.

Use Object.keys(obj) combined with Array.reduce() to convert flattened path node to a leaf node. If the value of a key contains a dot delimiter (.), use Array.split('.'), string transformations and JSON.parse() to create an object, then Object.assign() to create the leaf node. Otherwise, add the appropriate key-value pair to the accumulator object.

const unflattenObject = obj =>
+
intermediate

truthCheckCollection

Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).

Use Array.every() to check if each passed object has the specified property and if it returns a truthy value.

const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
+
truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true
+
advanced

unflattenObject

Unflatten an object with the paths for keys.

Use Object.keys(obj) combined with Array.reduce() to convert flattened path node to a leaf node. If the value of a key contains a dot delimiter (.), use Array.split('.'), string transformations and JSON.parse() to create an object, then Object.assign() to create the leaf node. Otherwise, add the appropriate key-value pair to the accumulator object.

const unflattenObject = obj =>
   Object.keys(obj).reduce((acc, k) => {
     if (k.indexOf('.') !== -1) {
       const keys = k.split('.');
@@ -370,5 +364,5 @@ Foo.prototypeelse acc[k] = obj[k];
     return acc;
   }, {});
-
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
-
\ No newline at end of file +
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
+
\ No newline at end of file diff --git a/docs/scss/style.scss b/docs/scss/style.scss new file mode 100644 index 000000000..fe764dd3e --- /dev/null +++ b/docs/scss/style.scss @@ -0,0 +1,869 @@ +$base-font-size: 16px; +$base-line-height: 1.5; +$__1px: (1px/$base-font-size) * 1rem; +$base-font-family: 'Roboto, Helvetica, sans-serif'; +$code-font-family: 'Roboto Mono, Menlo, Consolas, monospace'; +$code-font-size: 0.875em; +$_body-margin: 0; +$heading-line-height: 1.2; +$fore-color-var: '--fore-color'; +$fore-color: #212121; +$back-color-var: '--back-color'; +$back-color: #fff; +$border-color-var: '--border-color'; +$border-color: #eee; +$a-link-color-var: '--a-link-color'; +$a-link-color: #0277bd; +$a-visited-color-var: '--a-visited-color'; +$a-visited-color: #01579b; +$code-fore-color-var: '--code-fore-color'; +$code-fore-color: #8e24aa; +$code-back-color-var: '--code-back-color'; +$code-back-color: #f0f0f0; +$code-selected-color-var: '--code-selected-color'; +$code-selected-color: #37474f; +$pre-fore-color-var: '--pre-fore-color'; +$pre-fore-color: #e57373; +$pre-back-color-var: '--pre-back-color'; +$pre-back-color: #263238; +$token-color-a-var: '--token-color-a'; // Comments +$token-color-a: #7f99a5; +$token-color-b-var: '--token-color-b'; // Punctuation +$token-color-b: #bdbdbd; +$token-color-c-var: '--token-color-c'; // Functions +$token-color-c: #64b5f6; +$token-color-d-var: '--token-color-d'; // Numbers +$token-color-d: #ff8f00; +$token-color-e-var: '--token-color-e'; // Strings +$token-color-e: #c5e1a5; +$token-color-f-var: '--token-color-f'; // Keywords +$token-color-f: #ce93d8; +$token-color-g-var: '--token-color-g'; // Regular expressions +$token-color-g: #26c6da; +$token-color-h-var: '--token-color-h'; // Variables +$token-color-h: #e57373; +$collapse-color-var: '--collapse-color'; +$collapse-color: #607d8b; +$copy-button-color-var: '--copy-button-color'; +$copy-button-color: #1e88e5; +$copy-button-hover-color-var: '--copy-button-hover-color'; +$copy-button-hover-color: #2196f3; +$scrolltop-button-color-var: '--scrolltop-button-color'; +$scrolltop-button-color: #26a69a; +$scrolltop-button-hover-color-var: '--scrolltop-button-hover-color'; +$scrolltop-button-hover-color: #4db6ac; +$beginner-color-var: '--beginner-color'; +$beginner-color: #7cb342; +$intermediate-color-var: '--intermediate-color'; +$intermediate-color: #ffb300; +$advanced-color-var: '--advanced-color'; +$advanced-color: #e53935; +$header-fore-color-var: '--header-fore-color'; +$header-fore-color: #fff; +$header-back-color-var: '--header-back-color'; +$header-back-color: #202124; +$nav-fore-color-var: '--nav-fore-color'; +$nav-fore-color: #f0f0f0; +$nav-back-color-var: '--nav-back-color'; +$nav-back-color: #202124; +$nav-link-border-color-var: '--nav-link-border-color'; +$nav-link-border-color: #455a64; +$nav-link-fore-color-var: '--nav-link-fore-color'; +$nav-link-fore-color: #e0e0e0; +$nav-link-hover-color-var: '--nav-link-hover-color'; +$nav-link-hover-color: #2b2c30; +$search-fore-color-var: '--search-fore-color'; +$search-fore-color: #fafafa; +$search-back-color-var: '--search-back-color'; +$search-back-color: #111; +$search-border-color-var: '--search-border-color'; +$search-border-color: #9e9e9e; +$search-hover-border-color-var: '--search-hover-border-color'; +$search-hover-border-color: #26a69a; +$footer-fore-color-var: '--footer-fore-color'; +$footer-fore-color: #616161; +$footer-back-color-var: '--footer-back-color'; +$footer-back-color: #e0e0e0; +$universal-margin-var: '--universal-margin'; +$universal-margin: 0.5rem; +$universal-padding-var: '--universal-padding'; +$universal-padding: 0.5rem; +$universal-border-radius-var: '--universal-border-radius'; +$universal-border-radius: 0.125rem; +// ================= +$secondary-fore-color-var: '--secondary-fore-color'; // No use yet +$secondary-fore-color: #444; +$secondary-back-color-var: '--secondary-back-color'; // No use yet +$secondary-back-color: #f0f0f0; +$tertiary-fore-color-var: '--tertiary-fore-color'; // No use yet +$tertiary-fore-color: #222; + +// Load external fonts - progressive loading should help alleviate performance issues +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: local('Roboto Light'), local('Roboto-Light'), url(https://fonts.gstatic.com/s/roboto/v18/KFOlCnqEu92Fr1MmSU5fBBc4.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; + font-display: swap; +} +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-weight: 300; + src: local('Roboto Light Italic'), local('Roboto-LightItalic'), url(https://fonts.gstatic.com/s/roboto/v18/KFOjCnqEu92Fr1Mu51TjASc6CsQ.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; + font-display: swap; +} +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: local('Roboto Medium'), local('Roboto-Medium'), url(https://fonts.gstatic.com/s/roboto/v18/KFOlCnqEu92Fr1MmEU9fBBc4.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; + font-display: swap; +} +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: local('Roboto Mono Light'), local('RobotoMono-Light'), url(https://fonts.gstatic.com/s/robotomono/v5/L0xkDF4xlVMF-BfR8bXMIjDgiWqxf78.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; + font-display: swap; +} +@font-face { + font-family: 'Roboto Mono'; + font-style: italic; + font-weight: 300; + src: local('Roboto Mono Light Italic'), local('RobotoMono-LightItalic'), url(https://fonts.gstatic.com/s/robotomono/v5/L0xmDF4xlVMF-BfR8bXMIjhOk9a0T72jBg.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; + font-display: swap; +} +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: local('Roboto Mono Medium'), local('RobotoMono-Medium'), url(https://fonts.gstatic.com/s/robotomono/v5/L0xkDF4xlVMF-BfR8bXMIjC4iGqxf78.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; + font-display: swap; +} +// Set up variables for everything +:root { + #{$fore-color-var}: $fore-color; + #{$back-color-var}: $back-color; + #{$border-color-var}: $border-color; + #{$secondary-fore-color-var}: $secondary-fore-color; + #{$tertiary-fore-color-var}: $tertiary-fore-color; + #{$secondary-back-color-var}: $secondary-back-color; + #{$universal-margin-var}: $universal-margin; + #{$universal-padding-var}: $universal-padding; + #{$universal-border-radius-var}: $universal-border-radius; + #{$a-link-color-var} : $a-link-color; + #{$a-visited-color-var} : $a-visited-color; + #{$code-fore-color-var}: $code-fore-color; + #{$code-back-color-var}: $code-back-color; + #{$code-selected-color-var}: $code-selected-color; + #{$pre-fore-color-var}: $pre-fore-color; + #{$pre-back-color-var}: $pre-back-color; + #{$token-color-a-var}: $token-color-a; + #{$token-color-b-var}: $token-color-b; + #{$token-color-c-var}: $token-color-c; + #{$token-color-d-var}: $token-color-d; + #{$token-color-e-var}: $token-color-e; + #{$token-color-f-var}: $token-color-f; + #{$token-color-g-var}: $token-color-g; + #{$token-color-h-var}: $token-color-h; + #{$collapse-color-var}: $collapse-color; + #{$copy-button-color-var}: $copy-button-color; + #{$copy-button-hover-color-var}: $copy-button-hover-color; + #{$scrolltop-button-color-var}: $scrolltop-button-color; + #{$scrolltop-button-hover-color-var}: $scrolltop-button-hover-color; + #{$beginner-color-var}: $beginner-color; + #{$intermediate-color-var}: $intermediate-color; + #{$advanced-color-var}: $advanced-color; + #{$header-fore-color-var}: $header-fore-color; + #{$header-back-color-var}: $header-back-color; + #{$nav-fore-color-var}: $nav-fore-color; + #{$nav-back-color-var}: $nav-back-color; + #{$footer-fore-color-var}: $footer-fore-color; + #{$footer-back-color-var}: $footer-back-color; + #{$nav-link-fore-color-var}: $nav-link-fore-color; + #{$nav-link-border-color-var}: $nav-link-border-color; + #{$nav-link-hover-color-var}: $nav-link-hover-color; + #{$search-fore-color-var}: $search-fore-color; + #{$search-back-color-var}: $search-back-color; + #{$search-border-color-var}: $search-border-color; + #{$search-hover-border-color-var}: $search-hover-border-color; +} +// Set up some basic styling for everything +html { + font-size: $base-font-size; + scroll-behavior: smooth; +} +html, * { + font-family: #{$base-font-family}; + line-height: $base-line-height; + // Prevent adjustments of font size after orientation changes in mobile. + -webkit-text-size-adjust: 100%; +} +* { + font-size: 1rem; + font-weight: 300; +} +// Apply fixes and defaults as necessary for modern browsers only +a, b, del, em, i, ins, q, span, strong, u { + font-size: 1em; // Fix for elements inside headings not displaying properly. +} +body { + margin: $_body-margin; + color: var(#{$fore-color-var}); + background: var(#{$back-color-var}); + overflow-x: hidden; +} +// Correct display for Edge & Firefox. +details { + display: block; +} +// Correct display in all browsers. +summary { + display: list-item; +} +// Abbreviations +abbr[title] { + border-bottom: none; // Remove bottom border in Firefox 39-. + text-decoration: underline dotted; // Opinionated style-fix for all browsers. +} +// Show overflow in Edge. +input { + overflow: visible; +} +// Correct the cursor style of increment and decrement buttons in Chrome. +[type="number"]::-webkit-inner-spin-button, [type="number"]::-webkit-outer-spin-button { + height: auto; +} +// Correct style in Chrome and Safari. +[type="search"] { + -webkit-appearance: textfield; + outline-offset: -2px; +} +// Correct style in Chrome and Safari. +[type="search"]::-webkit-search-cancel-button, [type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} +// Make images responsive by default. +img { + max-width: 100%; + height: auto; +} +// Style headings according to material design guidelines +h1, h2, h3, h4, h5, h6 { + line-height: $heading-line-height; + margin: calc(1.5 * var(#{$universal-margin-var})) var(#{$universal-margin-var}); +} +h1 { + font-size: 6rem; +} +h2 { + font-size: 3.75rem; +} +h3 { + font-size: 3rem; +} +h4 { + font-size: 2.125rem; +} +h5 { + font-size: 1.5rem; +} +h6 { + font-size: 1.25rem; +} +// Style textual elements +p { + margin: var(#{$universal-margin-var}); +} +ol, ul { + margin: var(#{$universal-margin-var}); + padding-left: calc(2 * var(#{$universal-margin-var})); +} +b, strong { + font-weight: 500; +} +hr { + // Fixes and defaults for styling + box-sizing: content-box; + border: 0; + // Actual styling using variables + line-height: 1.25em; + margin: var(#{$universal-margin-var}); + height: $__1px; + background: linear-gradient(to right, transparent, var(#{$border-color-var}) 20%, var(#{$border-color-var}) 80%, transparent); +} +// Style code +code, kbd, pre { + font-size: $code-font-size; +} +code, kbd, pre, code *, pre *, kbd *, code[class*="language-"], pre[class*="language-"] { + font-family: #{$code-font-family}; +} +sup, sub, code, kbd { + line-height: 0; + position: relative; + vertical-align: baseline; +} + +code { + background: var(#{$code-back-color-var}); + color: var(#{$code-fore-color-var}); + padding: calc(var(#{$universal-padding-var}) / 4) calc(var(#{$universal-padding-var}) / 2); + border-radius: var(#{$universal-border-radius-var}); +} +/* === Unused so far === +kbd { + background: var(#{$fore-color-var}); + color: var(#{$back-color-var}); + border-radius: var(#{$universal-border-radius-var}); + padding: calc(var(#{$universal-padding-var}) / 4) calc(var(#{$universal-padding-var}) / 2); +} +*/ +pre { + overflow: auto; // Responsiveness + background: var(#{$pre-back-color-var}); + color: var(#{$pre-fore-color-var}); + padding: calc(1.5 * var(#{$universal-padding-var})); + margin: var(#{$universal-margin-var}); + border: 0; +} + +code[class*="language-"], pre[class*="language-"] { + color: var(#{$pre-fore-color-var}); + + text-align: left; + white-space: pre; + word-spacing: normal; + word-break: normal; + word-wrap: normal; + line-height: 1.8; + + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; + + -webkit-hypens: none; + -moz-hyphens: none; + -ms-hyphens: none; + hyphens: none; +} + +pre[class*="language-"] { + padding: calc(2 * var(#{$universal-padding-var})); + overflow: auto; + margin: var(#{$universal-margin-var}) 0; +} + +pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, +code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { + background: var(#{$code-selected-color-var}); +} + +pre[class*="language-"]::selection, pre[class*="language-"] ::selection, +code[class*="language-"]::selection, code[class*="language-"] ::selection { + background: var(#{$code-selected-color-var}); +} + +:not(pre) > code[class*="language-"] { + padding: .1em; + border-radius: .3em; + white-space: normal; +} + +.namespace { + opacity: .7; +} + +.token { + &.comment, &.prolog, &.doctype, &.cdata { + color: var(#{$token-color-a-var}); + } + &.punctuation { + color: var(#{$token-color-b-var}); + } + &.property, &.tag, &.boolean, &.constant, &.symbol, &.deleted, &.function { + color: var(#{$token-color-c-var}); + } + &.number, &.class-name { + color: var(#{$token-color-d-var}); + } + &.selector, &.attr-name, &.string, &.char, &.builtin, &.inserted { + color: var(#{$token-color-e-var}); + } + &.operator, &.entity, &.url, &.atrule, &.attr-value, &.keyword, &.interpolation-punctuation { + color: var(#{$token-color-f-var}); + } + &.regex { + color: var(#{$token-color-g-var}); + } + &.important, &.variable { + color: var(#{$token-color-h-var}); + } + &.italic, &.comment { + font-style: italic; + } + &.important, &.bold { + font-weight: 500; + } + &.entity { + cursor: help; + } +} +.language-css .token.string, .style .token.string { + color: var(#{$token-color-f-var}); +} + +a { + text-decoration: none; + &:link{ + color: var(#{$a-link-color-var}); + } + &:visited { + color: var(#{$a-visited-color-var}); + } + &:hover, &:focus { + text-decoration: underline; + } +} + +// Github Corner styles - Do not alter +.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}} + +/* +blockquote {} +sup {} +sub {} +figure {} +figcaption {} +*/ + +// =================================================== +// Layout +// =================================================== +$grid-medium-breakpoint: 768px; +$grid-large-breakpoint: 1280px; +// Grid container +.container { + display: grid; + grid-template-columns: repeat(12, 1fr); + grid-column-gap: calc(0.5 * var(#{$universal-margin-var})); + &.card-container { + position: absolute; + padding-top: 3.5rem; + height: calc(100vh - 3.5rem); + } +} +// Generic centered column +.col-centered { + grid-column: span 12; + max-width: 100%; + @media screen and (min-width: #{$grid-medium-breakpoint}) { + grid-column: 2/12; + } + @media screen and (min-width: #{$grid-large-breakpoint}) { + grid-column: 3/11; + } +} +// 25% width - For the 'in numbers' section +.col-quarter { + grid-column: span 3; +} +// 100% width +.col-full-width { + grid-column: span 12; +} +// For the contributors section +.flex-row { + display: flex; + flex: 0 1 auto; + flex-flow: row wrap; + .flex-item { + flex: 0 0 auto; + max-width: 50%; + flex-basis: 50%; + @media screen and (min-width: #{$grid-medium-breakpoint}) { + max-width: 25%; + flex-basis: 25%; + } + @media screen and (min-width: #{$grid-large-breakpoint}) { + max-width: 100%; + flex-grow: 1; + flex-basis: 0; + } + } +} +// =================================================== +// Cards +// =================================================== +h2.category-name { + text-align: center; +} +.card { + overflow: hidden; + position: relative; + margin: var(#{$universal-margin-var}); + border-radius: calc(4 * var(#{$universal-border-radius-var})); + box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.2); + h4 { + text-align: center; + padding-bottom: calc(0.75 * var(#{$universal-padding-var})); + margin-bottom: calc(2 * var(#{$universal-margin-var})); + border-bottom: $__1px solid var(#{$border-color-var}); + } + &.code-card { + margin-top: calc(5 * var(#{$universal-margin-var})); + background: var(#{$pre-back-color-var}); + .section.card-content{ + background: var(#{$back-color-var}); + padding: calc(1.5 * var(#{$universal-padding-var})); + } + .collapse { + display: block; + font-size: 0.75rem; + font-family: #{$code-font-family}; + text-transform: uppercase; + background: var(#{$pre-back-color-var}); + color: var(#{$collapse-color-var}); + padding: calc(1.5 * var(#{$universal-padding-var})) calc(1.5 * var(#{$universal-padding-var})) calc(2 * var(#{$universal-padding-var})) calc(2.25 * var(#{$universal-padding-var})); + cursor: pointer; + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23607D8B' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-plus-square'%3E%3Crect x='3' y='3' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='12' y1='8' x2='12' y2='16'%3E%3C/line%3E%3Cline x1='8' y1='12' x2='16' y2='12'%3E%3C/line%3E%3C/svg%3E"); + background-position: 0.25rem 0.9375rem; + background-repeat: no-repeat; + + pre.card-examples { + position: absolute; + transform: scaleY(0); + transform-origin: top; + transition: transform 0.3s ease; + } + &.toggled{ + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23607D8B' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-minus-square'%3E%3Crect x='3' y='3' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='8' y1='12' x2='16' y2='12'%3E%3C/line%3E%3C/svg%3E"); + padding-bottom: calc(0.125 * var(#{$universal-padding-var})); + + pre.card-examples { + position: relative; + transform: scaleY(1); + } + } + } + pre.section { + &.card-code { + position: relative; + margin-bottom: 0; + padding-bottom: 0; + } + &.card-examples { + margin-top: 0; + margin-bottom: 0; + border-radius: 0 0 calc(4 * var(#{$universal-border-radius-var})) calc(4 * var(#{$universal-border-radius-var})); + padding-top: 0; + &:before { + content: ''; + display: block; + position: absolute; + top: 0; + left: 0.5625rem; + border-left: $__1px solid var(#{$collapse-color-var}); + height: calc(100% - 18px); + } + } + } + .copy-button-container { + position: relative; + z-index: 2; + .copy-button { + background: var(#{$copy-button-color-var}); + box-sizing: border-box; + position: absolute; + top: -1.75rem; + right: 0; + margin: calc(2 * var(#{$universal-margin-var})); + padding: calc(2.5 * var(#{$universal-padding-var})); + border-radius: 50%; + border: 0; + box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.2); + transition: all 0.3s ease; + cursor: pointer; + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-clipboard'%3E%3Cpath d='M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2'%3E%3C/path%3E%3Crect x='8' y='2' width='8' height='4' rx='1' ry='1'%3E%3C/rect%3E%3C/svg%3E"); + background-position: center center; + background-repeat: no-repeat; + &:hover, &:focus { + background-color: var(#{$copy-button-hover-color-var}); + box-shadow: 0 3px 3px 0 rgba(0, 0, 0, 0.14), 0 1px 7px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -1px rgba(0, 0, 0, 0.2); + } + &:before { + background: var(#{$back-color-var}); + position: absolute; + top: -0.25rem; + right: -0.25rem; + content: ''; + display: block; + box-sizing: border-box; + padding: calc(2.5 * var(#{$universal-padding-var})); + border-radius: 50%; + border: 0.25rem solid var(#{$back-color-var}); + z-index: -1; + } + } + } + .corner { + box-sizing: border-box; + position: absolute; + top: -0.5rem; + right: -2.125rem; + width: 6.5rem; + height: 3.25rem; + padding-top: 2rem; + transform: rotate(45deg); + text-align: center; + font-size: 0.75rem; + font-weight: 500; + color: var(#{$back-color-var}); + box-shadow: 0 2px 2px 0 rgba(0,0,0,0.07),0 3px 1px -2px rgba(0,0,0,0.06),0 1px 5px 0 rgba(0,0,0,0.1); + &.beginner { + background: var(#{$beginner-color-var}); + } + &.intermediate { + background: var(#{$intermediate-color-var}); + } + &.advanced { + background: var(#{$advanced-color-var}); + } + } + } +} +// =================================================== +// Toast +// =================================================== +.toast { + position: fixed; + bottom: calc(var(#{$universal-margin-var}) * 2); + margin-bottom: 0; + font-size: 0.8125rem; + left: 50%; + transform: translate(-50%, -50%); + z-index: 1111; + color: var(#{$back-color-var}); + background: var(#{$fore-color-var}); + border-radius: calc(var(#{$universal-border-radius-var}) * 16); + padding: var(#{$universal-padding-var}) calc(var(#{$universal-padding-var}) * 2); + box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.2); + transition: all 0.3s ease; +} +// =================================================== +// Navigation +// =================================================== +header { + box-sizing: border-box; + overflow: hidden; + height: 3.5rem; + position: fixed; + width: 110%; + top: 0; + left: -5%; + box-shadow: 0 2px 4px rgba(0,0,0,.5); + z-index: 5; + background: var(#{$header-back-color-var}); + transition: top 0.3s ease; + h1 { + &.logo { + position: relative; + top: 0; + margin-top: 0; + font-size: 1.625rem; + text-align: center; + // transition: top 0.3s ease; + } + a, a:link, a:visited { + color: var(#{$header-fore-color-var}); + &:hover, &:focus { + text-decoration: none; + } + } + small { + display: block; + font-size: 0.875rem; + color: var(#{$header-back-color-var}); + margin-top: 0.75rem; + } + } + img { + height: 3.5rem; + padding: 0.375rem; + box-sizing: border-box; + } + #title { + position: relative; + top: -1.125rem; + @media screen and (max-width: 768px) { display: none; } + } +} + +nav { + position: fixed; + top: 3.5rem; + left: -320px; + width: 320px; + transition: left 0.3s ease; + z-index: 1100; + height: calc(100vh - 3.5rem); + box-sizing: border-box; + display: block; + background: var(#{$nav-back-color-var}); + border: 0; + overflow-y: auto; + @media screen and (max-width: 320px) { + width: 100%; + } + @media screen and (min-width: #{$grid-medium-breakpoint}) { + width: 33vw; + left: -33vw; + } + @media screen and (min-width: #{$grid-large-breakpoint}) { + width: 25vw; + left: -25vw; + } + &.col-nav { + box-shadow: 0 8px 17px 2px rgba(0,0,0,0.14),0 3px 14px 2px rgba(0,0,0,0.12),0 5px 5px -3px rgba(0,0,0,0.2); + left: 0; + // Also apply the main content style to the footer + @media screen and (min-width: #{$grid-medium-breakpoint}) { + + main.col-centered, + main.col-centered + footer.col-full-width { + grid-column: 5/13; + } + } + @media screen and (min-width: #{$grid-large-breakpoint}) { + + main.col-centered { + grid-column: 4/12; + padding-left: 8vw; + } + + main.col-centered + footer.col-full-width { + grid-column: 4/13; + } + } + } + h4 { + margin: var(#{$universal-margin-var}); + padding: var(#{$universal-padding-var}) calc(1.5 * var(#{$universal-padding-var})); + padding-left: 0; + color: var(#{$nav-fore-color-var}); + } + a { + display: block; + margin: calc(0.5 * var(#{$universal-margin-var})); + margin-left: var(#{$universal-margin-var}); + margin-bottom: 0; + padding: calc(2 * var(#{$universal-padding-var})) calc(1.5 * var(#{$universal-padding-var})); + border-left: $__1px solid var(#{$nav-link-border-color-var}); + &:hover { + text-decoration: none; + background: var(#{$nav-link-hover-color-var}); + } + + a { + margin-top: 0; + } + &:link, &:visited { + color: var(#{$nav-link-fore-color-var}); + } + } +} + +[type="search"] { + color: var(#{$search-fore-color-var}); + background: var(#{$search-back-color-var}); + outline: none; + box-sizing: border-box; + border: none; + border-bottom: $__1px solid var(#{$search-border-color-var}); + width: 100%; + margin-bottom: var(#{$universal-margin-var}); + padding: calc(2 * var(#{$universal-padding-var})) calc(1.5 * var(#{$universal-padding-var})) var(#{$universal-padding-var}) calc(1.5 * var(#{$universal-padding-var})); + transition: all 0.3s ease; + &:hover, &:focus { + border-bottom: $__1px solid var(#{$search-hover-border-color-var}); + } + &:focus { + box-shadow: 0 $__1px 0 0 var(#{$search-hover-border-color-var}); + } +} + +.menu-button { + position: fixed; + top: 0; + left: 0; + z-index: 1000; + box-sizing: border-box; + height: 3.5rem; + width: 3.5rem; + border: 0; + background: transparent; + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23fafafa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-more-horizontal'%3E%3Ccircle cx='12' cy='12' r='1'%3E%3C/circle%3E%3Ccircle cx='19' cy='12' r='1'%3E%3C/circle%3E%3Ccircle cx='5' cy='12' r='1'%3E%3C/circle%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: 0.875rem 0.875rem; + cursor: pointer; + transition: all 0.3s ease; + &:hover { + background-color: rgba(255,255,255, 0.08); + } + &.toggled { + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23fafafa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-more-vertical'%3E%3Ccircle cx='12' cy='12' r='1'%3E%3C/circle%3E%3Ccircle cx='12' cy='5' r='1'%3E%3C/circle%3E%3Ccircle cx='12' cy='19' r='1'%3E%3C/circle%3E%3C/svg%3E"); + } +} + +footer { + color: var(#{$footer-fore-color-var}); + background: var(#{$footer-back-color-var}); + padding-top: calc(2 * var(#{$universal-padding-var})); + padding-bottom: calc(3 * var(#{$universal-padding-var})); + margin-top: calc(6 * var(#{$universal-margin-var})); + * { + font-size: 0.875rem; + } + a, a:link, a:visited { + color: var(#{$fore-color-var}); + } +} + +.scroll-to-top { + position: fixed; + bottom: 1rem; + right: 1.3125rem; + box-sizing: border-box; + z-index: 1100; + height: 2.75rem; + width: 2.75rem; + border: 0; + border-radius: 100%; + background: var(#{$scrolltop-button-color-var}); + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-arrow-up'%3E%3Cline x1='12' y1='19' x2='12' y2='5'%3E%3C/line%3E%3Cpolyline points='5 12 12 5 19 12'%3E%3C/polyline%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: center center; + cursor: pointer; + box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.2); + transition: all 0.3s ease; + &:hover, &:focus { + background-color: var(#{$scrolltop-button-hover-color-var}); + box-shadow: 0 3px 3px 0 rgba(0,0,0,0.14),0 1px 7px 0 rgba(0,0,0,0.12),0 3px 1px -1px rgba(0,0,0,0.2); + } +} + +// About page +.card.contributor > .section.button { + font-size: 1rem; + font-weight: 500; + text-align: center; + display: block; + transition: all 0.3s ease; + &:link, &:visited { + color: var(#{$fore-color-var}); + &:hover { + color: var(#{$a-link-color-var}); + text-decoration: none; + } + } +} \ No newline at end of file diff --git a/docs/string.html b/docs/string.html index 778d8d658..fd7ca049d 100644 --- a/docs/string.html +++ b/docs/string.html @@ -1,6 +1,6 @@ -String - 30 seconds of codeString - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

String

byteSize

Returns the length of a string in bytes.

Convert a given string to a Blob Object and find its size.

const byteSize = str => new Blob([str]).size;
-
byteSize('😀'); // 4
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



String

intermediate

byteSize

Returns the length of a string in bytes.

Convert a given string to a Blob Object and find its size.

const byteSize = str => new Blob([str]).size;
+
byteSize('😀'); // 4
 byteSize('Hello World'); // 11
-

capitalize

Capitalizes the first letter of a string.

Use array destructuring and String.toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.join('') to make it a string again. Omit the lowerRest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

const capitalize = ([first, ...rest], lowerRest = false) =>
+
intermediate

capitalize

Capitalizes the first letter of a string.

Use array destructuring and String.toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.join('') to make it a string again. Omit the lowerRest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

const capitalize = ([first, ...rest], lowerRest = false) =>
   first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
-
capitalize('fooBar'); // 'FooBar'
+
capitalize('fooBar'); // 'FooBar'
 capitalize('fooBar', true); // 'Foobar'
-

capitalizeEveryWord

Capitalizes the first letter of every word in a string.

Use String.replace() to match the first character of each word and String.toUpperCase() to capitalize it.

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
-
capitalizeEveryWord('hello world!'); // 'Hello World!'
-

CSVToArray

Converts a comma-separated values (CSV) string to a 2D array.

Use Array.slice() and Array.indexOf('\n') to remove the first row (title row) if omitFirstRow is true. Use String.split('\n') to create a string for each row, then String.split(delimiter) to separate the values in each row. Omit the second argument, delimiter, to use a default delimiter of ,. Omit the third argument, omitFirstRow, to include the first row (title row) of the CSV string.

const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
+
intermediate

capitalizeEveryWord

Capitalizes the first letter of every word in a string.

Use String.replace() to match the first character of each word and String.toUpperCase() to capitalize it.

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
+
capitalizeEveryWord('hello world!'); // 'Hello World!'
+
intermediate

CSVToArray

Converts a comma-separated values (CSV) string to a 2D array.

Use Array.slice() and Array.indexOf('\n') to remove the first row (title row) if omitFirstRow is true. Use String.split('\n') to create a string for each row, then String.split(delimiter) to separate the values in each row. Omit the second argument, delimiter, to use a default delimiter of ,. Omit the third argument, omitFirstRow, to include the first row (title row) of the CSV string.

const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
   data
     .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
     .split('\n')
     .map(v => v.split(delimiter));
-
CSVToArray('a,b\nc,d'); // [['a','b'],['c','d']];
+
CSVToArray('a,b\nc,d'); // [['a','b'],['c','d']];
 CSVToArray('a;b\nc;d', ';'); // [['a','b'],['c','d']];
 CSVToArray('col1,col2\na,b\nc,d', ',', true); // [['a','b'],['c','d']];
-

CSVToJSONadvanced

Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.

Use Array.slice() and Array.indexOf('\n') and String.split(delimiter) to separate the first row (title row) into values. Use String.split('\n') to create a string for each row, then Array.map() and String.split(delimiter) to separate the values in each row. Use Array.reduce() to create an object for each row's values, with the keys parsed from the title row. Omit the second argument, delimiter, to use a default delimiter of ,.

const CSVToJSON = (data, delimiter = ',') => {
+
advanced

CSVToJSON

Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.

Use Array.slice() and Array.indexOf('\n') and String.split(delimiter) to separate the first row (title row) into values. Use String.split('\n') to create a string for each row, then Array.map() and String.split(delimiter) to separate the values in each row. Use Array.reduce() to create an object for each row's values, with the keys parsed from the title row. Omit the second argument, delimiter, to use a default delimiter of ,.

const CSVToJSON = (data, delimiter = ',') => {
   const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
   return data
     .slice(data.indexOf('\n') + 1)
@@ -106,13 +100,13 @@
       return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
     });
 };
-
CSVToJSON('col1,col2\na,b\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
+
CSVToJSON('col1,col2\na,b\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
 CSVToJSON('col1;col2\na;b\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
-

decapitalize

Decapitalizes the first letter of a string.

Use array destructuring and String.toLowerCase() to decapitalize first letter, ...rest to get array of characters after first letter and then Array.join('') to make it a string again. Omit the upperRest parameter to keep the rest of the string intact, or set it to true to convert to uppercase.

const decapitalize = ([first, ...rest], upperRest = false) =>
+
intermediate

decapitalize

Decapitalizes the first letter of a string.

Use array destructuring and String.toLowerCase() to decapitalize first letter, ...rest to get array of characters after first letter and then Array.join('') to make it a string again. Omit the upperRest parameter to keep the rest of the string intact, or set it to true to convert to uppercase.

const decapitalize = ([first, ...rest], upperRest = false) =>
   first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
-
decapitalize('FooBar'); // 'fooBar'
+
decapitalize('FooBar'); // 'fooBar'
 decapitalize('FooBar', true); // 'fOOBAR'
-

escapeHTML

Escapes a string for use in HTML.

Use String.replace() with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).

const escapeHTML = str =>
+
intermediate

escapeHTML

Escapes a string for use in HTML.

Use String.replace() with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).

const escapeHTML = str =>
   str.replace(
     /[&<>'"]/g,
     tag =>
@@ -124,22 +118,22 @@
         '"': '&quot;'
       }[tag] || tag)
   );
-
escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'
-

escapeRegExp

Escapes a string to use in a regular expression.

Use String.replace() to escape special characters.

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-
escapeRegExp('(test)'); // \\(test\\)
-

fromCamelCase

Converts a string from camelcase.

Use String.replace() to remove underscores, hyphens, and spaces and convert words to camelcase. Omit the second argument to use a default separator of _.

const fromCamelCase = (str, separator = '_') =>
+
escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'
+
intermediate

escapeRegExp

Escapes a string to use in a regular expression.

Use String.replace() to escape special characters.

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
escapeRegExp('(test)'); // \\(test\\)
+
intermediate

fromCamelCase

Converts a string from camelcase.

Use String.replace() to remove underscores, hyphens, and spaces and convert words to camelcase. Omit the second argument to use a default separator of _.

const fromCamelCase = (str, separator = '_') =>
   str
     .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
     .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
     .toLowerCase();
-
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
+
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
 fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'
 fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
-

isAbsoluteURL

Returns true if the given string is an absolute URL, false otherwise.

Use a regular expression to test if the string is an absolute URL.

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
-
isAbsoluteURL('https://google.com'); // true
+
intermediate

isAbsoluteURL

Returns true if the given string is an absolute URL, false otherwise.

Use a regular expression to test if the string is an absolute URL.

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
+
isAbsoluteURL('https://google.com'); // true
 isAbsoluteURL('ftp://www.myserver.net'); // true
 isAbsoluteURL('/foo/bar'); // false
-

isAnagram

Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).

Use String.toLowerCase(), String.replace() with an appropriate regular expression to remove unnecessary characters, String.split(''), Array.sort() and Array.join('') on both strings to normalize them, then check if their normalized forms are equal.

const isAnagram = (str1, str2) => {
+
intermediate

isAnagram

Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).

Use String.toLowerCase(), String.replace() with an appropriate regular expression to remove unnecessary characters, String.split(''), Array.sort() and Array.join('') on both strings to normalize them, then check if their normalized forms are equal.

const isAnagram = (str1, str2) => {
   const normalize = str =>
     str
       .toLowerCase()
@@ -149,43 +143,43 @@
       .join('');
   return normalize(str1) === normalize(str2);
 };
-
isAnagram('iceman', 'cinema'); // true
-

isLowerCase

Checks if a string is lower case.

Convert the given string to lower case, using String.toLowerCase() and compare it to the original.

const isLowerCase = str => str === str.toLowerCase();
-
isLowerCase('abc'); // true
+
isAnagram('iceman', 'cinema'); // true
+
intermediate

isLowerCase

Checks if a string is lower case.

Convert the given string to lower case, using String.toLowerCase() and compare it to the original.

const isLowerCase = str => str === str.toLowerCase();
+
isLowerCase('abc'); // true
 isLowerCase('a3@$'); // true
 isLowerCase('Ab4'); // false
-

isUpperCase

Checks if a string is upper case.

Convert the given string to upper case, using String.toUpperCase() and compare it to the original.

const isUpperCase = str => str === str.toUpperCase();
-
isUpperCase('ABC'); // true
+
intermediate

isUpperCase

Checks if a string is upper case.

Convert the given string to upper case, using String.toUpperCase() and compare it to the original.

const isUpperCase = str => str === str.toUpperCase();
+
isUpperCase('ABC'); // true
 isLowerCase('A3@$'); // true
 isLowerCase('aB4'); // false
-

mapString

Creates a new string with the results of calling a provided function on every character in the calling string.

Use String.split('') and Array.map() to call the provided function, fn, for each character in str. Use Array.join('') to recombine the array of characters into a string. The callback function, fn, takes three arguments (the current character, the index of the current character and the string mapString was called upon).

const mapString = (str, fn) =>
+
intermediate

mapString

Creates a new string with the results of calling a provided function on every character in the calling string.

Use String.split('') and Array.map() to call the provided function, fn, for each character in str. Use Array.join('') to recombine the array of characters into a string. The callback function, fn, takes three arguments (the current character, the index of the current character and the string mapString was called upon).

const mapString = (str, fn) =>
   str
     .split('')
     .map((c, i) => fn(c, i, str))
     .join('');
-
mapString('lorem ipsum', c => c.toUpperCase()); // 'LOREM IPSUM'
-

mask

Replaces all but the last num of characters with the specified mask character.

Use String.slice() to grab the portion of the characters that need to be masked and use String.replace() with a regexp to replace every character with the mask character. Concatenate the masked characters with the remaining unmasked portion of the string. Omit the second argument, num, to keep a default of 4 characters unmasked. If num is negative, the unmasked characters will be at the start of the string. Omit the third argument, mask, to use a default character of '*' for the mask.

const mask = (cc, num = 4, mask = '*') =>
+
mapString('lorem ipsum', c => c.toUpperCase()); // 'LOREM IPSUM'
+
intermediate

mask

Replaces all but the last num of characters with the specified mask character.

Use String.slice() to grab the portion of the characters that need to be masked and use String.replace() with a regexp to replace every character with the mask character. Concatenate the masked characters with the remaining unmasked portion of the string. Omit the second argument, num, to keep a default of 4 characters unmasked. If num is negative, the unmasked characters will be at the start of the string. Omit the third argument, mask, to use a default character of '*' for the mask.

const mask = (cc, num = 4, mask = '*') =>
   ('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num);
-
mask(1234567890); // '******7890'
+
mask(1234567890); // '******7890'
 mask(1234567890, 3); // '*******890'
 mask(1234567890, -4, '$'); // '$$$$567890'
-

pad

Pads a string on both sides with the specified character, if it's shorter than the specified length.

Use String.padStart() and String.padEnd() to pad both sides of the given string. Omit the third argument, char, to use the whitespace character as the default padding character.

const pad = (str, length, char = ' ') =>
+
intermediate

pad

Pads a string on both sides with the specified character, if it's shorter than the specified length.

Use String.padStart() and String.padEnd() to pad both sides of the given string. Omit the third argument, char, to use the whitespace character as the default padding character.

const pad = (str, length, char = ' ') =>
   str.padStart((str.length + length) / 2, char).padEnd(length, char);
-
pad('cat', 8); // '  cat   '
+
pad('cat', 8); // '  cat   '
 pad(String(42), 6, '0'); // '004200'
 pad('foobar', 3); // 'foobar'
-

palindrome

Returns true if the given string is a palindrome, false otherwise.

Convert string String.toLowerCase() and use String.replace() to remove non-alphanumeric characters from it. Then, use the spread operator (...) to split string into individual characters, Array.reverse(), String.join('') and compare to the original, unreversed string, after converting it String.tolowerCase().

const palindrome = str => {
+
intermediate

palindrome

Returns true if the given string is a palindrome, false otherwise.

Convert string String.toLowerCase() and use String.replace() to remove non-alphanumeric characters from it. Then, use the spread operator (...) to split string into individual characters, Array.reverse(), String.join('') and compare to the original, unreversed string, after converting it String.tolowerCase().

const palindrome = str => {
   const s = str.toLowerCase().replace(/[\W_]/g, '');
   return s === [...s].reverse().join('');
 };
-
palindrome('taco cat'); // true
-

pluralize

Returns the singular or plural form of the word based on the input number. If the first argument is an object, it will use a closure by returning a function that can auto-pluralize words that don't simply end in s if the supplied dictionary contains the word.

If num is either -1 or 1, return the singular form of the word. If num is any other number, return the plural form. Omit the third argument to use the default of the singular word + s, or supply a custom pluralized word when necessary. If the first argument is an object, utilize a closure by returning a function which can use the supplied dictionary to resolve the correct plural form of the word.

const pluralize = (val, word, plural = word + 's') => {
+
palindrome('taco cat'); // true
+
intermediate

pluralize

Returns the singular or plural form of the word based on the input number. If the first argument is an object, it will use a closure by returning a function that can auto-pluralize words that don't simply end in s if the supplied dictionary contains the word.

If num is either -1 or 1, return the singular form of the word. If num is any other number, return the plural form. Omit the third argument to use the default of the singular word + s, or supply a custom pluralized word when necessary. If the first argument is an object, utilize a closure by returning a function which can use the supplied dictionary to resolve the correct plural form of the word.

const pluralize = (val, word, plural = word + 's') => {
   const _pluralize = (num, word, plural = word + 's') =>
     [1, -1].includes(Number(num)) ? word : plural;
   if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]);
   return _pluralize(val, word, plural);
 };
-
pluralize(0, 'apple'); // 'apples'
+
pluralize(0, 'apple'); // 'apples'
 pluralize(1, 'apple'); // 'apple'
 pluralize(2, 'apple'); // 'apples'
 pluralize(2, 'person', 'people'); // 'people'
@@ -196,15 +190,15 @@
 };
 const autoPluralize = pluralize(PLURALS);
 autoPluralize(2, 'person'); // 'people'
-

removeNonASCII

Removes non-printable ASCII characters.

Use a regular expression to remove non-printable ASCII characters.

const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
-
removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'
-

reverseString

Reverses a string.

Use the spread operator (...) and Array.reverse() to reverse the order of the characters in the string. Combine characters to get a string using String.join('').

const reverseString = str => [...str].reverse().join('');
-
reverseString('foobar'); // 'raboof'
-

sortCharactersInString

Alphabetically sorts the characters in a string.

Use the spread operator (...), Array.sort() and String.localeCompare() to sort the characters in str, recombine using String.join('').

const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
-
sortCharactersInString('cabbage'); // 'aabbceg'
-

splitLines

Splits a multiline string into an array of lines.

Use String.split() and a regular expression to match line breaks and create an array.

const splitLines = str => str.split(/\r?\n/);
-
splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']
-

stringPermutations

⚠️ WARNING: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.

Generates all permutations of a string (contains duplicates).

Use recursion. For each letter in the given string, create all the partial permutations for the rest of its letters. Use Array.map() to combine the letter with each partial permutation, then Array.reduce() to combine all permutations in one array. Base cases are for string length equal to 2 or 1.

const stringPermutations = str => {
+
intermediate

removeNonASCII

Removes non-printable ASCII characters.

Use a regular expression to remove non-printable ASCII characters.

const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
+
removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'
+
beginner

reverseString

Reverses a string.

Use the spread operator (...) and Array.reverse() to reverse the order of the characters in the string. Combine characters to get a string using String.join('').

const reverseString = str => [...str].reverse().join('');
+
reverseString('foobar'); // 'raboof'
+
intermediate

sortCharactersInString

Alphabetically sorts the characters in a string.

Use the spread operator (...), Array.sort() and String.localeCompare() to sort the characters in str, recombine using String.join('').

const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
+
sortCharactersInString('cabbage'); // 'aabbceg'
+
intermediate

splitLines

Splits a multiline string into an array of lines.

Use String.split() and a regular expression to match line breaks and create an array.

const splitLines = str => str.split(/\r?\n/);
+
splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']
+
intermediate

stringPermutations

⚠️ WARNING: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.

Generates all permutations of a string (contains duplicates).

Use recursion. For each letter in the given string, create all the partial permutations for the rest of its letters. Use Array.map() to combine the letter with each partial permutation, then Array.reduce() to combine all permutations in one array. Base cases are for string length equal to 2 or 1.

const stringPermutations = str => {
   if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
   return str
     .split('')
@@ -214,10 +208,10 @@
       []
     );
 };
-
stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba']
-

stripHTMLTags

Removes HTML/XML tags from string.

Use a regular expression to remove HTML/XML tags from a string.

const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
-
stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'
-

toCamelCase

Converts a string to camelcase.

Break the string into words and combine them capitalizing the first letter of each word, using a regexp.

const toCamelCase = str => {
+
stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba']
+
intermediate

stripHTMLTags

Removes HTML/XML tags from string.

Use a regular expression to remove HTML/XML tags from a string.

const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
+
stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'
+
intermediate

toCamelCase

Converts a string to camelcase.

Break the string into words and combine them capitalizing the first letter of each word, using a regexp.

const toCamelCase = str => {
   let s =
     str &&
     str
@@ -226,36 +220,36 @@
       .join('');
   return s.slice(0, 1).toLowerCase() + s.slice(1);
 };
-
toCamelCase('some_database_field_name'); // 'someDatabaseFieldName'
+
toCamelCase('some_database_field_name'); // 'someDatabaseFieldName'
 toCamelCase('Some label that needs to be camelized'); // 'someLabelThatNeedsToBeCamelized'
 toCamelCase('some-javascript-property'); // 'someJavascriptProperty'
 toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMixedStringWithSpacesUnderscoresAndHyphens'
-

toKebabCase

Converts a string to kebab case.

Break the string into words and combine them adding - as a separator, using a regexp.

const toKebabCase = str =>
+
intermediate

toKebabCase

Converts a string to kebab case.

Break the string into words and combine them adding - as a separator, using a regexp.

const toKebabCase = str =>
   str &&
   str
     .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
     .map(x => x.toLowerCase())
     .join('-');
-
toKebabCase('camelCase'); // 'camel-case'
+
toKebabCase('camelCase'); // 'camel-case'
 toKebabCase('some text'); // 'some-text'
 toKebabCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some-mixed-string-with-spaces-underscores-and-hyphens'
 toKebabCase('AllThe-small Things'); // "all-the-small-things"
 toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"
-

toSnakeCase

Converts a string to snake case.

Break the string into words and combine them adding _ as a separator, using a regexp.

const toSnakeCase = str =>
+
intermediate

toSnakeCase

Converts a string to snake case.

Break the string into words and combine them adding _ as a separator, using a regexp.

const toSnakeCase = str =>
   str &&
   str
     .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
     .map(x => x.toLowerCase())
     .join('_');
-
toSnakeCase('camelCase'); // 'camel_case'
+
toSnakeCase('camelCase'); // 'camel_case'
 toSnakeCase('some text'); // 'some_text'
 toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens'
 toSnakeCase('AllThe-small Things'); // "all_the_smal_things"
 toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html"
-

truncateString

Truncates a string up to a specified length.

Determine if the string's length is greater than num. Return the string truncated to the desired length, with '...' appended to the end or the original string.

const truncateString = (str, num) =>
+
beginner

truncateString

Truncates a string up to a specified length.

Determine if the string's length is greater than num. Return the string truncated to the desired length, with '...' appended to the end or the original string.

const truncateString = (str, num) =>
   str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
-
truncateString('boomerang', 7); // 'boom...'
-

unescapeHTML

Unescapes escaped HTML characters.

Use String.replace() with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).

const unescapeHTML = str =>
+
truncateString('boomerang', 7); // 'boom...'
+
intermediate

unescapeHTML

Unescapes escaped HTML characters.

Use String.replace() with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).

const unescapeHTML = str =>
   str.replace(
     /&amp;|&lt;|&gt;|&#39;|&quot;/g,
     tag =>
@@ -267,8 +261,8 @@
         '&quot;': '"'
       }[tag] || tag)
   );
-
unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'
-

URLJoin

Joins all given URL segments together, then normalizes the resulting URL.

Use String.join('/') to combine URL segments, then a series of String.replace() calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&' and normalize first parameter delimiter).

const URLJoin = (...args) =>
+
unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'
+
intermediate

URLJoin

Joins all given URL segments together, then normalizes the resulting URL.

Use String.join('/') to combine URL segments, then a series of String.replace() calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&' and normalize first parameter delimiter).

const URLJoin = (...args) =>
   args
     .join('/')
     .replace(/[\/]+/g, '/')
@@ -277,8 +271,8 @@
     .replace(/\/(\?|&|#[^!])/g, '$1')
     .replace(/\?/g, '&')
     .replace('&', '?');
-
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'
-

words

Converts a given string into an array of words.

Use String.split() with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use Array.filter() to remove any empty strings. Omit the second argument to use the default regexp.

const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
-
words('I love javaScript!!'); // ["I", "love", "javaScript"]
+
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'
+
intermediate

words

Converts a given string into an array of words.

Use String.split() with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use Array.filter() to remove any empty strings. Omit the second argument to use the default regexp.

const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
+
words('I love javaScript!!'); // ["I", "love", "javaScript"]
 words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/style.css b/docs/style.css new file mode 100644 index 000000000..aabf9431d --- /dev/null +++ b/docs/style.css @@ -0,0 +1 @@ +@font-face{font-family:'Roboto';font-style:normal;font-weight:300;src:local("Roboto Light"),local("Roboto-Light"),url(https://fonts.gstatic.com/s/roboto/v18/KFOlCnqEu92Fr1MmSU5fBBc4.woff2) format("woff2");unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;font-display:swap}@font-face{font-family:'Roboto';font-style:italic;font-weight:300;src:local("Roboto Light Italic"),local("Roboto-LightItalic"),url(https://fonts.gstatic.com/s/roboto/v18/KFOjCnqEu92Fr1Mu51TjASc6CsQ.woff2) format("woff2");unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;font-display:swap}@font-face{font-family:'Roboto';font-style:normal;font-weight:500;src:local("Roboto Medium"),local("Roboto-Medium"),url(https://fonts.gstatic.com/s/roboto/v18/KFOlCnqEu92Fr1MmEU9fBBc4.woff2) format("woff2");unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;font-display:swap}@font-face{font-family:'Roboto Mono';font-style:normal;font-weight:300;src:local("Roboto Mono Light"),local("RobotoMono-Light"),url(https://fonts.gstatic.com/s/robotomono/v5/L0xkDF4xlVMF-BfR8bXMIjDgiWqxf78.woff2) format("woff2");unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;font-display:swap}@font-face{font-family:'Roboto Mono';font-style:italic;font-weight:300;src:local("Roboto Mono Light Italic"),local("RobotoMono-LightItalic"),url(https://fonts.gstatic.com/s/robotomono/v5/L0xmDF4xlVMF-BfR8bXMIjhOk9a0T72jBg.woff2) format("woff2");unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;font-display:swap}@font-face{font-family:'Roboto Mono';font-style:normal;font-weight:500;src:local("Roboto Mono Medium"),local("RobotoMono-Medium"),url(https://fonts.gstatic.com/s/robotomono/v5/L0xkDF4xlVMF-BfR8bXMIjC4iGqxf78.woff2) format("woff2");unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;font-display:swap}:root{--fore-color:#212121;--back-color:#fff;--border-color:#eee;--secondary-fore-color:#444;--tertiary-fore-color:#222;--secondary-back-color:#f0f0f0;--universal-margin:.5rem;--universal-padding:.5rem;--universal-border-radius:.125rem;--a-link-color:#0277bd;--a-visited-color:#01579b;--code-fore-color:#8e24aa;--code-back-color:#f0f0f0;--code-selected-color:#37474f;--pre-fore-color:#e57373;--pre-back-color:#263238;--token-color-a:#7f99a5;--token-color-b:#bdbdbd;--token-color-c:#64b5f6;--token-color-d:#ff8f00;--token-color-e:#c5e1a5;--token-color-f:#ce93d8;--token-color-g:#26c6da;--token-color-h:#e57373;--collapse-color:#607d8b;--copy-button-color:#1e88e5;--copy-button-hover-color:#2196f3;--scrolltop-button-color:#26a69a;--scrolltop-button-hover-color:#4db6ac;--beginner-color:#7cb342;--intermediate-color:#ffb300;--advanced-color:#e53935;--header-fore-color:#fff;--header-back-color:#202124;--nav-fore-color:#f0f0f0;--nav-back-color:#202124;--footer-fore-color:#616161;--footer-back-color:#e0e0e0;--nav-link-fore-color:#e0e0e0;--nav-link-border-color:#455a64;--nav-link-hover-color:#2b2c30;--search-fore-color:#fafafa;--search-back-color:#111;--search-border-color:#9e9e9e;--search-hover-border-color:#26a69a}html{font-size:16px;scroll-behavior:smooth}html,*{font-family:Roboto, Helvetica, sans-serif;line-height:1.5;-webkit-text-size-adjust:100%}*{font-size:1rem;font-weight:300}a,b,del,em,i,ins,q,span,strong,u{font-size:1em}body{margin:0;color:var(--fore-color);background:var(--back-color);overflow-x:hidden}details{display:block}summary{display:list-item}abbr[title]{border-bottom:none;text-decoration:underline dotted}input{overflow:visible}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}[type="search"]{-webkit-appearance:textfield;outline-offset:-2px}[type="search"]::-webkit-search-cancel-button,[type="search"]::-webkit-search-decoration{-webkit-appearance:none}img{max-width:100%;height:auto}h1,h2,h3,h4,h5,h6{line-height:1.2;margin:calc(1.5 * var(--universal-margin)) var(--universal-margin)}h1{font-size:6rem}h2{font-size:3.75rem}h3{font-size:3rem}h4{font-size:2.125rem}h5{font-size:1.5rem}h6{font-size:1.25rem}p{margin:var(--universal-margin)}ol,ul{margin:var(--universal-margin);padding-left:calc(2 * var(--universal-margin))}b,strong{font-weight:500}hr{box-sizing:content-box;border:0;line-height:1.25em;margin:var(--universal-margin);height:.0625rem;background:linear-gradient(to right, transparent, var(--border-color) 20%, var(--border-color) 80%, transparent)}code,kbd,pre{font-size:.875em}code,kbd,pre,code *,pre *,kbd *,code[class*="language-"],pre[class*="language-"]{font-family:Roboto Mono, Menlo, Consolas, monospace}sup,sub,code,kbd{line-height:0;position:relative;vertical-align:baseline}code{background:var(--code-back-color);color:var(--code-fore-color);padding:calc(var(--universal-padding) / 4) calc(var(--universal-padding) / 2);border-radius:var(--universal-border-radius)}pre{overflow:auto;background:var(--pre-back-color);color:var(--pre-fore-color);padding:calc(1.5 * var(--universal-padding));margin:var(--universal-margin);border:0}code[class*="language-"],pre[class*="language-"]{color:var(--pre-fore-color);text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.8;-moz-tab-size:2;-o-tab-size:2;tab-size:2;-webkit-hypens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*="language-"]{padding:calc(2 * var(--universal-padding));overflow:auto;margin:var(--universal-margin) 0}pre[class*="language-"]::-moz-selection,pre[class*="language-"] ::-moz-selection,code[class*="language-"]::-moz-selection,code[class*="language-"] ::-moz-selection{background:var(--code-selected-color)}pre[class*="language-"]::selection,pre[class*="language-"] ::selection,code[class*="language-"]::selection,code[class*="language-"] ::selection{background:var(--code-selected-color)}:not(pre)>code[class*="language-"]{padding:.1em;border-radius:.3em;white-space:normal}.namespace{opacity:.7}.token.comment,.token.prolog,.token.doctype,.token.cdata{color:var(--token-color-a)}.token.punctuation{color:var(--token-color-b)}.token.property,.token.tag,.token.boolean,.token.constant,.token.symbol,.token.deleted,.token.function{color:var(--token-color-c)}.token.number,.token.class-name{color:var(--token-color-d)}.token.selector,.token.attr-name,.token.string,.token.char,.token.builtin,.token.inserted{color:var(--token-color-e)}.token.operator,.token.entity,.token.url,.token.atrule,.token.attr-value,.token.keyword,.token.interpolation-punctuation{color:var(--token-color-f)}.token.regex{color:var(--token-color-g)}.token.important,.token.variable{color:var(--token-color-h)}.token.italic,.token.comment{font-style:italic}.token.important,.token.bold{font-weight:500}.token.entity{cursor:help}.language-css .token.string,.style .token.string{color:var(--token-color-f)}a{text-decoration:none}a:link{color:var(--a-link-color)}a:visited{color:var(--a-visited-color)}a:hover,a:focus{text-decoration:underline}.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}}.container{display:grid;grid-template-columns:repeat(12, 1fr);grid-column-gap:calc(0.5 * var(--universal-margin))}.container.card-container{position:absolute;padding-top:3.5rem;height:calc(100vh - 3.5rem)}.col-centered{grid-column:span 12;max-width:100%}@media screen and (min-width: 768px){.col-centered{grid-column:2/12}}@media screen and (min-width: 1280px){.col-centered{grid-column:3/11}}.col-quarter{grid-column:span 3}.col-full-width{grid-column:span 12}.flex-row{display:flex;flex:0 1 auto;flex-flow:row wrap}.flex-row .flex-item{flex:0 0 auto;max-width:50%;flex-basis:50%}@media screen and (min-width: 768px){.flex-row .flex-item{max-width:25%;flex-basis:25%}}@media screen and (min-width: 1280px){.flex-row .flex-item{max-width:100%;flex-grow:1;flex-basis:0}}h2.category-name{text-align:center}.card{overflow:hidden;position:relative;margin:var(--universal-margin);border-radius:calc(4 * var(--universal-border-radius));box-shadow:0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.2)}.card h4{text-align:center;padding-bottom:calc(0.75 * var(--universal-padding));margin-bottom:calc(2 * var(--universal-margin));border-bottom:.0625rem solid var(--border-color)}.card.code-card{margin-top:calc(5 * var(--universal-margin));background:var(--pre-back-color)}.card.code-card .section.card-content{background:var(--back-color);padding:calc(1.5 * var(--universal-padding))}.card.code-card .collapse{display:block;font-size:0.75rem;font-family:Roboto Mono, Menlo, Consolas, monospace;text-transform:uppercase;background:var(--pre-back-color);color:var(--collapse-color);padding:calc(1.5 * var(--universal-padding)) calc(1.5 * var(--universal-padding)) calc(2 * var(--universal-padding)) calc(2.25 * var(--universal-padding));cursor:pointer;background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23607D8B' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-plus-square'%3E%3Crect x='3' y='3' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='12' y1='8' x2='12' y2='16'%3E%3C/line%3E%3Cline x1='8' y1='12' x2='16' y2='12'%3E%3C/line%3E%3C/svg%3E");background-position:0.25rem 0.9375rem;background-repeat:no-repeat}.card.code-card .collapse+pre.card-examples{position:absolute;transform:scaleY(0);transform-origin:top;transition:transform 0.3s ease}.card.code-card .collapse.toggled{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23607D8B' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-minus-square'%3E%3Crect x='3' y='3' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='8' y1='12' x2='16' y2='12'%3E%3C/line%3E%3C/svg%3E");padding-bottom:calc(0.125 * var(--universal-padding))}.card.code-card .collapse.toggled+pre.card-examples{position:relative;transform:scaleY(1)}.card.code-card pre.section.card-code{position:relative;margin-bottom:0;padding-bottom:0}.card.code-card pre.section.card-examples{margin-top:0;margin-bottom:0;border-radius:0 0 calc(4 * var(--universal-border-radius)) calc(4 * var(--universal-border-radius));padding-top:0}.card.code-card pre.section.card-examples:before{content:'';display:block;position:absolute;top:0;left:0.5625rem;border-left:.0625rem solid var(--collapse-color);height:calc(100% - 18px)}.card.code-card .copy-button-container{position:relative;z-index:2}.card.code-card .copy-button-container .copy-button{background:var(--copy-button-color);box-sizing:border-box;position:absolute;top:-1.75rem;right:0;margin:calc(2 * var(--universal-margin));padding:calc(2.5 * var(--universal-padding));border-radius:50%;border:0;box-shadow:0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.2);transition:all 0.3s ease;cursor:pointer;background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-clipboard'%3E%3Cpath d='M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2'%3E%3C/path%3E%3Crect x='8' y='2' width='8' height='4' rx='1' ry='1'%3E%3C/rect%3E%3C/svg%3E");background-position:center center;background-repeat:no-repeat}.card.code-card .copy-button-container .copy-button:hover,.card.code-card .copy-button-container .copy-button:focus{background-color:var(--copy-button-hover-color);box-shadow:0 3px 3px 0 rgba(0,0,0,0.14),0 1px 7px 0 rgba(0,0,0,0.12),0 3px 1px -1px rgba(0,0,0,0.2)}.card.code-card .copy-button-container .copy-button:before{background:var(--back-color);position:absolute;top:-0.25rem;right:-0.25rem;content:'';display:block;box-sizing:border-box;padding:calc(2.5 * var(--universal-padding));border-radius:50%;border:0.25rem solid var(--back-color);z-index:-1}.card.code-card .corner{box-sizing:border-box;position:absolute;top:-0.5rem;right:-2.125rem;width:6.5rem;height:3.25rem;padding-top:2rem;transform:rotate(45deg);text-align:center;font-size:0.75rem;font-weight:500;color:var(--back-color);box-shadow:0 2px 2px 0 rgba(0,0,0,0.07),0 3px 1px -2px rgba(0,0,0,0.06),0 1px 5px 0 rgba(0,0,0,0.1)}.card.code-card .corner.beginner{background:var(--beginner-color)}.card.code-card .corner.intermediate{background:var(--intermediate-color)}.card.code-card .corner.advanced{background:var(--advanced-color)}.toast{position:fixed;bottom:calc(var(--universal-margin) * 2);margin-bottom:0;font-size:0.8125rem;left:50%;transform:translate(-50%, -50%);z-index:1111;color:var(--back-color);background:var(--fore-color);border-radius:calc(var(--universal-border-radius) * 16);padding:var(--universal-padding) calc(var(--universal-padding) * 2);box-shadow:0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.2);transition:all 0.3s ease}header{box-sizing:border-box;overflow:hidden;height:3.5rem;position:fixed;width:110%;top:0;left:-5%;box-shadow:0 2px 4px rgba(0,0,0,0.5);z-index:5;background:var(--header-back-color);transition:top 0.3s ease}header h1.logo{position:relative;top:0;margin-top:0;font-size:1.625rem;text-align:center}header h1 a,header h1 a:link,header h1 a:visited{color:var(--header-fore-color)}header h1 a:hover,header h1 a:focus,header h1 a:link:hover,header h1 a:link:focus,header h1 a:visited:hover,header h1 a:visited:focus{text-decoration:none}header h1 small{display:block;font-size:0.875rem;color:var(--header-back-color);margin-top:0.75rem}header img{height:3.5rem;padding:0.375rem;box-sizing:border-box}header #title{position:relative;top:-1.125rem}@media screen and (max-width: 768px){header #title{display:none}}nav{position:fixed;top:3.5rem;left:-320px;width:320px;transition:left 0.3s ease;z-index:1100;height:calc(100vh - 3.5rem);box-sizing:border-box;display:block;background:var(--nav-back-color);border:0;overflow-y:auto}@media screen and (max-width: 320px){nav{width:100%}}@media screen and (min-width: 768px){nav{width:33vw;left:-33vw}}@media screen and (min-width: 1280px){nav{width:25vw;left:-25vw}}nav.col-nav{box-shadow:0 8px 17px 2px rgba(0,0,0,0.14),0 3px 14px 2px rgba(0,0,0,0.12),0 5px 5px -3px rgba(0,0,0,0.2);left:0}@media screen and (min-width: 768px){nav.col-nav+main.col-centered,nav.col-nav+main.col-centered+footer.col-full-width{grid-column:5/13}}@media screen and (min-width: 1280px){nav.col-nav+main.col-centered{grid-column:4/12;padding-left:8vw}nav.col-nav+main.col-centered+footer.col-full-width{grid-column:4/13}}nav h4{margin:var(--universal-margin);padding:var(--universal-padding) calc(1.5 * var(--universal-padding));padding-left:0;color:var(--nav-fore-color)}nav a{display:block;margin:calc(0.5 * var(--universal-margin));margin-left:var(--universal-margin);margin-bottom:0;padding:calc(2 * var(--universal-padding)) calc(1.5 * var(--universal-padding));border-left:.0625rem solid var(--nav-link-border-color)}nav a:hover{text-decoration:none;background:var(--nav-link-hover-color)}nav a+a{margin-top:0}nav a:link,nav a:visited{color:var(--nav-link-fore-color)}[type="search"]{color:var(--search-fore-color);background:var(--search-back-color);outline:none;box-sizing:border-box;border:none;border-bottom:.0625rem solid var(--search-border-color);width:100%;margin-bottom:var(--universal-margin);padding:calc(2 * var(--universal-padding)) calc(1.5 * var(--universal-padding)) var(--universal-padding) calc(1.5 * var(--universal-padding));transition:all 0.3s ease}[type="search"]:hover,[type="search"]:focus{border-bottom:.0625rem solid var(--search-hover-border-color)}[type="search"]:focus{box-shadow:0 .0625rem 0 0 var(--search-hover-border-color)}.menu-button{position:fixed;top:0;left:0;z-index:1000;box-sizing:border-box;height:3.5rem;width:3.5rem;border:0;background:transparent;background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23fafafa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-more-horizontal'%3E%3Ccircle cx='12' cy='12' r='1'%3E%3C/circle%3E%3Ccircle cx='19' cy='12' r='1'%3E%3C/circle%3E%3Ccircle cx='5' cy='12' r='1'%3E%3C/circle%3E%3C/svg%3E");background-repeat:no-repeat;background-position:0.875rem 0.875rem;cursor:pointer;transition:all 0.3s ease}.menu-button:hover{background-color:rgba(255,255,255,0.08)}.menu-button.toggled{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23fafafa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-more-vertical'%3E%3Ccircle cx='12' cy='12' r='1'%3E%3C/circle%3E%3Ccircle cx='12' cy='5' r='1'%3E%3C/circle%3E%3Ccircle cx='12' cy='19' r='1'%3E%3C/circle%3E%3C/svg%3E")}footer{color:var(--footer-fore-color);background:var(--footer-back-color);padding-top:calc(2 * var(--universal-padding));padding-bottom:calc(3 * var(--universal-padding));margin-top:calc(6 * var(--universal-margin))}footer *{font-size:0.875rem}footer a,footer a:link,footer a:visited{color:var(--fore-color)}.scroll-to-top{position:fixed;bottom:1rem;right:1.3125rem;box-sizing:border-box;z-index:1100;height:2.75rem;width:2.75rem;border:0;border-radius:100%;background:var(--scrolltop-button-color);background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-arrow-up'%3E%3Cline x1='12' y1='19' x2='12' y2='5'%3E%3C/line%3E%3Cpolyline points='5 12 12 5 19 12'%3E%3C/polyline%3E%3C/svg%3E");background-repeat:no-repeat;background-position:center center;cursor:pointer;box-shadow:0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.2);transition:all 0.3s ease}.scroll-to-top:hover,.scroll-to-top:focus{background-color:var(--scrolltop-button-hover-color);box-shadow:0 3px 3px 0 rgba(0,0,0,0.14),0 1px 7px 0 rgba(0,0,0,0.12),0 3px 1px -1px rgba(0,0,0,0.2)}.card.contributor>.section.button{font-size:1rem;font-weight:500;text-align:center;display:block;transition:all 0.3s ease}.card.contributor>.section.button:link,.card.contributor>.section.button:visited{color:var(--fore-color)}.card.contributor>.section.button:link:hover,.card.contributor>.section.button:visited:hover{color:var(--a-link-color);text-decoration:none} diff --git a/docs/type.html b/docs/type.html index 5bb220519..e7228d0b2 100644 --- a/docs/type.html +++ b/docs/type.html @@ -1,6 +1,6 @@ -Type - 30 seconds of codeType - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Type

getType

Returns the native type of a value.

Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null.

const getType = v =>
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Type

intermediate

getType

Returns the native type of a value.

Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null.

const getType = v =>
   v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
-
getType(new Set([1, 2, 3])); // 'set'
-

is

Checks if the provided value is of the specified type.

Ensure the value is not undefined or null using Array.includes(), and compare the constructor property on the value with type to check if the provided value is of the specified type.

const is = (type, val) => ![, null].includes(val) && val.constructor === type;
-
is(Array, [1]); // true
+
getType(new Set([1, 2, 3])); // 'set'
+
intermediate

is

Checks if the provided value is of the specified type.

Ensure the value is not undefined or null using Array.includes(), and compare the constructor property on the value with type to check if the provided value is of the specified type.

const is = (type, val) => ![, null].includes(val) && val.constructor === type;
+
is(Array, [1]); // true
 is(ArrayBuffer, new ArrayBuffer()); // true
 is(Map, new Map()); // true
 is(RegExp, /./g); // true
@@ -96,15 +90,15 @@
 is(Number, new Number(1)); // true
 is(Boolean, true); // true
 is(Boolean, new Boolean(true)); // true
-

isArrayLike

Checks if the provided argument is array-like (i.e. is iterable).

Check if the provided argument is not null and that its Symbol.iterator property is a function.

const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function';
-
isArrayLike(document.querySelectorAll('.className')); // true
+
intermediate

isArrayLike

Checks if the provided argument is array-like (i.e. is iterable).

Check if the provided argument is not null and that its Symbol.iterator property is a function.

const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function';
+
isArrayLike(document.querySelectorAll('.className')); // true
 isArrayLike('abc'); // true
 isArrayLike(null); // false
-

isBoolean

Checks if the given argument is a native boolean element.

Use typeof to check if a value is classified as a boolean primitive.

const isBoolean = val => typeof val === 'boolean';
-
isBoolean(null); // false
+
intermediate

isBoolean

Checks if the given argument is a native boolean element.

Use typeof to check if a value is classified as a boolean primitive.

const isBoolean = val => typeof val === 'boolean';
+
isBoolean(null); // false
 isBoolean(false); // true
-

isEmpty

Returns true if the a value is an empty object, collection, map or set, has no enumerable properties or is any type that is not considered a collection.

Check if the provided value is null or if its length is equal to 0.

const isEmpty = val => val == null || !(Object.keys(val) || val).length;
-
isEmpty(new Map()); // true
+
intermediate

isEmpty

Returns true if the a value is an empty object, collection, map or set, has no enumerable properties or is any type that is not considered a collection.

Check if the provided value is null or if its length is equal to 0.

const isEmpty = val => val == null || !(Object.keys(val) || val).length;
+
isEmpty(new Map()); // true
 isEmpty(new Set()); // true
 isEmpty([]); // true
 isEmpty({}); // true
@@ -114,57 +108,57 @@
 isEmpty('text'); // false
 isEmpty(123); // true - type is not considered a collection
 isEmpty(true); // true - type is not considered a collection
-

isFunction

Checks if the given argument is a function.

Use typeof to check if a value is classified as a function primitive.

const isFunction = val => typeof val === 'function';
-
isFunction('x'); // false
+
intermediate

isFunction

Checks if the given argument is a function.

Use typeof to check if a value is classified as a function primitive.

const isFunction = val => typeof val === 'function';
+
isFunction('x'); // false
 isFunction(x => x); // true
-

isNil

Returns true if the specified value is null or undefined, false otherwise.

Use the strict equality operator to check if the value and of val are equal to null or undefined.

const isNil = val => val === undefined || val === null;
-
isNil(null); // true
+
intermediate

isNil

Returns true if the specified value is null or undefined, false otherwise.

Use the strict equality operator to check if the value and of val are equal to null or undefined.

const isNil = val => val === undefined || val === null;
+
isNil(null); // true
 isNil(undefined); // true
-

isNull

Returns true if the specified value is null, false otherwise.

Use the strict equality operator to check if the value and of val are equal to null.

const isNull = val => val === null;
-
isNull(null); // true
-

isNumber

Checks if the given argument is a number.

Use typeof to check if a value is classified as a number primitive.

const isNumber = val => typeof val === 'number';
-
isNumber('1'); // false
+
intermediate

isNull

Returns true if the specified value is null, false otherwise.

Use the strict equality operator to check if the value and of val are equal to null.

const isNull = val => val === null;
+
isNull(null); // true
+
intermediate

isNumber

Checks if the given argument is a number.

Use typeof to check if a value is classified as a number primitive.

const isNumber = val => typeof val === 'number';
+
isNumber('1'); // false
 isNumber(1); // true
-

isObject

Returns a boolean determining if the passed value is an object or not.

Uses the Object constructor to create an object wrapper for the given value. If the value is null or undefined, create and return an empty object. Οtherwise, return an object of a type that corresponds to the given value.

const isObject = obj => obj === Object(obj);
-
isObject([1, 2, 3, 4]); // true
+
intermediate

isObject

Returns a boolean determining if the passed value is an object or not.

Uses the Object constructor to create an object wrapper for the given value. If the value is null or undefined, create and return an empty object. Οtherwise, return an object of a type that corresponds to the given value.

const isObject = obj => obj === Object(obj);
+
isObject([1, 2, 3, 4]); // true
 isObject([]); // true
 isObject(['Hello!']); // true
 isObject({ a: 1 }); // true
 isObject({}); // true
 isObject(true); // false
-

isObjectLike

Checks if a value is object-like.

Check if the provided value is not null and its typeof is equal to 'object'.

const isObjectLike = val => val !== null && typeof val === 'object';
-
isObjectLike({}); // true
+
intermediate

isObjectLike

Checks if a value is object-like.

Check if the provided value is not null and its typeof is equal to 'object'.

const isObjectLike = val => val !== null && typeof val === 'object';
+
isObjectLike({}); // true
 isObjectLike([1, 2, 3]); // true
 isObjectLike(x => x); // false
 isObjectLike(null); // false
-

isPlainObject

Checks if the provided value is an object created by the Object constructor.

Check if the provided value is truthy, use typeof to check if it is an object and Object.constructor to make sure the constructor is equal to Object.

const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;
-
isPlainObject({ a: 1 }); // true
+
intermediate

isPlainObject

Checks if the provided value is an object created by the Object constructor.

Check if the provided value is truthy, use typeof to check if it is an object and Object.constructor to make sure the constructor is equal to Object.

const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;
+
isPlainObject({ a: 1 }); // true
 isPlainObject(new Map()); // false
-

isPrimitive

Returns a boolean determining if the passed value is primitive or not.

Use Array.includes() on an array of type strings which are not primitive, supplying the type using typeof. Since typeof null evaluates to 'object', it needs to be directly compared.

const isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null;
-
isPrimitive(null); // true
+
intermediate

isPrimitive

Returns a boolean determining if the passed value is primitive or not.

Use Array.includes() on an array of type strings which are not primitive, supplying the type using typeof. Since typeof null evaluates to 'object', it needs to be directly compared.

const isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null;
+
isPrimitive(null); // true
 isPrimitive(50); // true
 isPrimitive('Hello!'); // true
 isPrimitive(false); // true
 isPrimitive(Symbol()); // true
 isPrimitive([]); // false
-

isPromiseLike

Returns true if an object looks like a Promise, false otherwise.

Check if the object is not null, its typeof matches either object or function and if it has a .then property, which is also a function.

const isPromiseLike = obj =>
+
intermediate

isPromiseLike

Returns true if an object looks like a Promise, false otherwise.

Check if the object is not null, its typeof matches either object or function and if it has a .then property, which is also a function.

const isPromiseLike = obj =>
   obj !== null &&
   (typeof obj === 'object' || typeof obj === 'function') &&
   typeof obj.then === 'function';
-
isPromiseLike({
+
isPromiseLike({
   then: function() {
     return '';
   }
 }); // true
 isPromiseLike(null); // false
 isPromiseLike({}); // false
-

isString

Checks if the given argument is a string.

Use typeof to check if a value is classified as a string primitive.

const isString = val => typeof val === 'string';
-
isString('10'); // true
-

isSymbol

Checks if the given argument is a symbol.

Use typeof to check if a value is classified as a symbol primitive.

const isSymbol = val => typeof val === 'symbol';
-
isSymbol(Symbol('x')); // true
-

isUndefined

Returns true if the specified value is undefined, false otherwise.

Use the strict equality operator to check if the value and of val are equal to undefined.

const isUndefined = val => val === undefined;
-
isUndefined(undefined); // true
-

isValidJSON

Checks if the provided argument is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided argument is a valid JSON.

const isValidJSON = obj => {
+
intermediate

isString

Checks if the given argument is a string.

Use typeof to check if a value is classified as a string primitive.

const isString = val => typeof val === 'string';
+
isString('10'); // true
+
intermediate

isSymbol

Checks if the given argument is a symbol.

Use typeof to check if a value is classified as a symbol primitive.

const isSymbol = val => typeof val === 'symbol';
+
isSymbol(Symbol('x')); // true
+
intermediate

isUndefined

Returns true if the specified value is undefined, false otherwise.

Use the strict equality operator to check if the value and of val are equal to undefined.

const isUndefined = val => val === undefined;
+
isUndefined(undefined); // true
+
intermediate

isValidJSON

Checks if the provided argument is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided argument is a valid JSON.

const isValidJSON = obj => {
   try {
     JSON.parse(obj);
     return true;
@@ -172,7 +166,7 @@
     return false;
   }
 };
-
isValidJSON('{"name":"Adam","age":20}'); // true
+
isValidJSON('{"name":"Adam","age":20}'); // true
 isValidJSON('{"name":"Adam",age:"20"}'); // false
 isValidJSON(null); // true
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/utility.html b/docs/utility.html index a01bd86ce..899e31e99 100644 --- a/docs/utility.html +++ b/docs/utility.html @@ -1,6 +1,6 @@ -Utility - 30 seconds of codeUtility - 30 seconds of code

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Utility

castArray

Casts the provided value as an array if it's not one.

Use Array.isArray() to determine if val is an array and return it as-is or encapsulated in an array accordingly.

const castArray = val => (Array.isArray(val) ? val : [val]);
-
castArray('foo'); // ['foo']
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Utility

intermediate

castArray

Casts the provided value as an array if it's not one.

Use Array.isArray() to determine if val is an array and return it as-is or encapsulated in an array accordingly.

const castArray = val => (Array.isArray(val) ? val : [val]);
+
castArray('foo'); // ['foo']
 castArray([1]); // [1]
-

cloneRegExp

Clones a regular expression.

Use new RegExp(), RegExp.source and RegExp.flags to clone the given regular expression.

const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
-
const regExp = /lorem ipsum/gi;
+
intermediate

cloneRegExp

Clones a regular expression.

Use new RegExp(), RegExp.source and RegExp.flags to clone the given regular expression.

const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
+
const regExp = /lorem ipsum/gi;
 const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi
-

coalesce

Returns the first non-null/undefined argument.

Use Array.find() to return the first non null/undefined argument.

const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
-
coalesce(null, undefined, '', NaN, 'Waldo'); // ""
-

coalesceFactory

Returns a customized coalesce function that returns the first argument that returns true from the provided argument validation function.

Use Array.find() to return the first argument that returns true from the provided argument validation function.

const coalesceFactory = valid => (...args) => args.find(valid);
-
const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));
+
intermediate

coalesce

Returns the first non-null/undefined argument.

Use Array.find() to return the first non null/undefined argument.

const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
+
coalesce(null, undefined, '', NaN, 'Waldo'); // ""
+
intermediate

coalesceFactory

Returns a customized coalesce function that returns the first argument that returns true from the provided argument validation function.

Use Array.find() to return the first argument that returns true from the provided argument validation function.

const coalesceFactory = valid => (...args) => args.find(valid);
+
const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));
 customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo"
-

extendHex

Extends a 3-digit color code to a 6-digit color code.

Use Array.map(), String.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.

const extendHex = shortHex =>
+
intermediate

extendHex

Extends a 3-digit color code to a 6-digit color code.

Use Array.map(), String.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.

const extendHex = shortHex =>
   '#' +
   shortHex
     .slice(shortHex.startsWith('#') ? 1 : 0)
     .split('')
     .map(x => x + x)
     .join('');
-
extendHex('#03f'); // '#0033ff'
+
extendHex('#03f'); // '#0033ff'
 extendHex('05a'); // '#0055aa'
-

getURLParameters

Returns an object containing the parameters of the current URL.

Use String.match() with an appropriate regular expression to get all key-value pairs, Array.reduce() to map and combine them into a single object. Pass location.search as the argument to apply to the current url.

const getURLParameters = url =>
+
intermediate

getURLParameters

Returns an object containing the parameters of the current URL.

Use String.match() with an appropriate regular expression to get all key-value pairs, Array.reduce() to map and combine them into a single object. Pass location.search as the argument to apply to the current url.

const getURLParameters = url =>
   (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
     (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
     {}
   );
-
getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
+
getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
 getURLParameters('google.com'); // {}
-

hexToRGBadvanced

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 an alpha value is provided alongside 6-digit hex, give rgba() string in return.

const hexToRGB = hex => {
+
advanced

hexToRGB

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 an alpha value is provided alongside 6-digit hex, give rgba() string in return.

const hexToRGB = hex => {
   let alpha = false,
     h = hex.slice(hex.startsWith('#') ? 1 : 0);
   if (h.length === 3) h = [...h].map(x => x + x).join('');
@@ -125,17 +119,17 @@
     ')'
   );
 };
-
hexToRGB('#27ae60ff'); // 'rgba(39, 174, 96, 255)'
+
hexToRGB('#27ae60ff'); // 'rgba(39, 174, 96, 255)'
 hexToRGB('27ae60'); // 'rgb(39, 174, 96)'
 hexToRGB('#fff'); // 'rgb(255, 255, 255)'
-

httpGet

Makes a GET request to the passed URL.

Use XMLHttpRequest web api to make a get request to the given url. Handle the onload event, by calling the given callback the responseText. Handle the onerror event, by running the provided err function. Omit the third argument, err, to log errors to the console's error stream by default.

const httpGet = (url, callback, err = console.error) => {
+
intermediate

httpGet

Makes a GET request to the passed URL.

Use XMLHttpRequest web api to make a get request to the given url. Handle the onload event, by calling the given callback the responseText. Handle the onerror event, by running the provided err function. Omit the third argument, err, to log errors to the console's error stream by default.

const httpGet = (url, callback, err = console.error) => {
   const request = new XMLHttpRequest();
   request.open('GET', url, true);
   request.onload = () => callback(request.responseText);
   request.onerror = () => err(request);
   request.send();
 };
-
httpGet(
+
httpGet(
   'https://jsonplaceholder.typicode.com/posts/1',
   console.log
 ); /* 
@@ -146,7 +140,7 @@ Logs: {
   "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
 }
 */
-

httpPost

Makes a POST request to the passed URL.

Use XMLHttpRequest web api to make a post request to the given url. Set the value of an HTTP request header with setRequestHeader method. Handle the onload event, by calling the given callback the responseText. Handle the onerror event, by running the provided err function. Omit the third argument, data, to send no data to the provided url. Omit the fourth argument, err, to log errors to the console's error stream by default.

const httpPost = (url, data, callback, err = console.error) => {
+
intermediate

httpPost

Makes a POST request to the passed URL.

Use XMLHttpRequest web api to make a post request to the given url. Set the value of an HTTP request header with setRequestHeader method. Handle the onload event, by calling the given callback the responseText. Handle the onerror event, by running the provided err function. Omit the third argument, data, to send no data to the provided url. Omit the fourth argument, err, to log errors to the console's error stream by default.

const httpPost = (url, data, callback, err = console.error) => {
   const request = new XMLHttpRequest();
   request.open('POST', url, true);
   request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
@@ -154,7 +148,7 @@ Logs: {
   request.onerror = () => err(request);
   request.send(data);
 };
-
const newPost = {
+
const newPost = {
   userId: 1,
   id: 1337,
   title: 'Foo',
@@ -182,10 +176,10 @@ Logs: {
   "id": 101
 }
 */
-

isBrowser

Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.

Use Array.includes() on the typeof values of both window and document (globals usually only available in a browser environment unless they were explicitly defined), which will return true if one of them is undefined. typeof allows globals to be checked for existence without throwing a ReferenceError. If both of them are not undefined, then the current environment is assumed to be a browser.

const isBrowser = () => ![typeof window, typeof document].includes('undefined');
-
isBrowser(); // true (browser)
+
intermediate

isBrowser

Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.

Use Array.includes() on the typeof values of both window and document (globals usually only available in a browser environment unless they were explicitly defined), which will return true if one of them is undefined. typeof allows globals to be checked for existence without throwing a ReferenceError. If both of them are not undefined, then the current environment is assumed to be a browser.

const isBrowser = () => ![typeof window, typeof document].includes('undefined');
+
isBrowser(); // true (browser)
 isBrowser(); // false (Node)
-

mostPerformant

Returns the index of the function in an array of functions which executed the fastest.

Use Array.map() to generate an array where each value is the total time taken to execute the function after iterations times. Use the difference in performance.now() values before and after to get the total time in milliseconds to a high degree of accuracy. Use Math.min() to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function. Omit the second argument, iterations, to use a default of 10,000 iterations. The more iterations, the more reliable the result but the longer it will take.

const mostPerformant = (fns, iterations = 10000) => {
+
intermediate

mostPerformant

Returns the index of the function in an array of functions which executed the fastest.

Use Array.map() to generate an array where each value is the total time taken to execute the function after iterations times. Use the difference in performance.now() values before and after to get the total time in milliseconds to a high degree of accuracy. Use Math.min() to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function. Omit the second argument, iterations, to use a default of 10,000 iterations. The more iterations, the more reliable the result but the longer it will take.

const mostPerformant = (fns, iterations = 10000) => {
   const times = fns.map(fn => {
     const before = performance.now();
     for (let i = 0; i < iterations; i++) fn();
@@ -193,7 +187,7 @@ Logs: {
   });
   return times.indexOf(Math.min(...times));
 };
-
mostPerformant([
+
mostPerformant([
   () => {
     // Loops through the entire array before returning `false`
     [1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number');
@@ -203,13 +197,13 @@ Logs: {
     [1, '2', 3, 4, 5, 6, 7, 8, 9, 10].every(el => typeof el === 'number');
   }
 ]); // 1
-

nthArg

Creates a function that gets the argument at index n. If n is negative, the nth argument from the end is returned.

Use Array.slice() to get the desired argument at index n.

const nthArg = n => (...args) => args.slice(n)[0];
-
const third = nthArg(2);
+
intermediate

nthArg

Creates a function that gets the argument at index n. If n is negative, the nth argument from the end is returned.

Use Array.slice() to get the desired argument at index n.

const nthArg = n => (...args) => args.slice(n)[0];
+
const third = nthArg(2);
 third(1, 2, 3); // 3
 third(1, 2); // undefined
 const last = nthArg(-1);
 last(1, 2, 3, 4, 5); // 5
-

parseCookie

Parse an HTTP Cookie header string and return an object of all cookie name-value pairs.

Use String.split(';') to separate key-value pairs from each other. Use Array.map() and String.split('=') to separate keys from values in each pair. Use Array.reduce() and decodeURIComponent() to create an object with all key-value pairs.

const parseCookie = str =>
+
intermediate

parseCookie

Parse an HTTP Cookie header string and return an object of all cookie name-value pairs.

Use String.split(';') to separate key-value pairs from each other. Use Array.map() and String.split('=') to separate keys from values in each pair. Use Array.reduce() and decodeURIComponent() to create an object with all key-value pairs.

const parseCookie = str =>
   str
     .split(';')
     .map(v => v.split('='))
@@ -217,43 +211,43 @@ Logs: {
       acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
       return acc;
     }, {});
-
parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' }
-

prettyBytes

Converts a number in bytes to a human-readable string.

Use an array dictionary of units to be accessed based on the exponent. Use Number.toPrecision() to truncate the number to a certain number of digits. Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not. Omit the second argument, precision, to use a default precision of 3 digits. Omit the third argument, addSpace, to add space between the number and unit by default.

const prettyBytes = (num, precision = 3, addSpace = true) => {
+
parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' }
+
intermediate

prettyBytes

Converts a number in bytes to a human-readable string.

Use an array dictionary of units to be accessed based on the exponent. Use Number.toPrecision() to truncate the number to a certain number of digits. Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not. Omit the second argument, precision, to use a default precision of 3 digits. Omit the third argument, addSpace, to add space between the number and unit by default.

const prettyBytes = (num, precision = 3, addSpace = true) => {
   const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
   if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
   const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);
   const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));
   return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
 };
-
prettyBytes(1000); // "1 KB"
+
prettyBytes(1000); // "1 KB"
 prettyBytes(-27145424323.5821, 5); // "-27.145 GB"
 prettyBytes(123456789, 3, false); // "123MB"
-

randomHexColorCode

Generates a random hexadecimal color code.

Use Math.random to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using toString(16).

const randomHexColorCode = () => {
+
intermediate

randomHexColorCode

Generates a random hexadecimal color code.

Use Math.random to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using toString(16).

const randomHexColorCode = () => {
   let n = (Math.random() * 0xfffff * 1000000).toString(16);
   return '#' + n.slice(0, 6);
 };
-
randomHexColorCode(); // "#e34155"
-

RGBToHex

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 String.padStart(6,'0') to get a 6-digit hexadecimal value.

const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
-
RGBToHex(255, 165, 1); // 'ffa501'
-

serializeCookie

Serialize a cookie name-value pair into a Set-Cookie header string.

Use template literals and encodeURIComponent() to create the appropriate string.

const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
-
serializeCookie('foo', 'bar'); // 'foo=bar'
-

timeTaken

Measures the time taken by a function to execute.

Use console.time() and console.timeEnd() to measure the difference between the start and end times to determine how long the callback took to execute.

const timeTaken = callback => {
+
randomHexColorCode(); // "#e34155"
+
intermediate

RGBToHex

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 String.padStart(6,'0') to get a 6-digit hexadecimal value.

const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
+
RGBToHex(255, 165, 1); // 'ffa501'
+
intermediate

serializeCookie

Serialize a cookie name-value pair into a Set-Cookie header string.

Use template literals and encodeURIComponent() to create the appropriate string.

const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
+
serializeCookie('foo', 'bar'); // 'foo=bar'
+
intermediate

timeTaken

Measures the time taken by a function to execute.

Use console.time() and console.timeEnd() to measure the difference between the start and end times to determine how long the callback took to execute.

const timeTaken = callback => {
   console.time('timeTaken');
   const r = callback();
   console.timeEnd('timeTaken');
   return r;
 };
-
timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
-

toCurrency

Take a number and return specified currency formatting.

Use Intl.NumberFormat to enable country / currency sensitive formatting.

const toCurrency = (n, curr, LanguageFormat = undefined) =>
+
timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
+
intermediate

toCurrency

Take a number and return specified currency formatting.

Use Intl.NumberFormat to enable country / currency sensitive formatting.

const toCurrency = (n, curr, LanguageFormat = undefined) =>
   Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
-
toCurrency(123456.789, 'EUR'); // €123,456.79  | currency: Euro | currencyLangFormat: Local
+
toCurrency(123456.789, 'EUR'); // €123,456.79  | currency: Euro | currencyLangFormat: Local
 toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79  | currency: US Dollar | currencyLangFormat: English (United States)
 toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | currencyLangFormat: Farsi
 toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local
 toCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish
-

toDecimalMark

Use toLocaleString() to convert a float-point arithmetic to the Decimal mark form. It makes a comma separated string from a number.

const toDecimalMark = num => num.toLocaleString('en-US');
-
toDecimalMark(12305030388.9087); // "12,305,030,388.909"
-

toOrdinalSuffix

Adds an ordinal suffix to a number.

Use the modulo operator (%) to find values of single and tens digits. Find which ordinal pattern digits match. If digit is found in teens pattern, use teens ordinal.

const toOrdinalSuffix = num => {
+
intermediate

toDecimalMark

Use toLocaleString() to convert a float-point arithmetic to the Decimal mark form. It makes a comma separated string from a number.

const toDecimalMark = num => num.toLocaleString('en-US');
+
toDecimalMark(12305030388.9087); // "12,305,030,388.909"
+
intermediate

toOrdinalSuffix

Adds an ordinal suffix to a number.

Use the modulo operator (%) to find values of single and tens digits. Find which ordinal pattern digits match. If digit is found in teens pattern, use teens ordinal.

const toOrdinalSuffix = num => {
   const int = parseInt(num),
     digits = [int % 10, int % 100],
     ordinals = ['st', 'nd', 'rd', 'th'],
@@ -263,13 +257,13 @@ Logs: {
     ? int + ordinals[digits[0] - 1]
     : int + ordinals[3];
 };
-
toOrdinalSuffix('123'); // "123rd"
-

validateNumber

Returns true if the given value is a number, false otherwise.

Use !isNaN() in combination with parseFloat() to check if the argument is a number. Use isFinite() to check if the number is finite. Use Number() to check if the coercion holds.

const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
-
validateNumber('10'); // true
-

yesNo

Returns true if the string is y/yes or false if the string is n/no.

Use RegExp.test() to check if the string evaluates to y/yes or n/no. Omit the second argument, def to set the default answer as no.

const yesNo = (val, def = false) =>
+
toOrdinalSuffix('123'); // "123rd"
+
intermediate

validateNumber

Returns true if the given value is a number, false otherwise.

Use !isNaN() in combination with parseFloat() to check if the argument is a number. Use isFinite() to check if the number is finite. Use Number() to check if the coercion holds.

const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
+
validateNumber('10'); // true
+
intermediate

yesNo

Returns true if the string is y/yes or false if the string is n/no.

Use RegExp.test() to check if the string evaluates to y/yes or n/no. Omit the second argument, def to set the default answer as no.

const yesNo = (val, def = false) =>
   /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;
-
yesNo('Y'); // true
+
yesNo('Y'); // true
 yesNo('yes'); // true
 yesNo('No'); // false
 yesNo('Foo', true); // true
-
\ No newline at end of file + \ No newline at end of file diff --git a/scripts/web.js b/scripts/web.js index 35540fe0a..67bac1f57 100644 --- a/scripts/web.js +++ b/scripts/web.js @@ -34,28 +34,29 @@ if ( ); process.exit(0); } -// Compile the mini.css framework and custom CSS styles, using `node-sass`. +// Compile the SCSS file, using `node-sass`. const sass = require('node-sass'); sass.render( { - file: path.join('docs', 'mini', 'flavor.scss'), - outFile: path.join('docs', 'mini.css'), + file: path.join('docs', 'scss', 'style.scss'), + outFile: path.join('docs', 'style.css'), outputStyle: 'compressed' }, function(err, result) { if (!err) { - fs.writeFile(path.join('docs', 'mini.css'), result.css, function(err2) { - if (!err2) console.log(`${chalk.green('SUCCESS!')} mini.css file generated!`); - else console.log(`${chalk.red('ERROR!')} During mini.css file generation: ${err}`); + fs.writeFile(path.join('docs', 'style.css'), result.css, function(err2) { + if (!err2) console.log(`${chalk.green('SUCCESS!')} style.css file generated!`); + else console.log(`${chalk.red('ERROR!')} During style.css file generation: ${err}`); }); } else { - console.log(`${chalk.red('ERROR!')} During mini.css file generation: ${err}`); + console.log(`${chalk.red('ERROR!')} During style.css file generation: ${err}`); } } ); // Set variables for paths const snippetsPath = './snippets', archivedSnippetsPath = './snippets_archive', + glossarySnippetsPath = './glossary', staticPartsPath = './static-parts', docsPath = './docs'; // Set variables for script @@ -97,6 +98,9 @@ let snippets = {}, archivedStartPart = '', archivedEndPart = '', archivedOutput = '', + glossaryStartPart = '', + glossaryEndPart = '', + glossaryOutput = '', indexStaticFile = '', pagesOutput = [], tagDbData = {}; @@ -105,6 +109,7 @@ console.time('Webber'); // Synchronously read all snippets and sort them as necessary (case-insensitive) snippets = util.readSnippets(snippetsPath); archivedSnippets = util.readSnippets(archivedSnippetsPath); +glossarySnippets = util.readSnippets(glossarySnippetsPath); // Load static parts for all pages try { @@ -123,7 +128,11 @@ try { ); archivedEndPart = fs.readFileSync(path.join(staticPartsPath, 'archived-page-end.html'), 'utf8'); - indexStaticFile = fs.readFileSync(path.join(staticPartsPath, 'index.html'), 'utf8'); + glossaryStartPart = fs.readFileSync( + path.join(staticPartsPath, 'glossary-page-start.html'), + 'utf8' + ); + glossaryEndPart = fs.readFileSync(path.join(staticPartsPath, 'glossary-page-end.html'), 'utf8'); } catch (err) { // Handle errors (hopefully not!) console.log(`${chalk.red('ERROR!')} During static part loading: ${err}`); @@ -131,148 +140,6 @@ try { } // Load tag data from the database tagDbData = util.readTags(); -// Create the output for the index.html file (only locally or on Travis CRON or custom job) -if ( - !util.isTravisCI() || - (util.isTravisCI() && - (process.env['TRAVIS_EVENT_TYPE'] === 'cron' || process.env['TRAVIS_EVENT_TYPE'] === 'api')) -) { - try { - // Shuffle the array of snippets, pick 3 - let indexDailyPicks = ''; - let shuffledSnippets = util.shuffle(Object.keys(snippets)).slice(0, 3); - const dailyPicks = Object.keys(snippets) - .filter(key => shuffledSnippets.includes(key)) - .reduce((obj, key) => { - obj[key] = snippets[key]; - return obj; - }, {}); - - // Generate the html for the picked snippets - for (let snippet of Object.entries(dailyPicks)) - indexDailyPicks += - '
' + - md - .render(`\n${snippets[snippet[0]]}`) - .replace(/

/g, - `${snippet[1].includes('advanced') ? 'advanced' : ''}

` - ) - .replace(/<\/h3>/g, '
') - .replace( - /
([^\0]*?)<\/code><\/pre>/gm,
-            (match, p1) =>
-              `
${Prism.highlight(
-                unescapeHTML(p1),
-                Prism.languages.javascript
-              )}
` - ) - .replace(/<\/pre>\s+
📋 Copy to clipboard' +
-        '
'; - // Select the first snippet from today's picks - indexDailyPicks = indexDailyPicks.replace('card fluid pick', 'card fluid pick selected'); - // Optimize punctuation nodes - indexDailyPicks = util.optimizeNodes( - indexDailyPicks, - /([^\0<]*?)<\/span>([\n\r\s]*)([^\0]*?)<\/span>/gm, - (match, p1, p2, p3) => `${p1}${p2}${p3}` - ); - // Optimize operator nodes - indexDailyPicks = util.optimizeNodes( - indexDailyPicks, - /([^\0<]*?)<\/span>([\n\r\s]*)([^\0]*?)<\/span>/gm, - (match, p1, p2, p3) => `${p1}${p2}${p3}` - ); - // Optimize keyword nodes - indexDailyPicks = util.optimizeNodes( - indexDailyPicks, - /([^\0<]*?)<\/span>([\n\r\s]*)([^\0]*?)<\/span>/gm, - (match, p1, p2, p3) => `${p1}${p2}${p3}` - ); - // Put the daily picks into the page - indexStaticFile = indexStaticFile.replace('$daily-picks', indexDailyPicks); - // Use the Github API to get the needed data - const githubApi = 'api.github.com'; - const headers = util.isTravisCI() - ? { 'User-Agent': '30-seconds-of-code', Authorization: 'token ' + process.env['GH_TOKEN'] } - : { 'User-Agent': '30-seconds-of-code' }; - // Test the API's rate limit (keep for various reasons) - https.get({ host: githubApi, path: '/rate_limit?', headers: headers }, res => { - res.on('data', function(chunk) { - console.log(`Remaining requests: ${JSON.parse(chunk).resources.core.remaining}`); - }); - }); - // Send requests and wait for responses, write to the page - https.get( - { - host: githubApi, - path: '/repos/chalarangelo/30-seconds-of-code/commits?per_page=1', - headers: headers - }, - resCommits => { - https.get( - { - host: githubApi, - path: '/repos/chalarangelo/30-seconds-of-code/contributors?per_page=1', - headers: headers - }, - resContributors => { - https.get( - { - host: githubApi, - path: '/repos/chalarangelo/30-seconds-of-code/stargazers?per_page=1', - headers: headers - }, - resStars => { - let commits = resCommits.headers.link - .split('&') - .slice(-1)[0] - .replace(/[^\d]/g, ''), - contribs = resContributors.headers.link - .split('&') - .slice(-1)[0] - .replace(/[^\d]/g, ''), - stars = resStars.headers.link - .split('&') - .slice(-1)[0] - .replace(/[^\d]/g, ''); - indexStaticFile = indexStaticFile - .replace(/\$snippet-count/g, Object.keys(snippets).length) - .replace(/\$commit-count/g, commits) - .replace(/\$contrib-count/g, contribs) - .replace(/\$star-count/g, stars); - indexStaticFile = minify(indexStaticFile, { - collapseBooleanAttributes: true, - collapseWhitespace: true, - decodeEntities: false, - minifyCSS: true, - minifyJS: true, - keepClosingSlash: true, - processConditionalComments: true, - removeAttributeQuotes: false, - removeComments: true, - removeEmptyAttributes: false, - removeOptionalTags: false, - removeScriptTypeAttributes: false, - removeStyleLinkTypeAttributes: false, - trimCustomFragments: true - }); - // Generate 'index.html' file - fs.writeFileSync(path.join(docsPath, 'index.html'), indexStaticFile); - console.log(`${chalk.green('SUCCESS!')} index.html file generated!`); - } - ); - } - ); - } - ); - } catch (err) { - console.log(`${chalk.red('ERROR!')} During index.html generation: ${err}`); - process.exit(1); - } -} // Create the output for individual category pages try { @@ -290,23 +157,24 @@ try { : a.localeCompare(b) )) { output += - '

' + + '

' + md .render(`${util.capitalize(tag, true)}\n`) .replace(/

/g, '') .replace(/<\/p>/g, '') + - '

'; + ''; for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag)) output += md - .render(`[${taggedSnippet[0]}](./${tag}#${taggedSnippet[0].toLowerCase()})\n`) + .render(`[${taggedSnippet[0]}](./${tag == 'array' ?'index' : tag}#${taggedSnippet[0].toLowerCase()})\n`) .replace(/

/g, '') .replace(/<\/p>/g, '') - .replace(/

'; - output += ' '; + '
'; + output += '

'; // Loop over tags and snippets to create the list of snippets for (let tag of [...new Set(Object.entries(tagDbData).map(t => t[1][0]))] .filter(v => v) @@ -321,25 +189,28 @@ try { let localOutput = output .replace(/\$tag/g, util.capitalize(tag)) .replace(new RegExp(`./${tag}#`, 'g'), '#'); + if (tag === 'array') localOutput = localOutput.replace(new RegExp(`./index#`, 'g'), '#'); localOutput += md .render(`## ${util.capitalize(tag, true)}\n`) - .replace(/

/g, '

'); + .replace(/

/g, '

'); for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag)) localOutput += - '
' + + '
' + + `
${taggedSnippet[1].includes('advanced') ? 'advanced' : taggedSnippet[1].includes('beginner') ? 'beginner' : 'intermediate'}
` + md .render(`\n${snippets[taggedSnippet[0] + '.md']}`) .replace( /

/g, - `${ - taggedSnippet[1].includes('advanced') ? 'advanced' : '' - }

` + '

' + ) + .replace( + /
/m,
+            '
'
           )
-          .replace(/<\/h3>/g, '
') .replace( /
([^\0]*?)<\/code><\/pre>/gm,
             (match, p1) =>
@@ -348,9 +219,9 @@ try {
                 Prism.languages.javascript
               )}
` ) - .replace(/<\/pre>\s+
📋 Copy to clipboard' +
-        '
'; + .replace(/<\/div>\s*
\s+
examples
' +
-      '
' + - '
' + + '
' + md - .render(`\n${filteredArchivedSnippets[snippet[0]]}`) - .replace(/

/g, '

') + .render(`\n${filteredArchivedSnippets[snippet[0]]}`) + .replace( + /

/g, + '

' + ) + .replace( + /
/m,
+          '
'
+        )
         .replace(
           /
([^\0]*?)<\/code><\/pre>/gm,
           (match, p1) =>
@@ -516,9 +397,9 @@ try {
               Prism.languages.javascript
             )}
` ) - .replace(/<\/pre>\s+
📋 Copy to clipboard' +
-      '
'; + .replace(/<\/div>\s*
\s+
examples
' + + md + .render(`\n${filteredGlossarySnippets[snippet[0]]}`) + .replace( + /

/g, + '

' + ) + + '
'; + + glossaryOutput += `${glossaryEndPart}`; + + // Generate and minify 'glossary.html' file + const minifiedGlossaryOutput = minify(glossaryOutput, { + collapseBooleanAttributes: true, + collapseWhitespace: true, + decodeEntities: false, + minifyCSS: true, + minifyJS: true, + keepClosingSlash: true, + processConditionalComments: true, + removeAttributeQuotes: false, + removeComments: true, + removeEmptyAttributes: false, + removeOptionalTags: false, + removeScriptTypeAttributes: false, + removeStyleLinkTypeAttributes: false, + trimCustomFragments: true + }); + + fs.writeFileSync(path.join(docsPath, 'glossary.html'), minifiedGlossaryOutput); + console.log(`${chalk.green('SUCCESS!')} glossary.html file generated!`); +} catch (err) { + console.log(`${chalk.red('ERROR!')} During glossary.html generation: ${err}`); + process.exit(1); +} + +// Copy about.html +try { + fs.copyFileSync(path.join(staticPartsPath, 'about.html'), path.join(docsPath, 'about.html')); + console.log(`${chalk.green('SUCCESS!')} about.html file copied!`); +} catch (err) { + console.log(`${chalk.red('ERROR!')} During about.html copying: ${err}`); + process.exit(1); +} +// Copy contributing.html +try { + fs.copyFileSync(path.join(staticPartsPath, 'contributing.html'), path.join(docsPath, 'contributing.html')); + console.log(`${chalk.green('SUCCESS!')} contributing.html file copied!`); +} catch (err) { + console.log(`${chalk.red('ERROR!')} During contributing.html copying: ${err}`); + process.exit(1); +} + // Log the time taken console.timeEnd('Webber'); diff --git a/static-parts/about.html b/static-parts/about.html new file mode 100644 index 000000000..5cdc41d1d --- /dev/null +++ b/static-parts/about.html @@ -0,0 +1,128 @@ + + + + + + + + About - 30 seconds of code + + + + + + + + + + + + + +
+

logo 30 + seconds of code + Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. +

+
+
+
+

+

Our philosophy

+

The core goal of 30 seconds of code is to provide a quality resource for beginner and advanced JavaScript developers alike. We want to help improve the JavaScript ecosystem, by lowering the barrier of entry for newcomers and help seasoned veterans pick up new tricks and remember old ones. In order to achieve this, we have collected hundreds of snippets that can be of use in a wide range of situations. We welcome new contributors and we like fresh ideas, as long as the code is short and easy to grasp in about 30 seconds. The only catch, if you may, is that a few of our snippets are not perfectly optimized for large, enterprise applications and they might not be deemed production-ready.


+

Related projects

+

The idea behind 30 seconds of code has inspired some people to create similar collections in other programming languages and environments. Here are the ones we like the most:

+
+

Maintainers

+
+
+ +
+
+
+ fejes713 + Stefan Fejes +
+
+
+
+ flxwu + Felix Wu +
+
+
+
+ atomiks + atomiks +
+
+
+ +
+
+

Past maintainers

+
+
+ +
+ +
+
+ iamsoorena + Soorena +
+
+

License

+

In order for 30 seconds of code to be as accessible and useful as + possible, all of the snippets in the collection are licensed under the CC0-1.0 + License, meaning they are absolutely free to use in any project you like. If you like what we do, you can + always credit us, but that is not mandatory.


+
+ +
+ + + + diff --git a/static-parts/archived-page-end.html b/static-parts/archived-page-end.html index 5113345d9..ee6ad478b 100644 --- a/static-parts/archived-page-end.html +++ b/static-parts/archived-page-end.html @@ -1,7 +1,18 @@ +
+ + - - -
- - + + \ No newline at end of file diff --git a/static-parts/archived-page-start.html b/static-parts/archived-page-start.html index c249ed188..3f8691150 100644 --- a/static-parts/archived-page-start.html +++ b/static-parts/archived-page-start.html @@ -9,12 +9,12 @@ gtag('js', new Date()); gtag('config', 'UA-117141635-1'); - + Snippets Archive - 30 seconds of code - + @@ -22,11 +22,25 @@ - -
-

logo 30 seconds of code

-

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

- -
-
-
-
-

Snippets Archive

-

These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.


-
-
+ +
+

logo 30 seconds of code + Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. +

+
+
+
+

+

Snippets Archive

+

These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.


diff --git a/static-parts/beginner-page-start.html b/static-parts/beginner-page-start.html index 4ab08e6a0..4767d9bd8 100644 --- a/static-parts/beginner-page-start.html +++ b/static-parts/beginner-page-start.html @@ -9,7 +9,7 @@ gtag('js', new Date()); gtag('config', 'UA-117141635-1'); - + Snippets for Beginners - 30 seconds of code @@ -84,7 +84,7 @@ - +

logo 30 seconds of code

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

diff --git a/static-parts/contributing.html b/static-parts/contributing.html new file mode 100644 index 000000000..a3b47913b --- /dev/null +++ b/static-parts/contributing.html @@ -0,0 +1,79 @@ + + + + + + + + Contributing - 30 seconds of code + + + + + + + + + + + + + +
+

logo 30 + seconds of code + Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. +

+
+
+
+

+

How to contribute

+

Do you have a cool idea for a new snippet? Maybe some code you use often and is not part of our collection? Contributing to 30 seconds of code is as simple as 1,2,3,4!


+

1. Create

+

Start by creating a snippet, according to the snippet template. Make sure to follow these simple guidelines:

+
    +
  • Your snippet title must be unique and the same as the name of the implemented function.
  • +
  • Use the snippet description to explain what your snippet does and how it works.
  • +
  • Try to keep the snippet's code short and to the point. Use modern techniques and features.
  • +
  • Remember to provide an example of how your snippet works.
  • +
  • Your snippet should solve a real-world problem, no matter how simple.
  • +
  • Never modify README.md or any of the HTML files.
  • +

+

2. Tag

+

Run npm run tagger from your terminal, then open the tag_database file and tag your snippet appropriately. Multitagging is also supported, just make sure the first tag you specify is on of the major tags and the one that is most relevant to the implemented function.


+

3. Test

+

You can optionally test your snippet to make our job easier. Simply run npm run tester to generate the test files for your snippet. Find the related folder for you snippet under the test directory and write some tests. Remember to run npm run tester again to make sure your tests are passing.


+

4. Pull request

+

If you have done everything mentioned above, you should now have an awesome snippet to add to our collection. Simply start a pull request and follow the guidelines provided. Remember to only submit one snippet per pull request, so that we can quickly evaluate and merge your code into the collection.


+
+ +
+
+ + + diff --git a/static-parts/glossary-page-end.html b/static-parts/glossary-page-end.html new file mode 100644 index 000000000..ee6ad478b --- /dev/null +++ b/static-parts/glossary-page-end.html @@ -0,0 +1,18 @@ +
+ +
+
+ + + \ No newline at end of file diff --git a/static-parts/glossary-page-start.html b/static-parts/glossary-page-start.html new file mode 100644 index 000000000..c4f792a2c --- /dev/null +++ b/static-parts/glossary-page-start.html @@ -0,0 +1,114 @@ + + + + + + + + Glossary - 30 seconds of code + + + + + + + + + + + + + + +
+

logo 30 seconds of code + Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. +

+
+
+
+

+

Glossary

+

Developers use a lot of terminology daily. Every once in a while, you might find a term you do not know. We know how frustrating that can get, so we provide you with a handy glossary of frequently used web development terms.


diff --git a/static-parts/index.html b/static-parts/index.html deleted file mode 100644 index 54101f38a..000000000 --- a/static-parts/index.html +++ /dev/null @@ -1,273 +0,0 @@ - - - - - - - - 30 seconds of code - - - - - - - - - - - - - -
-

logo 30 seconds of code

-

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

- -
-
-
-
-
- -

$snippet-count
snippets

-
-
- -

$contrib-count
contributors

-
-
- -

$commit-count
commits

-
-
- -

$star-count
stars

-
-
-
-
-
-
-
-

Our philosophy

-

The core goal of 30 seconds of code is to provide a quality resource for beginner and advanced JavaScript developers alike. We want to help improve the JavaScript ecosystem, by lowering the barrier of entry for newcomers and help seasoned veterans pick up new tricks and remember old ones. In order to achieve this, we have collected hundreds of snippets that can be of use in a wide range of situations. We welcome new contributors and we like fresh ideas, as long as the code is short and easy to grasp in about 30 seconds. The only catch, if you may, is that a few of our snippets are not perfectly optimized for large, enterprise applications and they might not be deemed production-ready.


-
-
-
-
-
-
-
-
-

In order for 30 seconds of code to be as accessible and useful as possible, all of the snippets in the collection are licensed under the CC0-1.0 License, meaning they are absolutely free to use in any project you like. If you like what we do, you can always credit us, but that is not mandatory.

-
-

-
-
-
-
-

Today's picks

-

Our sophisticated robot helpers pick new snippets from our collection daily, so that you can discover new snippets to enhance your projects:

-
- - - $daily-picks -
-
-
-
-
-
-
-
-

Getting started

-
-
-
-
-
-

Related projects

-

The idea behind 30 seconds of code has inspired some people to create similar collections in other programming languages and environments. Here are the ones we like the most:

-
-
-
-
-
-

Top contributors

-
- - -
- flxwu - Felix Wu -
-
- atomiks - atomiks -
- -
- kriadmin - Rohit Tanwar -
- - -
-
-
-
-
-

How to contribute

-

Do you have a cool idea for a new snippet? Maybe some code you use often and is not part of our collection? Contributing to 30 seconds of code is as simple as 1,2,3,4!

-
- 1 -
-

Create

-

Start by creating a snippet, according to the snippet template. Make sure to follow these simple guidelines:

-
    -
  • Your snippet title must be unique and the same as the name of the implemented function.
  • -
  • Use the snippet description to explain what your snippet does and how it works.
  • -
  • Try to keep the snippet's code short and to the point. Use modern techniques and features.
  • -
  • Remember to provide an example of how your snippet works.
  • -
  • Your snippet should solve a real-world problem, no matter how simple.
  • -
  • Never modify README.md or any of the HTML files.
  • -
-
-
-
- 2 -
-

Tag

-

Run npm run tagger from your terminal, then open the tag_database file and tag your snippet appropriately. Multitagging is also supported, just make sure the first tag you specify is on of the major tags and the one that is most relevant to the implemented function.

-
-
-
- 3 -
-

Test

-

You can optionally test your snippet to make our job easier. Simply run npm run tester to generate the test files for your snippet. Find the related folder for you snippet under the test directory and write some tests. Remember to run npm run tester again to make sure your tests are passing.

-
-
-
- 4 -
-

Pull request

-

If you have done everything mentioned above, you should now have an awesome snippet to add to our collection. Simply start a pull request and follow the guidelines provided. Remember to only submit one snippet per pull request, so that we can quickly evaluate and merge your code into the collection.

-
-
-

If you need additional pointers about writing a snippet, be sure to read the complete contribution guidelines.

-
-
-
-
- - - - diff --git a/static-parts/page-end.html b/static-parts/page-end.html index 9871cd7c4..a3e5d1750 100644 --- a/static-parts/page-end.html +++ b/static-parts/page-end.html @@ -1,8 +1,13 @@ - -
+ +
- + \ No newline at end of file diff --git a/static-parts/page-start.html b/static-parts/page-start.html index 88a8c8d0c..a954e1555 100644 --- a/static-parts/page-start.html +++ b/static-parts/page-start.html @@ -9,7 +9,7 @@ gtag('js', new Date()); gtag('config', 'UA-117141635-1'); - + $tag - 30 seconds of code @@ -24,7 +24,7 @@ - -
-

logo 30 seconds of code + + +
+

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

-
-
- -