diff --git a/.gitignore b/.gitignore index dbebeb876..39ac4677d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -node_modules/ currentSnippet\.js *.md.temp.js .idea @@ -8,3 +7,77 @@ dist/flavor\.min\.css dist/flavor\.css test_old/ coverage/ + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn +yarn-error.log +.pnp/ +.pnp.js + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +# next.js build output +.next + +# gatsby files +.cache/ +public + +# Mac files +.DS_Store \ No newline at end of file diff --git a/docs/logos/logo_512.png b/assets/30s-icon.png similarity index 100% rename from docs/logos/logo_512.png rename to assets/30s-icon.png diff --git a/assets/NotoSans-Italic.ttf b/assets/NotoSans-Italic.ttf new file mode 100644 index 000000000..6d2c71c86 Binary files /dev/null and b/assets/NotoSans-Italic.ttf differ diff --git a/assets/NotoSans-Light.ttf b/assets/NotoSans-Light.ttf new file mode 100644 index 000000000..404ed0787 Binary files /dev/null and b/assets/NotoSans-Light.ttf differ diff --git a/assets/NotoSans-LightItalic.ttf b/assets/NotoSans-LightItalic.ttf new file mode 100644 index 000000000..4c338dba3 Binary files /dev/null and b/assets/NotoSans-LightItalic.ttf differ diff --git a/assets/NotoSans-Medium.ttf b/assets/NotoSans-Medium.ttf new file mode 100644 index 000000000..5dbefd372 Binary files /dev/null and b/assets/NotoSans-Medium.ttf differ diff --git a/assets/NotoSans-MediumItalic.ttf b/assets/NotoSans-MediumItalic.ttf new file mode 100644 index 000000000..3641525ea Binary files /dev/null and b/assets/NotoSans-MediumItalic.ttf differ diff --git a/assets/NotoSans-Regular.ttf b/assets/NotoSans-Regular.ttf new file mode 100644 index 000000000..0a01a062f Binary files /dev/null and b/assets/NotoSans-Regular.ttf differ diff --git a/assets/NotoSans-SemiBold.ttf b/assets/NotoSans-SemiBold.ttf new file mode 100644 index 000000000..8b7fd1302 Binary files /dev/null and b/assets/NotoSans-SemiBold.ttf differ diff --git a/assets/NotoSans-SemiBoldItalic.ttf b/assets/NotoSans-SemiBoldItalic.ttf new file mode 100644 index 000000000..a7e904c38 Binary files /dev/null and b/assets/NotoSans-SemiBoldItalic.ttf differ diff --git a/assets/RobotoMono-Italic.woff2 b/assets/RobotoMono-Italic.woff2 new file mode 100644 index 000000000..65d8c7b76 Binary files /dev/null and b/assets/RobotoMono-Italic.woff2 differ diff --git a/assets/RobotoMono-Medium.woff2 b/assets/RobotoMono-Medium.woff2 new file mode 100644 index 000000000..ec09ab18f Binary files /dev/null and b/assets/RobotoMono-Medium.woff2 differ diff --git a/assets/RobotoMono-Regular.woff2 b/assets/RobotoMono-Regular.woff2 new file mode 100644 index 000000000..53d4b505c Binary files /dev/null and b/assets/RobotoMono-Regular.woff2 differ diff --git a/assets/logo.png b/assets/logo.png new file mode 100644 index 000000000..9fa658d54 Binary files /dev/null and b/assets/logo.png differ diff --git a/docs/logos/logo.svg b/assets/logos/logo.svg similarity index 100% rename from docs/logos/logo.svg rename to assets/logos/logo.svg diff --git a/docs/logos/logo_128.png b/assets/logos/logo_128.png similarity index 100% rename from docs/logos/logo_128.png rename to assets/logos/logo_128.png diff --git a/docs/logos/logo_128_o.png b/assets/logos/logo_128_o.png similarity index 100% rename from docs/logos/logo_128_o.png rename to assets/logos/logo_128_o.png diff --git a/docs/logos/logo_128_white.png b/assets/logos/logo_128_white.png similarity index 100% rename from docs/logos/logo_128_white.png rename to assets/logos/logo_128_white.png diff --git a/docs/logos/logo_256.png b/assets/logos/logo_256.png similarity index 100% rename from docs/logos/logo_256.png rename to assets/logos/logo_256.png diff --git a/docs/logos/logo_256_white.png b/assets/logos/logo_256_white.png similarity index 100% rename from docs/logos/logo_256_white.png rename to assets/logos/logo_256_white.png diff --git a/docs/logos/logo_32.png b/assets/logos/logo_32.png similarity index 100% rename from docs/logos/logo_32.png rename to assets/logos/logo_32.png diff --git a/docs/logos/logo_32_white.png b/assets/logos/logo_32_white.png similarity index 100% rename from docs/logos/logo_32_white.png rename to assets/logos/logo_32_white.png diff --git a/docs/logos/logo_384.png b/assets/logos/logo_384.png similarity index 100% rename from docs/logos/logo_384.png rename to assets/logos/logo_384.png diff --git a/docs/logos/logo_384_white.png b/assets/logos/logo_384_white.png similarity index 100% rename from docs/logos/logo_384_white.png rename to assets/logos/logo_384_white.png diff --git a/assets/logos/logo_512.png b/assets/logos/logo_512.png new file mode 100644 index 000000000..9fa658d54 Binary files /dev/null and b/assets/logos/logo_512.png differ diff --git a/docs/logos/logo_512_white.png b/assets/logos/logo_512_white.png similarity index 100% rename from docs/logos/logo_512_white.png rename to assets/logos/logo_512_white.png diff --git a/docs/logos/logo_64.png b/assets/logos/logo_64.png similarity index 100% rename from docs/logos/logo_64.png rename to assets/logos/logo_64.png diff --git a/docs/logos/logo_64_white.png b/assets/logos/logo_64_white.png similarity index 100% rename from docs/logos/logo_64_white.png rename to assets/logos/logo_64_white.png diff --git a/config.js b/config.js index 75dbd628a..1d041cbcd 100644 --- a/config.js +++ b/config.js @@ -1,9 +1,9 @@ module.exports = { // Project metadata - name: `30 seconds starter`, - description: `Kick off your next, great 30 seconds project with this starter.`, + name: `30 seconds of code`, + description: `Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.`, shortName: `30s`, - repositoryUrl: `https://github.com/30-seconds/30-seconds-starter`, + repositoryUrl: `https://github.com/30-seconds/30-seconds-of-code`, // Path information snippetPath: `snippets`, snippetArchivePath: `snippets_archive`, diff --git a/docs/CNAME b/docs/CNAME deleted file mode 100644 index c4391f9e1..000000000 --- a/docs/CNAME +++ /dev/null @@ -1 +0,0 @@ -30secondsofcode.org diff --git a/docs/about.html b/docs/about.html deleted file mode 100644 index 819afc14b..000000000 --- a/docs/about.html +++ /dev/null @@ -1,598 +0,0 @@ - - - - - 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 deleted file mode 100644 index 41e7db03e..000000000 --- a/docs/adapter.html +++ /dev/null @@ -1,163 +0,0 @@ -Adapter - 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.prototype.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])
-  .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));
-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' };
-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.prototype.map() and Function.prototype.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.prototype.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.prototype.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,
-  async x => (await x) + 4
-);
-(async() => {
-  console.log(await sum(5)); // 15 (after one second)
-})();
-

Recommended Resource - ES6: The Right Parts

Learn new ES6 JavaScript language features like arrow function, destructuring, generators & more to write cleaner and more productive, readable programs.

pipeFunctions

Performs left-to-right function composition.

Use Array.prototype.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) =>
-  new Promise((resolve, reject) =>
-    func(...args, (err, result) => (err ? reject(err) : resolve(result)))
-  );
-
const delay = promisify((d, cb) => setTimeout(cb, d));
-delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s
-

rearg

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

Use Array.prototype.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);
-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 diff --git a/docs/archive.html b/docs/archive.html deleted file mode 100644 index f4c035a04..000000000 --- a/docs/archive.html +++ /dev/null @@ -1,292 +0,0 @@ -Snippets 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.prototype.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.prototype.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], 21); // -1
-

celsiusToFahrenheit

Celsius to Fahrenheit temperature conversion.

Follows the conversion formula F = 1.8C + 32.

const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;
-
celsiusToFahrenheit(33) // 91.4
-

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);
-    } else if (!keysToKeep.includes(key)) {
-      delete obj[key];
-    }
-  });
-  return obj;
-};
-
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
-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.prototype.map() and Array.prototype.filter() to find all the factors of num. If given num is negative, use Array.prototype.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.prototype.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;
-    return num >= 2;
-  };
-  const isNeg = num < 0;
-  num = isNeg ? -num : num;
-  let array = Array.from({ length: num - 1 })
-    .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
-    .filter(val => val);
-  if (isNeg)
-    array = array.reduce((acc, val) => {
-      acc.push(val);
-      acc.push(-val);
-      return acc;
-    }, []);
-  return primes ? array.filter(isPrime) : array;
-};
-
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]
-

fahrenheitToCelsius

Fahrenheit to Celsius temperature conversion.

Follows the conversion formula C = (F - 32) * 5/9.

const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;
-
fahrenheitToCelsius(32); // 0
-

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

heronArea

Returns the area of a triangle using only the 3 side lengths, Heron's formula. Assumes that the sides define a valid triangle. Does NOT assume it is a right triangle.

More information on what Heron's formula is and why it works available here: https://en.wikipedia.org/wiki/Heron%27s_formula.

Uses Math.sqrt() to find the square root of a value.

const heronArea = (side_a, side_b, side_c) => {
-    const p = (side_a + side_b + side_c) / 2
-    return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))
-  };
-
heronArea(3, 4, 5); // 6
-

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;
-  while (Number.isInteger(num / divisor)) {
-    i++;
-    num = num / divisor;
-  }
-  return i;
-};
-
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) => {
-  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 => {
-  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) => {
-  const request = new XMLHttpRequest();
-  request.open("PUT", url, true);
-  request.setRequestHeader('Content-type','application/json; charset=utf-8');
-  request.onload = () => callback(request);
-  request.onerror = () => err(request);
-  request.send(data);
-};
-
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 =>
-  (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
-    (digits + '').split('')
-  );
-
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) =>
-  [...str].reduce(
-      (matchIndex, char) =>
-          char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()
-              ? matchIndex + 1
-              : matchIndex,
-      0
-  ) === pattern.length;
-
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 => {
-  const dt = new Date(parseInt(arr.toString().substr(6)));
-  return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
-};
-
JSONToDate(/Date(1489525200000)/); // "14/3/2017"
-

kmphToMph

Convert kilometers/hour to miles/hour.

Multiply the constant of proportionality with the argument.

const kmphToMph = (kmph) => 0.621371192 * kmph;
-
kmphToMph(10); // 16.09344000614692
-kmphToMph(345.4); // 138.24264965280207
-

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]);
-  matrix[0] = Array(string1.length + 1)
-    .fill(0)
-    .map((x, i) => i);
-  for (let i = 1; i <= string2.length; i++) {
-    for (let j = 1; j <= string1.length; j++) {
-      if (string2[i - 1] === string1[j - 1]) {
-        matrix[i][j] = matrix[i - 1][j - 1];
-      } else {
-        matrix[i][j] = Math.min(
-          matrix[i - 1][j - 1] + 1,
-          matrix[i][j - 1] + 1,
-          matrix[i - 1][j] + 1
-        );
-      }
-    }
-  }
-  return matrix[string2.length][string1.length];
-};
-
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 (%)
-

mphToKmph

Convert miles/hour to kilometers/hour.

Multiply the constant of proportionality with the argument.

const mphToKmph = (mph) => 1.6093440006146922 * mph;
-
mphToKmph(10); // 16.09344000614692
-mphToKmph(85.9); // 138.24264965280207
-

pipeLog

Logs a value and returns it.

Use console.log to log the supplied value, combined with the || operator to return it.

const pipeLog = data => console.log(data) || data;
-
pipeLog(1); // logs `1` and returns `1`
-

quickSort

QuickSort an Array (ascending sort by default).

Use recursion. Use Array.prototype.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)
-    ? []
-    : [
-        ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),
-        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], true); // [4,3,2,1]
-

removeVowels

Returns all the vowels in a str replaced by repl.

Use String.prototype.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.prototype.replace() with a regular expression to replace ^ with **, String.prototype.split() to tokenize the string and Array.prototype.filter() to remove empty tokens. Use Array.prototype.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,
-    '-': (a, b) => a - b,
-    '/': (a, b) => a / b,
-    '**': (a, b) => a ** b
-  };
-  const [stack, solve] = [
-    [],
-    rpn
-      .replace(/\^/g, '**')
-      .split(/\s+/g)
-      .filter(el => !/\s+/.test(el) && el !== '')
-  ];
-  solve.forEach(symbol => {
-    if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {
-      stack.push(symbol);
-    } else if (Object.keys(OPERATORS).includes(symbol)) {
-      const [a, b] = [stack.pop(), stack.pop()];
-      stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));
-    } else {
-      throw `${symbol} is not a recognized symbol`;
-    }
-  });
-  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('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 => {
-  const msg = new SpeechSynthesisUtterance(message);
-  msg.voice = window.speechSynthesis.getVoices()[0];
-  window.speechSynthesis.speak(msg);
-};
-
speechSynthesis('Hello, World'); // // plays the message
-

squareSum

Squares each number in an array and then sums the results together.

Use Array.prototype.reduce() in combination with Math.pow() to iterate over numbers and sum their squares into an accumulator.

const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);
-
squareSum(1, 2, 2); // 9
-
\ No newline at end of file diff --git a/docs/array.html b/docs/array.html deleted file mode 100644 index d82a3f558..000000000 --- a/docs/array.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - Array - 30 seconds of code - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/browser.html b/docs/browser.html deleted file mode 100644 index efcc33e94..000000000 --- a/docs/browser.html +++ /dev/null @@ -1,396 +0,0 @@ -Browser - 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.prototype.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 = () =>
-  document.documentElement.clientHeight + window.scrollY >=
-  (document.documentElement.scrollHeight || document.documentElement.clientHeight);
-
bottomVisible(); // true
-

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', '');
-  el.style.position = 'absolute';
-  el.style.left = '-9999px';
-  document.body.appendChild(el);
-  const selected =
-    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
-  el.select();
-  document.execCommand('copy');
-  document.body.removeChild(el);
-  if (selected) {
-    document.getSelection().removeAllRanges();
-    document.getSelection().addRange(selected);
-  }
-};
-
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
-

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(() => {
-      current += _step;
-      document.querySelector(selector).innerHTML = current;
-      if (current >= end) document.querySelector(selector).innerHTML = end;
-      if (current >= end) clearInterval(timer);
-    }, 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 => {
-  const el = document.createElement('div');
-  el.innerHTML = str;
-  return el.firstElementChild;
-};
-
const el = createElement(
-  `<div class="container">
-    <p>Hello!</p>
-  </div>`
-);
-console.log(el.className); // 'container'
-

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.prototype.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.prototype.push() to add the handler to the array. For off, use Array.prototype.findIndex() to find the index of the handler in the event array and remove it using Array.prototype.splice().

const createEventHub = () => ({
-  hub: Object.create(null),
-  emit(event, data) {
-    (this.hub[event] || []).forEach(handler => handler(data));
-  },
-  on(event, handler) {
-    if (!this.hub[event]) this.hub[event] = [];
-    this.hub[event].push(handler);
-  },
-  off(event, handler) {
-    const i = (this.hub[event] || []).findIndex(h => h === handler);
-    if (i > -1) this.hub[event].splice(i, 1);
-    if (this.hub[event].length === 0) delete this.hub[event];
-  }
-});
-
const handler = data => console.log(data);
-const hub = createEventHub();
-let increment = 0;
-
-// Subscribe: listen for different types of events
-hub.on('message', handler);
-hub.on('message', () => console.log('Message event fired'));
-hub.on('increment', () => increment++);
-
-// Publish: emit events to invoke all handlers subscribed to them, passing the data to them as an argument
-hub.emit('message', 'hello world'); // logs 'hello world' and 'Message event fired'
-hub.emit('message', { hello: 'world' }); // logs the object and 'Message event fired'
-hub.emit('increment'); // `increment` variable is now 1
-
-// 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 whether 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
-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) => {
-  const { top, left, bottom, right } = el.getBoundingClientRect();
-  const { innerHeight, innerWidth } = window;
-  return partiallyVisible
-    ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
-        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
-    : 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}
-elementIsVisibleInViewport(el); // false - (not fully visible)
-elementIsVisibleInViewport(el, true); // true - (partially visible)
-

formToObject

Encode a set of form elements as an object.

Use the FormData constructor to convert the HTML form to FormData, Array.from() to convert to an array. Collect the object from the array, using Array.prototype.reduce().

const formToObject = form =>
-  Array.from(new FormData(form)).reduce(
-    (acc, [key, value]) => ({
-      ...acc,
-      [key]: value
-    }),
-    {}
-  );
-
formToObject(document.querySelector('#form')); // { email: 'test@email.com', name: 'Test Name' }
-

getImages

Fetches all images from within an element and puts them into an array

Use Element.prototype.getElementsByTagName() to fetch all <img> elements inside the provided element, Array.prototype.map() to map every src attribute of their respective <img> element, then create a Set to eliminate duplicates and return the array.

const getImages = (el, includeDuplicates = false) => {
-  const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
-  return includeDuplicates ? images : [...new Set(images)];
-};
-
getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
-getImages(document, false); // ['image1.jpg', 'image2.png', '...']
-

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
-

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);
-    for (let i = 0; i < view.byteLength; i += 4)
-      hexes.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 = (...el) => [...el].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.prototype.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>
-

Recommended Resource - JavaScript: The Hard Parts

Take your JavaScript to the next level. Gain an understanding of callbacks, higher order functions, closure, asynchronous and object-oriented JavaScript!

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

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.prototype.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,
-    Object.assign(
-      {
-        childList: true,
-        attributes: true,
-        attributeOldValue: true,
-        characterData: true,
-        characterDataOldValue: true,
-        subtree: true
-      },
-      options
-    )
-  );
-  return observer;
-};
-
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('!');
-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 = {}) => {
-  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('!');
-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
-

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 = () => {
-    const now = performance.now();
-    if (now - lastTime < 20)
-      (type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler);
-    lastTime = now;
-  };
-  document.addEventListener('touchstart', () => {
-    if (type === 'touch') return;
-    (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler);
-  });
-};
-
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.prototype.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.prototype.charAt() and String.prototype.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(
-    prefix => typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined'
-  );
-  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) => {
-  let running = true,
-    raf;
-  const stop = () => {
-    running = false;
-    cancelAnimationFrame(raf);
-  };
-  const start = () => {
-    running = true;
-    run();
-  };
-  const run = () => {
-    raf = requestAnimationFrame(() => {
-      callback();
-      if (running) run();
-    });
-  };
-  if (autoStart) start();
-  return { start, stop };
-};
-
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) =>
-  asLink ? (window.location.href = url) : window.location.replace(url);
-
redirect('https://google.com');
-

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'
-    })
-  );
-  return new Promise((res, rej) => {
-    worker.onmessage = ({ data }) => {
-      res(data), worker.terminate();
-    };
-    worker.onerror = err => {
-      rej(err), worker.terminate();
-    };
-  });
-};
-
const longRunningFunction = () => {
-  let result = 0;
-  for (let i = 0; i < 1000; i++)
-    for (let j = 0; j < 700; j++) for (let k = 0; k < 300; k++) result = result + i + j + k;
-
-  return result;
-};
-/*
-  NOTE: Since the function is running in a different context, closures are not supported.
-  The function supplied to `runAsync` gets stringified, so everything becomes literal.
-  All variables and functions must be defined inside.
-*/
-runAsync(longRunningFunction).then(console.log); // 209685000000
-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 = () => {
-  const c = document.documentElement.scrollTop || document.body.scrollTop;
-  if (c > 0) {
-    window.requestAnimationFrame(scrollToTop);
-    window.scrollTo(0, c - c / 8);
-  }
-};
-
scrollToTop();
-

serializeForm

Encode a set of form elements as a query string.

Use the FormData constructor to convert the HTML form to FormData, Array.from() to convert to an array, passing a map function as the second argument. Use Array.prototype.map() and window.encodeURIComponent() to encode each field's value. Use Array.prototype.join() with appropriate argumens to produce an appropriate query string.

const serializeForm = form =>
-  Array.from(new FormData(form), field => field.map(encodeURIComponent).join('=')).join('&');
-
serializeForm(document.querySelector('#form')); // email=test%40email.com&name=Test%20Name
-

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.prototype.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 =>
-  document.querySelector(element).scrollIntoView({
-    behavior: 'smooth'
-  });
-
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) =>
-  el.dispatchEvent(new CustomEvent(eventType, { detail }));
-
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 = () =>
-  ([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 diff --git a/docs/clipboard.svg b/docs/clipboard.svg deleted file mode 100644 index 478a450ef..000000000 --- a/docs/clipboard.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/docs/contributing.html b/docs/contributing.html deleted file mode 100644 index 5fdd717e3..000000000 --- a/docs/contributing.html +++ /dev/null @@ -1,549 +0,0 @@ - - - - - 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 deleted file mode 100644 index 8cd64ebed..000000000 --- a/docs/date.html +++ /dev/null @@ -1,174 +0,0 @@ -Date - 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

dayOfYear

Gets the day of the year from a Date object.

Use new Date() and Date.prototype.getFullYear() to get the first day of the year as a Date object, subtract it from the provided date and divide with the milliseconds in each day to get the result. Use Math.floor() to appropriately round the resulting day count to an integer.

const dayOfYear = date =>
-  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
-
dayOfYear(new Date()); // 272
-

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.prototype.filter() to keep only non-zero values. Use Array.prototype.map() to create the string for each value, pluralizing appropriately. Use String.prototype.join(', ') to combine the values into a string.

const formatDuration = ms => {
-  if (ms < 0) ms = -ms;
-  const time = {
-    day: Math.floor(ms / 86400000),
-    hour: Math.floor(ms / 3600000) % 24,
-    minute: Math.floor(ms / 60000) % 60,
-    second: Math.floor(ms / 1000) % 60,
-    millisecond: Math.floor(ms) % 1000
-  };
-  return Object.entries(time)
-    .filter(val => val[1] !== 0)
-    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
-    .join(', ');
-};
-
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.prototype.toTimeString() and String.prototype.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) =>
-  (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 =>
-  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"
-

isAfterDate

Check if a date is after another date.

Use the greater than operator (>) to check if the first date comes after the second one.

const isAfterDate = (dateA, dateB) => dateA > dateB;
-
isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true
-

isBeforeDate

Check if a date is before another date.

Use the less than operator (<) to check if the first date comes before the second one.

const isBeforeDate = (dateA, dateB) => dateA < dateB;
-
isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true
-

isSameDate

Check if a date is the same as another date.

Use Date.prototype.toISOString() and strict equality checking (===) to check if the first date is the same as the second one.

const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();
-
isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true
-

Recommended Resource - JavaScript: The Hard Parts

Take your JavaScript to the next level. Gain an understanding of callbacks, higher order functions, closure, asynchronous and object-oriented JavaScript!

isWeekday

Results in a boolean representation of a specific date.

Pass the specific date object firstly. Use Date.getDay() to check weekday by using a modulo operator and then returning a boolean.

const isWeekday = (t = new Date()) => {
-  return t.getDay() % 6 !== 0;
-};
-
isWeekday(); // true (if current date is 2019-07-19)
-

isWeekend

Results in a boolean representation of a specific date.

Pass the specific date object firstly. Use Date.getDay() to check weekend based on the day being returned as 0 - 6 using a modulo operation then return a boolean.

const isWeekend = (t = new Date()) => {
-  return t.getDay() % 6 === 0;
-};
-
isWeekend(); // 2018-10-19 (if current date is 2018-10-18)
-

maxDate

Returns the maximum of the given dates.

Use the ES6 spread syntax with Math.max to find the maximum date value, new Date() to convert it to a Date object.

const maxDate = dates => new Date(Math.max(...dates));
-
const array = [
-  new Date(2017, 4, 13),
-  new Date(2018, 2, 12),
-  new Date(2016, 0, 10),
-  new Date(2016, 0, 9)
-];
-maxDate(array); // 2018-03-11T22:00:00.000Z
-

minDate

Returns the minimum of the given dates.

Use the ES6 spread syntax to find the minimum date value, new Date() to convert it to a Date object.

const minDate = dates => new Date(Math.min(...dates));
-
const array = [
-  new Date(2017, 4, 13),
-  new Date(2018, 2, 12),
-  new Date(2016, 0, 10),
-  new Date(2016, 0, 9)
-];
-minDate(array); // 2016-01-08T22:00:00.000Z
-

tomorrow

Results in a string representation of tomorrow's date.

Use new Date() to get the current date, increment by one using Date.getDate() and set the value to the result using Date.setDate(). Use Date.prototype.toISOString() to return a string in yyyy-mm-dd format.

const tomorrow = () => {
-  let t = new Date();
-  t.setDate(t.getDate() + 1);
-  return t.toISOString().split('T')[0];
-};
-
tomorrow(); // 2018-10-19 (if current date is 2018-10-18)
-

yesterday

Results in a string representation of yesterday's date.

Use new Date() to get the current date, decrement by one using Date.getDate() and set the value to the result using Date.setDate(). Use Date.prototype.toISOString() to return a string in yyyy-mm-dd format.

const yesterday = () => {
-  let t = new Date();
-  t.setDate(t.getDate() - 1);
-  return t.toISOString().split('T')[0];
-};
-
yesterday(); // 2018-10-17 (if current date is 2018-10-18)
-
\ No newline at end of file diff --git a/docs/favicon.png b/docs/favicon.png deleted file mode 100644 index 7113c0ef1..000000000 Binary files a/docs/favicon.png and /dev/null differ diff --git a/docs/function.html b/docs/function.html deleted file mode 100644 index df61f8276..000000000 --- a/docs/function.html +++ /dev/null @@ -1,354 +0,0 @@ -Function - 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) => {
-  try {
-    return fn(...args);
-  } catch (e) {
-    return e instanceof Error ? e : new Error(e);
-  }
-};
-
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.prototype.apply() to apply the given context to fn. Use Array.prototype.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.prototype.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 = {
-  user: 'fred',
-  greet: function(greeting, punctuation) {
-    return greeting + ' ' + this.user + punctuation;
-  }
-};
-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 => {
-  let curr = 0;
-  const last = fns[fns.length - 1];
-  const next = () => {
-    const fn = fns[curr++];
-    fn === last ? fn() : fn(next);
-  };
-  next();
-};
-
chainAsync([
-  next => {
-    console.log('0 seconds');
-    setTimeout(next, 1000);
-  },
-  next => {
-    console.log('1 second');
-    setTimeout(next, 1000);
-  },
-  () => {
-    console.log('2 second');
-  }
-]);
-

checkProp

Given a predicate function and a prop string, this curried function will then take an object to inspect by calling the property and passing it to the predicate.

Summon prop on obj, pass it to a provided predicate function and return a masked boolean.

const checkProp = (predicate, prop) => obj => !!predicate(obj[prop]);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-const lengthIs4 = checkProp(l => l === 4, 'length');
-lengthIs4([]); // false
-lengthIs4([1,2,3,4]); // true
-lengthIs4(new Set([1,2,3,4])); // false (Set uses Size, not length)
-
-const session = { user: {} };
-const validUserSession = checkProps(u => u.active && !u.disabled, 'user');
-
-validUserSession(session); // false
-
-session.user.active = true;
-validUserSession(session); // true
-
-const noLength(l => l === undefined, 'length');
-noLength([]); // false
-noLength({}); // true
-noLength(new Set()); // true
-

compose

Performs right-to-left function composition.

Use Array.prototype.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.prototype.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.prototype.map() and Function.prototype.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) =>
-  arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
-
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.prototype.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(
-  '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:
-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(
-  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) => {
-  const before = performance.now();
-  for (let i = 0; i < iterations; i++) fn();
-  return (1000 * iterations) / (performance.now() - before);
-};
-
// 10,000 element array
-const numbers = Array(10000)
-  .fill()
-  .map((_, i) => i);
-
-// Test functions with the same goal: sum up the elements in the array
-const sumReduce = () => numbers.reduce((acc, n) => acc + n, 0);
-const sumForLoop = () => {
-  let sum = 0;
-  for (let i = 0; i < numbers.length; i++) sum += numbers[i];
-  return sum;
-};
-
-// `sumForLoop` is nearly 10 times faster
-Math.round(hz(sumReduce)); // 572
-Math.round(hz(sumForLoop)); // 4784
-

Recommended Resource - ES6: The Right Parts

Learn new ES6 JavaScript language features like arrow function, destructuring, generators & more to write cleaner and more productive, readable programs.

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);
-  };
-  cached.cache = cache;
-  return cached;
-};
-
// 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 => {
-  let called = false;
-  return function(...args) {
-    if (called) return;
-    called = true;
-    return fn.apply(this, args);
-  };
-};
-
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 + '!';
-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 + '!';
-const greetJohn = partialRight(greet, 'John');
-greetJohn('Hello'); // 'Hello John!'
-

runPromisesInSeries

Runs an array of promises in series.

Use Array.prototype.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() {
-  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.prototype.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,
-      args = arguments;
-    if (!inThrottle) {
-      fn.apply(context, args);
-      lastTime = Date.now();
-      inThrottle = true;
-    } else {
-      clearTimeout(lastFn);
-      lastFn = setTimeout(function() {
-        if (Date.now() - lastTime >= wait) {
-          fn.apply(context, args);
-          lastTime = Date.now();
-        }
-      }, Math.max(wait - (Date.now() - lastTime), 0));
-    }
-  };
-};
-
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) => {
-  let i = 0;
-  while (fn.call(context, i) !== false && ++i < n) {}
-};
-
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.prototype.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.prototype.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 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.prototype.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]);
-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);
-doubleEvenNumbers(2); // 4
-doubleEvenNumbers(1); // 1
-
\ No newline at end of file diff --git a/docs/glossary.html b/docs/glossary.html deleted file mode 100644 index 2b3fc6c00..000000000 --- a/docs/glossary.html +++ /dev/null @@ -1,79 +0,0 @@ -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 transferred 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 shadowdom 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 webcomponents 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.

Shadow DOM

Shadow DOM allows you to attach hidden DOM trees to elements in the normal DOM tree, which are included in the document rendering, but excluded from the main document DOM tree. A shadow DOM tree will start with a shadow root, to which you can attach any elements you want, just like in a regular DOM. Examples of shadow DOM uses are the <video>/<audio> elements and the simple <input type="range"> element.

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.

Web Components

Web Components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use on web pages and apps. Building custom components using these standards means that you can use them across modern browsers regardless of any JavaScript library or framework.

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/icons/chevron-left.svg b/docs/icons/chevron-left.svg deleted file mode 100644 index 5fa552a07..000000000 --- a/docs/icons/chevron-left.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/docs/icons/chevron-right.svg b/docs/icons/chevron-right.svg deleted file mode 100644 index 399d68762..000000000 --- a/docs/icons/chevron-right.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/docs/icons/code.svg b/docs/icons/code.svg deleted file mode 100644 index d66aa59da..000000000 --- a/docs/icons/code.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/docs/icons/dashboard.svg b/docs/icons/dashboard.svg deleted file mode 100644 index 8a27ad0ad..000000000 --- a/docs/icons/dashboard.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/docs/icons/git-branch.svg b/docs/icons/git-branch.svg deleted file mode 100644 index 279e21c5c..000000000 --- a/docs/icons/git-branch.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/docs/icons/law.svg b/docs/icons/law.svg deleted file mode 100644 index 61701b384..000000000 --- a/docs/icons/law.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/docs/icons/organization.svg b/docs/icons/organization.svg deleted file mode 100644 index b968ecfcd..000000000 --- a/docs/icons/organization.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/docs/icons/star.svg b/docs/icons/star.svg deleted file mode 100644 index 4a584a3c9..000000000 --- a/docs/icons/star.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index 4fb8f9ff6..000000000 --- a/docs/index.html +++ /dev/null @@ -1,647 +0,0 @@ -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

all

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

Use Array.prototype.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
-

allEqual

Check if all elements in an array are equal.

Use Array.prototype.every() to check if all the elements of the array are the same as the first one. Elements in the array are compared using the strict comparison operator, which does not account for NaN self-inequality.

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

any

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

Use Array.prototype.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
-

arrayToCSV

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

Use Array.prototype.map() and Array.prototype.join(delimiter) to combine individual 1D arrays (rows) into strings. Use Array.prototype.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 => (isNaN(x) ? `"${x.replace(/"/g, '""')}"` : 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"'
-arrayToCSV([['a', '"b" great'], ['c', 3.1415]]); // '"a","""b"" great"\n"c",3.1415'
-

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.prototype.reduce() and Array.prototype.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'] ]
-

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.prototype.reduce() and Array.prototype.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'] ]
-

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

compact

Removes falsy values from an array.

Use Array.prototype.filter() to filter out falsy 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 ]
-

countBy

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

Use Array.prototype.map() to map the values of an array to a function or property name. Use Array.prototype.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) => {
-    acc[val] = (acc[val] || 0) + 1;
-    return acc;
-  }, {});
-
countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
-countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}
-

countOccurrences

Counts the occurrences of a value in an array.

Use Array.prototype.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
-

deepFlatten

Deep flattens an array.

Use recursion. Use Array.prototype.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]
-

difference

Returns the difference between two arrays.

Create a Set from b, then use Array.prototype.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]
-

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.prototype.map() to apply fn to each element in a, then Array.prototype.filter()

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

differenceWith

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

Use Array.prototype.filter() and Array.prototype.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]
-

drop

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

Use Array.prototype.slice() to 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); // []
-

dropRight

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

Use Array.prototype.slice() to 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); // []
-

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.prototype.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) => {
-  let rightIndex = arr.length;
-  while (rightIndex-- && !func(arr[rightIndex]));
-  return arr.slice(0, rightIndex + 1);
-};
-
dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
-

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

everyNth

Returns every nth element in an array.

Use Array.prototype.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 ]
-

filterFalsy

Filters out the falsy values in an array.

Use Array.prototype.filter() to get an array containing only truthy values.

const filterFalsy = arr => arr.filter(Boolean);
-
filterFalsy(['', true, {}, false, 'sample', 1, 0]); // [true, {}, 'sample', 1]
-

filterNonUnique

Filters out the non-unique values in an array.

Use Array.prototype.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]
-

filterNonUniqueBy

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

Use Array.prototype.filter() and Array.prototype.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' } ]
-

findLast

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

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

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

findLastIndex

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

Use Array.prototype.map() to map each element to an array with its index and value. Use Array.prototype.filter() to remove elements for which fn returns falsy values, Array.prototype.pop() to get the last one. -1 is the default value when not found.

const findLastIndex = (arr, fn) =>
-  (arr
-    .map((val, i) => [i, val])
-    .filter(([i, val]) => fn(val, i, arr))
-    .pop() || [-1])[0];
-
findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3)
-findLastIndex([1, 2, 3, 4], n => n === 5); // -1 (default value when not found)
-

flatten

Flattens an array up to the specified depth.

Use recursion, decrementing depth by 1 for each level of depth. Use Array.prototype.reduce() and Array.prototype.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]
-

forEachRight

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

Use Array.prototype.slice(0) to clone the given array, Array.prototype.reverse() to reverse it and Array.prototype.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'
-

groupBy

Groups the elements of an array based on the given function.

Use Array.prototype.map() to map the values of an array to a function or property name. Use Array.prototype.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']}
-

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
-

indexOfAll

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

Use Array.prototype.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); // []
-

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

initialize2DArray

Initializes a 2D array of given width and height and value.

Use Array.prototype.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]]
-

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

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

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

initializeNDArray

Create a n-dimensional array with given value.

Use recursion. Use Array.prototype.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]]]
-

intersection

Returns a list of elements that exist in both arrays.

Create a Set from b, then use Array.prototype.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]
-

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.prototype.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(fn));
-  return a.filter(x => s.has(fn(x)));
-};
-
intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
-

intersectionWith

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

Use Array.prototype.filter() and Array.prototype.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]
-

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
-

join

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

Use Array.prototype.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"
-

JSONtoCSV

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

Use Array.prototype.join(delimiter) to combine all the names in columns to create the first row. Use Array.prototype.map() and Array.prototype.reduce() to create a row for each object, substituting non-existent values with empty strings and only mapping values in columns. Use Array.prototype.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"'
-

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
-

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.prototype.reduce(), comparing the length of objects to find the longest one.

const longestItem = (...vals) => 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'
-

mapObject

Maps the values of an array to an object using a function, where the key-value pairs consist of the stringified 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 }
-

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.prototype.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. Use Array.prototype.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.prototype.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in ascending order. Use Array.prototype.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]
-

none

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

Use Array.prototype.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
-

nthElement

Returns the nth element of an array.

Use Array.prototype.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'
-

Recommended Resource - ES6: The Right Parts

Learn new ES6 JavaScript language features like arrow function, destructuring, generators & more to write cleaner and more productive, readable programs.

offset

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

Use Array.prototype.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]
-

partition

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

Use Array.prototype.reduce() to create an array of two arrays. Use Array.prototype.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 }]]
-

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.prototype.map() to combine the element with each partial permutation, then Array.prototype.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 ] ]
-

pull

Mutates the original array to filter out the values specified.

Use Array.prototype.filter() and Array.prototype.includes() to pull out the values that are not needed. Use Array.prototype.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.prototype.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'];
-pull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ]
-

pullAtIndex

Mutates the original array to filter out the values at the specified indexes.

Use Array.prototype.filter() and Array.prototype.includes() to pull out the values that are not needed. Use Array.prototype.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.prototype.push() to re-populate it with only the pulled values. Use Array.prototype.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' ]
-

pullAtValue

Mutates the original array to filter out the values specified. Returns the removed elements.

Use Array.prototype.filter() and Array.prototype.includes() to pull out the values that are not needed. Use Array.prototype.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.prototype.push() to re-populate it with only the pulled values. Use Array.prototype.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' ]
-

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.prototype.map() to apply the iterator function fn to all array elements. Use Array.prototype.filter() and Array.prototype.includes() to pull out the values that are not needed. Use Array.prototype.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.prototype.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 }]
-

reducedFilter

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

Use Array.prototype.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.prototype.map() to return the new object using Array.prototype.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 = [
-  {
-    id: 1,
-    name: 'john',
-    age: 24
-  },
-  {
-    id: 2,
-    name: 'mike',
-    age: 50
-  }
-];
-
-reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]
-

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

reduceWhich

Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.

Use Array.prototype.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}
-

reject

Takes a predicate and array, like Array.prototype.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']
-

remove

Removes elements from an array for which the given function returns false.

Use Array.prototype.filter() to find array elements that return truthy values and Array.prototype.reduce() to remove elements using Array.prototype.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]
-

sample

Returns a random element from an array.

Use Math.random() to generate a random number, multiply it by length and round it off 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
-

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

shank

Has the same functionality as Array.prototype.splice(), but returning a new array instead of mutating the original array.

Use Array.prototype.slice() and Array.prototype.concat() to get a new array with the new contents after removing existing elements and/or adding new elements. Omit the second argument, index, to start at 0. Omit the third argument, delCount, to remove 0 elements. Omit the fourth argument, elements, in order to not add any new elements.

const shank = (arr, index = 0, delCount = 0, ...elements) =>
-  arr
-    .slice(0, index)
-    .concat(elements)
-    .concat(arr.slice(index + delCount));
-
const names = ['alpha', 'bravo', 'charlie'];
-const namesAndDelta = shank(names, 1, 0, 'delta'); // [ 'alpha', 'delta', 'bravo', 'charlie' ]
-const namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ]
-console.log(names); // ['alpha', 'bravo', 'charlie']
-

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

similarity

Returns an array of elements that appear in both arrays.

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

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

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

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

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.prototype.reverse() and Array.prototype.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
-

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.prototype.map() to apply the iterator function to all elements of the array. Use Array.prototype.reverse() and Array.prototype.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
-

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.prototype.map() to pair each element of the input array with its corresponding index. Use Array.prototype.sort() and a compare function to sort the list, preserving their initial order if the items compared are equal. Use Array.prototype.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]
-

symmetricDifference

Returns the symmetric difference between two arrays, without filtering out duplicate values.

Create a Set from each array, then use Array.prototype.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]
-

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

symmetricDifferenceWith

Returns the symmetric difference between two arrays, using a provided function as a comparator.

Use Array.prototype.filter() and Array.prototype.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]
-

tail

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

Return Array.prototype.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]
-

take

Returns an array with n elements removed from the beginning.

Use Array.prototype.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); // []
-

takeRight

Returns an array with n elements removed from the end.

Use Array.prototype.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]
-

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 Array.prototype.reduceRight() and accumulating elements while the function returns falsy value.

const takeRightWhile = (arr, func) =>
-  arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []);
-
takeRightWhile([1, 2, 3, 4], n => n < 3); // [3, 4]
-

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.prototype.entries() until the returned value from the function is true. Return the removed elements, using Array.prototype.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]
-

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, 3: 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" } ] } ]
-

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

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(fn));
-  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]
-

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

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

uniqueElementsBy

Returns all unique values of an array, based on a provided comparator function.

Use Array.prototype.reduce() and Array.prototype.some() for an array containing only the first unique occurrence 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' } ]
-

uniqueElementsByRight

Returns all unique values of an array, based on a provided comparator function, starting from the right.

Use Array.prototype.reduceRight() and Array.prototype.some() for an array containing only the last unique occurrence 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' } ]
-

uniqueSymmetricDifference

Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.

Use Array.prototype.filter() and Array.prototype.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]
-

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.prototype.map() to make each element an array. Use Array.prototype.reduce() and Array.prototype.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]]
-

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.prototype.map() to make each element an array. Use Array.prototype.reduce() and Array.prototype.forEach() to map grouped values to individual arrays. Use Array.prototype.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]
-

without

Filters out the elements of an array, that have one of the specified values.

Use Array.prototype.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]
-

xProd

Creates a new array out of the two supplied by creating each possible pair from the arrays.

Use Array.prototype.reduce(), Array.prototype.map() and Array.prototype.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']]
-

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

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.prototype.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}
-

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/manifest.json b/docs/manifest.json deleted file mode 100644 index a07c048e8..000000000 --- a/docs/manifest.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "30 seconds of code", - "short_name": "30s of code", - "start_url": "./index.html", - "display": "standalone", - "background_color": "#fff", - "theme_color": "#202124", - "description": "Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.", - "icons": [ - { - "src": "./logos/logo_32.png", - "sizes": "32x32", - "type": "image/png" - }, - { - "src": "./logos/logo_64.png", - "sizes": "64x64", - "type": "image/png" - }, - { - "src": "./logos/logo_128.png", - "sizes": "128x128", - "type": "image/png" - }, - { - "src": "./logos/logo_256.png", - "sizes": "256x256", - "type": "image/png" - }, - { - "src": "./logos/logo_512.png", - "sizes": "512x512", - "type": "image/png" - } - ] -} diff --git a/docs/math.html b/docs/math.html deleted file mode 100644 index 1746dc8a0..000000000 --- a/docs/math.html +++ /dev/null @@ -1,311 +0,0 @@ -Math - 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.prototype.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.prototype.map() to map each element to the value returned by fn, Array.prototype.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 }], '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) => {
-  if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
-  if (k < 0 || k > n) return 0;
-  if (k === 0 || k === n) return 1;
-  if (k === 1 || k === n - 1) return n;
-  if (n - k < k) k = n - k;
-  let res = n;
-  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
-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.prototype.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
-

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) =>
-    (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));
-  if (ratings.length === 2) return [newRating(a, 1), newRating(b, 0)];
-
-  for (let i = 0, len = ratings.length; i < len; i++) {
-    let j = i;
-    while (j < len - 1) {
-      j++;
-      [ratings[i], ratings[j]] = elo([ratings[i], ratings[j]], kFactor);
-    }
-  }
-  return ratings;
-};
-
// Standard 1v1s
-elo([1200, 1200]); // [1216, 1184]
-elo([1200, 1200], 64); // [1232, 1168]
-// 4 player FFA, all same rank
-elo([1200, 1200, 1200, 1200]).map(Math.round); // [1246, 1215, 1185, 1154]
-/*
-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 =>
-  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.prototype.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) => {
-  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
-

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.prototype.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, 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) => {
-  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, 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
-

isNegativeZero

Checks if the given value is equal to negative zero (-0).

Checks whether a passed value is equal to 0 and if 1 divided by the value equals -Infinity.

const isNegativeZero = val => val === 0 && 1 / val === -Infinity;
-
isNegativeZero(-0); // true
-isNegativeZero(0); // 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
-

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
-

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.prototype.split(''), Array.prototype.reverse() and Array.prototype.map() in combination with parseInt() to obtain an array of digits. Use Array.prototype.splice(0,1) to obtain the last digit. Use Array.prototype.reduce() to implement the Luhn Algorithm. Return true if sum is divisible by 10, false otherwise.

const luhnCheck = num => {
-  let arr = (num + '')
-    .split('')
-    .reverse()
-    .map(x => parseInt(x));
-  let lastDigit = arr.splice(0, 1)[0];
-  let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0);
-  sum += lastDigit;
-  return sum % 10 === 0;
-};
-
luhnCheck('4485275742308327'); // true
-luhnCheck(6011329933655299); //  false
-luhnCheck(123456789); // false
-

mapNumRange

Maps a number from one range to another range.

Returns num mapped between outMin-outMax from inMin-inMax.

const mapNumRange = (num, inMin, inMax, outMin, outMax) =>
-  ((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
-
mapNumRange(5, 0, 10, 0, 100); // 50
-

Recommended Resource - JavaScript: From Fundamentals to Functional JS

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.

maxBy

Returns the maximum value of an array, after mapping each element to a value using the provided function.

Use Array.prototype.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.prototype.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
-

midpoint

Calculates the midpoint between two pairs of (x,y) points.

Destructure the array to get x1, y1, x2 and y2, calculate the midpoint for each dimension by dividing the sum of the two endpoints by 2.

const midpoint = ([x1, y1], [x2, y2]) => [(x1 + x2) / 2, (y1 + y2) / 2];
-
midpoint([2, 2], [4, 4]); // [3, 3]
-midpoint([4, 4], [6, 6]); // [5, 5]
-midpoint([1, 3], [2, 4]); // [1.5, 3.5]
-

minBy

Returns the minimum value of an array, after mapping each element to a value using the provided function.

Use Array.prototype.map() to map each element to the value returned by fn, Math.min() to get the minimum 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.prototype.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.prototype.reduce() combined with Array.prototype.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.prototype.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) =>
-  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.prototype.split('') and Array.prototype.reduce() to create a hash of the input string, utilizing bit shifting.

const sdbm = str => {
-  let arr = str.split('');
-  return arr.reduce(
-    (hashCode, currentVal) =>
-      (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode),
-    0
-  );
-};
-
sdbm('name'); // -3521204949
-

standardDeviation

Returns the standard deviation of an array of numbers.

Use Array.prototype.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], true); // 12.29899614287479 (population)
-

sum

Returns the sum of two or more numbers/arrays.

Use Array.prototype.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
-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.prototype.map() to map each element to the value returned by fn, Array.prototype.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 }], 'n'); // 20
-

sumPower

Returns the sum of the powers of all the numbers from start to end (both inclusive).

Use Array.prototype.fill() to create an array of all the numbers in the target range, Array.prototype.map() and the exponent operator (**) to raise them to power and Array.prototype.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, 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 =>
-  Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
-
toSafeInteger('3.2'); // 3
-toSafeInteger(Infinity); // 9007199254740991
-

vectorDistance

Returns the distance between two vectors.

Use Array.prototype.reduce(), Math.pow() and Math.sqrt() to calculate the Euclidean distance between two vectors.

const vectorDistance = (...coords) => {
-  let pointLength = Math.trunc(coords.length / 2);
-  let sum = coords
-    .slice(0, pointLength)
-    .reduce((acc, val, i) => acc + Math.pow(val - coords[pointLength + i], 2), 0);
-  return Math.sqrt(sum);
-};
-
vectorDistance(10, 0, 5, 20, 0, 10); // 11.180339887498949
-
\ No newline at end of file diff --git a/docs/node.html b/docs/node.html deleted file mode 100644 index 67d2f6569..000000000 --- a/docs/node.html +++ /dev/null @@ -1,203 +0,0 @@ -Node - 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 => Buffer.from(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 => Buffer.from(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) => ({
-  black: `\x1b[30m${args.join(' ')}`,
-  red: `\x1b[31m${args.join(' ')}`,
-  green: `\x1b[32m${args.join(' ')}`,
-  yellow: `\x1b[33m${args.join(' ')}`,
-  blue: `\x1b[34m${args.join(' ')}`,
-  magenta: `\x1b[35m${args.join(' ')}`,
-  cyan: `\x1b[36m${args.join(' ')}`,
-  white: `\x1b[37m${args.join(' ')}`,
-  bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`,
-  bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`,
-  bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`,
-  bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`,
-  bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`,
-  bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`,
-  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', '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)
-

createDirIfNotExists

Creates a directory, if it does not exist.

Use fs.existsSync() to check if the directory exists, fs.mkdirSync() to create it.

const fs = require('fs');
-const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
-
createDirIfNotExists('test'); // creates the directory 'test', if it doesn't exist
-

hasFlags

Check if the current process's arguments contain the specified flags.

Use Array.prototype.every() and Array.prototype.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
-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, setTimeout to prevent blocking on a long operation, and a Promise to give it a familiar interface.

const crypto = require('crypto');
-const hashNode = val =>
-  new Promise(resolve =>
-    setTimeout(
-      () =>
-        resolve(
-          crypto
-            .createHash('sha256')
-            .update(val)
-            .digest('hex')
-        ),
-      0
-    )
-  );
-
hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
-

isDuplexStream

Checks if the given argument is a duplex (readable and writable) stream.

Check if the value is different from null, use typeof to check if a value is of type object and the pipe property is of type function. Additionally check if the typeof the _read, _write and _readableState, _writableState properties are function and object respectively.

const isDuplexStream = val =>
-  val !== null &&
-  typeof val === 'object' &&
-  typeof val.pipe === 'function' &&
-  typeof val._read === 'function' &&
-  typeof val._readableState === 'object' &&
-  typeof val._write === 'function' &&
-  typeof val._writableState === 'object';
-
const Stream = require('stream');
-isDuplexStream(new Stream.Duplex()); // true
-

isReadableStream

Checks if the given argument is a readable stream.

Check if the value is different from null, use typeof to check if the value is of type object and the pipe property is of type function. Additionally check if the typeof the _read and _readableState properties are function and object respectively.

const isReadableStream = val =>
-  val !== null &&
-  typeof val === 'object' &&
-  typeof val.pipe === 'function' &&
-  typeof val._read === 'function' &&
-  typeof val._readableState === 'object';
-
const fs = require('fs');
-isReadableStream(fs.createReadStream('test.txt')); // true
-

isStream

Checks if the given argument is a stream.

Check if the value is different from null, use typeof to check if the value is of type object and the pipe property is of type function.

const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function';
-
const fs = require('fs');
-isStream(fs.createReadStream('test.txt')); // true
-

Recommended Resource - JavaScript: The Hard Parts

Take your JavaScript to the next level. Gain an understanding of callbacks, higher order functions, closure, asynchronous and object-oriented JavaScript!

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

isWritableStream

Checks if the given argument is a writable stream.

Check if the value is different from null, use typeof to check if the value is of type object and the pipe property is of type function. Additionally check if the typeof the _write and _writableState properties are function and object respectively.

const isWritableStream = val =>
-  val !== null &&
-  typeof val === 'object' &&
-  typeof val.pipe === 'function' &&
-  typeof val._write === 'function' &&
-  typeof val._writableState === 'object';
-
const fs = require('fs');
-isWritableStream(fs.createWriteStream('test.txt')); // true
-

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');
-const readFileLines = filename =>
-  fs
-    .readFileSync(filename)
-    .toString('UTF8')
-    .split('\n');
-
/*
-contents of test.txt :
-  line1
-  line2
-  line3
-  ___________________________
-*/
-let arr = readFileLines('test.txt');
-console.log(arr); // ['line1', 'line2', 'line3']
-

untildify

Converts a tilde path to an absolute path.

Use String.prototype.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');
-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 diff --git a/docs/object.html b/docs/object.html deleted file mode 100644 index 2d0b97d91..000000000 --- a/docs/object.html +++ /dev/null @@ -1,442 +0,0 @@ -Object - 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.prototype.forEach() to return a function that uses Function.prototype.apply() to apply the given context (obj) to fn for each function specified.

const bindAll = (obj, ...fns) =>
-  fns.forEach(
-    fn => (
-      (f = obj[fn]),
-      (obj[fn] = function() {
-        return f.apply(obj);
-      })
-    )
-  );
-
var view = {
-  label: 'docs',
-  click: function() {
-    console.log('clicked ' + this.label);
-  }
-};
-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.prototype.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) && obj.length
-    ? (clone.length = obj.length) && Array.from(clone)
-    : Array.isArray(obj)
-      ? Array.from(obj)
-      : clone;
-};
-
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 =>
-  Object.keys(obj).forEach(
-    prop =>
-      !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
-  ) || Object.freeze(obj);
-
'use strict';
-
-const o = deepFreeze([1, [2, 3]]);
-
-o[0] = 3; // not allowed
-o[1][0] = 4; // not allowed as well
-

deepGet

Returns the target value in a nested JSON object, based on the keys array.

Compare the keys you want in the nested JSON object as an Array. Use Array.prototype.reduce() to get value from nested JSON object one by one. If the key exists in object, return target value, otherwise, return null.

const deepGet = (obj, keys) => keys.reduce((xs, x) => (xs && xs[x] ? xs[x] : null), obj);
-
let index = 2;
-const data = {
-  foo: {
-    foz: [1, 2, 3],
-    bar: {
-      baz: ['a', 'b', 'c']
-    }
-  }
-};
-deepGet(data, ['foo', 'foz', index]); // get 3
-deepGet(data, ['foo', 'bar', 'baz', 8, 'foz']); // null
-

deepMapKeys

Deep maps an object keys.

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

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

const deepMapKeys = (obj, f) =>
-  Array.isArray(obj)
-    ? obj.map(val => deepMapKeys(val, f))
-    : typeof obj === 'object'
-      ? Object.keys(obj).reduce((acc, current) => {
-        const val = obj[current];
-        acc[f(current)] =
-            val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);
-        return acc;
-      }, {})
-      : obj;
-
const obj = {
-  foo: '1',
-  nested: {
-    child: {
-      withArray: [
-        {
-          grandChild: ['hello']
-        }
-      ]
-    }
-  }
-};
-const upperKeysObj = deepMapKeys(obj, key => key.toUpperCase());
-/*
-{
-  "FOO":"1",
-  "NESTED":{
-    "CHILD":{
-      "WITHARRAY":[
-        {
-          "GRANDCHILD":[ 'hello' ]
-        }
-      ]
-    }
-  }
-}
-*/
-

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.prototype.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.prototype.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 = {
-  level1: {
-    level2: {
-      level3: 'some data'
-    }
-  }
-};
-dig(data, 'level3'); // 'some data'
-dig(data, 'level4'); // undefined
-

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.prototype.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;
-  if (a === null || a === undefined || b === null || b === undefined) return false;
-  if (a.prototype !== b.prototype) return false;
-  let keys = Object.keys(a);
-  if (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.prototype.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 },
-    pebbles: { age: 1, active: true }
-  },
-  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.prototype.reverse() to reverse their order and Array.prototype.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(
-  {
-    barney: { age: 36, active: true },
-    fred: { age: 40, active: false },
-    pebbles: { age: 1, active: true }
-  },
-  o => o['active']
-); // 'pebbles'
-

flattenObject

Flatten an object with the paths for keys.

Use recursion. Use Object.keys(obj) combined with Array.prototype.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.prototype.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.prototype.reverse() to reverse their order and Array.prototype.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.prototype.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() {
-  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.prototype.map() for each selector, String.prototype.replace() to replace square brackets with dots, String.prototype.split('.') to split each selector, Array.prototype.filter() to remove empty values and Array.prototype.reduce() to get the value indicated by it.

const get = (from, ...selectors) =>
-  [...selectors].map(s =>
-    s
-      .replace(/\[([^\[\]]*)\]/g, '.$1.')
-      .split('.')
-      .filter(t => t !== '')
-      .reduce((prev, cur) => prev && prev[cur], from)
-  );
-
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.prototype.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 }, 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.prototype.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 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.prototype.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.prototype.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 = {
-  fred: { user: 'fred', age: 40 },
-  pebbles: { user: 'pebbles', age: 1 }
-};
-mapValues(users, u => u.age); // { fred: 40, pebbles: 1 }
-

Recommended Resource - ES6: The Right Parts

Learn new ES6 JavaScript language features like arrow function, destructuring, generators & more to write cleaner and more productive, readable programs.

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.prototype.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({ 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.prototype.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);
-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.prototype.reduce() combined with Object.keys(obj) to iterate over all objects and keys. Use hasOwnProperty() and Array.prototype.concat() to append values for keys existing in multiple objects.

const merge = (...objs) =>
-  [...objs].reduce(
-    (acc, obj) =>
-      Object.keys(obj).reduce((a, k) => {
-        acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
-        return acc;
-      }, {}),
-    {}
-  );
-
const object = {
-  a: [{ x: 2 }, { y: 4 }],
-  b: 1
-};
-const other = {
-  a: { z: 3 },
-  b: [2, 3],
-  c: '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.prototype.filter() to filter the items where the id matches the link, then Array.prototype.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
-const comments = [
-  { id: 1, parent_id: null },
-  { id: 2, parent_id: 1 },
-  { id: 3, parent_id: 1 },
-  { id: 4, parent_id: 2 },
-  { id: 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.prototype.reduce() to create and combine key-value pairs.

const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), 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.prototype.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.prototype.filter() and Array.prototype.includes() to remove the provided keys. Use Array.prototype.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 falsy for. The function is invoked with two arguments: (value, key).

Use Object.keys(obj) and Array.prototype.filter()to remove the keys for which fn returns a truthy value. Use Array.prototype.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.prototype.sort(), Array.prototype.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) {
-        const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]];
-        acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
-      }
-      return acc;
-    }, 0)
-  );
-
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.prototype.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.prototype.filter()to remove the keys for which fn returns a falsy value. Use Array.prototype.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.prototype.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,
-      ...{ [keysMap[key] || key]: obj[key] }
-    }),
-    {}
-  );
-
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 };
-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 =>
-  Array.isArray(val)
-    ? val.length
-    : val && typeof val === 'object'
-      ? val.size || val.length || Object.keys(val).length
-      : typeof val === 'string'
-        ? new Blob([val]).size
-        : 0;
-
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.prototype.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);
-    return r;
-  },
-  {}
-); // { '1': ['a', 'c'], '2': ['b'] }
-

truthCheckCollection

Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).

Use Array.prototype.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
-

unflattenObject

Unflatten an object with the paths for keys.

Use Object.keys(obj) combined with Array.prototype.reduce() to convert flattened path node to a leaf node. If the value of a key contains a dot delimiter (.), use Array.prototype.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('.');
-      Object.assign(
-        acc,
-        JSON.parse(
-          '{' +
-            keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') +
-            obj[k] +
-            '}'.repeat(keys.length)
-        )
-      );
-    } else 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 diff --git a/docs/prism.js b/docs/prism.js deleted file mode 100644 index 7a6f93675..000000000 --- a/docs/prism.js +++ /dev/null @@ -1,5 +0,0 @@ -/* PrismJS 1.9.0 -http://prismjs.com/download.html?themes=prism&languages=clike+javascript */ -var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(){var e=/\blang(?:uage)?-(\w+)\b/i,t=0,n=_self.Prism={manual:_self.Prism&&_self.Prism.manual,disableWorkerMessageHandler:_self.Prism&&_self.Prism.disableWorkerMessageHandler,util:{encode:function(e){return e instanceof r?new r(e.type,n.util.encode(e.content),e.alias):"Array"===n.util.type(e)?e.map(n.util.encode):e.replace(/&/g,"&").replace(/e.length)return;if(!(w instanceof s)){h.lastIndex=0;var _=h.exec(w),P=1;if(!_&&m&&b!=t.length-1){if(h.lastIndex=k,_=h.exec(e),!_)break;for(var A=_.index+(d?_[1].length:0),j=_.index+_[0].length,x=b,O=k,N=t.length;N>x&&(j>O||!t[x].type&&!t[x-1].greedy);++x)O+=t[x].length,A>=O&&(++b,k=O);if(t[b]instanceof s||t[x-1].greedy)continue;P=x-b,w=e.slice(k,O),_.index-=k}if(_){d&&(p=_[1].length);var A=_.index+p,_=_[0].slice(p),j=A+_.length,S=w.slice(0,A),C=w.slice(j),M=[b,P];S&&(++b,k+=S.length,M.push(S));var E=new s(g,f?n.tokenize(_,f):_,y,_,m);if(M.push(E),C&&M.push(C),Array.prototype.splice.apply(t,M),1!=P&&n.matchGrammar(e,t,r,b,k,!0,g),i)break}else if(i)break}}}}},tokenize:function(e,t){var r=[e],a=t.rest;if(a){for(var l in a)t[l]=a[l];delete t.rest}return n.matchGrammar(e,r,t,0,0,!1),r},hooks:{all:{},add:function(e,t){var r=n.hooks.all;r[e]=r[e]||[],r[e].push(t)},run:function(e,t){var r=n.hooks.all[e];if(r&&r.length)for(var a,l=0;a=r[l++];)a(t)}}},r=n.Token=function(e,t,n,r,a){this.type=e,this.content=t,this.alias=n,this.length=0|(r||"").length,this.greedy=!!a};if(r.stringify=function(e,t,a){if("string"==typeof e)return e;if("Array"===n.util.type(e))return e.map(function(n){return r.stringify(n,t,e)}).join("");var l={type:e.type,content:r.stringify(e.content,t,a),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:a};if(e.alias){var i="Array"===n.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(l.classes,i)}n.hooks.run("wrap",l);var o=Object.keys(l.attributes).map(function(e){return e+'="'+(l.attributes[e]||"").replace(/"/g,""")+'"'}).join(" ");return"<"+l.tag+' class="'+l.classes.join(" ")+'"'+(o?" "+o:"")+">"+l.content+""},!_self.document)return _self.addEventListener?(n.disableWorkerMessageHandler||_self.addEventListener("message",function(e){var t=JSON.parse(e.data),r=t.language,a=t.code,l=t.immediateClose;_self.postMessage(n.highlight(a,n.languages[r],r)),l&&_self.close()},!1),_self.Prism):_self.Prism;var a=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return a&&(n.filename=a.src,n.manual||a.hasAttribute("data-manual")||("loading"!==document.readyState?window.requestAnimationFrame?window.requestAnimationFrame(n.highlightAll):window.setTimeout(n.highlightAll,16):document.addEventListener("DOMContentLoaded",n.highlightAll))),_self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism); -Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,"boolean":/\b(?:true|false)\b/,"function":/[a-z0-9_]+(?=\()/i,number:/\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i,operator:/--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,punctuation:/[{}[\];(),.:]/}; -Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,number:/\b-?(?:0[xX][\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+|\d*\.?\d+(?:[Ee][+-]?\d+)?|NaN|Infinity)\b/,"function":/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*\()/i,operator:/-[-=]?|\+[+=]?|!=?=?|<>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/}),Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^\/])\/(?!\/)(\[[^\]\r\n]+]|\\.|[^\/\\\[\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,lookbehind:!0,greedy:!0},"function-variable":{pattern:/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=\s*(?:function\b|(?:\([^()]*\)|[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/i,alias:"function"}}),Prism.languages.insertBefore("javascript","string",{"template-string":{pattern:/`(?:\\[\s\S]|[^\\`])*`/,greedy:!0,inside:{interpolation:{pattern:/\$\{[^}]+\}/,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}}}),Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/()[\s\S]*?(?=<\/script>)/i,lookbehind:!0,inside:Prism.languages.javascript,alias:"language-javascript",greedy:!0}}),Prism.languages.js=Prism.languages.javascript; diff --git a/docs/scss/style.scss b/docs/scss/style.scss deleted file mode 100644 index 19b523071..000000000 --- a/docs/scss/style.scss +++ /dev/null @@ -1,971 +0,0 @@ -$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; -$card-page-back-color-var: '--card-page-back-color'; -$card-page-back-color: #eee; -$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; - -// 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; - #{$card-page-back-color-var}: $card-page-back-color; - #{$border-color-var}: $border-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; - &.card-page { - background: var(#{$card-page-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; -} -// 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; - white-space: pre-wrap; -} - -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; - } -} -// 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}); - padding-top: 5rem; - margin-top: -4.25rem; - } - &.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})); - margin-left: calc(1.5 * var(#{$universal-margin-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 { - margin-left: calc(1.5 * var(#{$universal-margin-var})); - 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; - padding-top: calc(3 * var(--universal-padding)); - } - &.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: 4rem; - height: 2rem; - 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: 6.5rem; - left: -320px; - width: 320px; - transition: left 0.3s ease; - z-index: 1100; - height: calc(100vh - 6.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: 0; - padding: calc(2.5 * var(#{$universal-padding-var})) calc(2 * var(#{$universal-padding-var})) calc(1 * var(#{$universal-padding-var})) calc(1 * var(#{$universal-padding-var})); - color: var(#{$nav-fore-color-var}); - font-size: 1.5rem; - &.collapse { - display: block; - 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-chevron-down'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); - //background-position: 0rem 1.25rem; - background-position: right 0.5rem top 1.5rem; - background-repeat: no-repeat; - + ul { - 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='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-chevron-up'%3E%3Cpolyline points='18 15 12 9 6 15'%3E%3C/polyline%3E%3C/svg%3E"); - padding-bottom: calc(0.125 * var(#{$universal-padding-var})); - + ul { - position: relative; - transform: scaleY(1); - } - } - } - + h4 { - border-top: $__1px solid var(#{$nav-link-border-color-var}); - } - > a { - display: block; - line-height: 1; - &:hover, &:focus { - text-decoration: none; - } - } - } - ul { - width: 100%; - margin-left: -0.75rem; - background: var(#{$nav-back-color-var}); - + h4 { - border-top: $__1px solid var(#{$nav-link-border-color-var}); - } - } - li { - margin: calc(0.5 * var(#{$universal-margin-var})); - margin-left: var(#{$universal-margin-var}); - margin-bottom: 0; - border-left: $__1px solid var(#{$nav-link-border-color-var}); - &:hover { - text-decoration: none; - background: var(#{$nav-link-hover-color-var}); - } - + li { - margin-top: 0; - } - } - a { - display: block; - padding: calc(2 * var(#{$universal-padding-var})) calc(1.5 * var(#{$universal-padding-var})); - &:link, &:visited { - color: var(#{$nav-link-fore-color-var}); - } - } - button.social { - width: 33.333%; - margin: 0; - border: 0; - border-radius: 0; - box-sizing: border-box; - height: 4rem; - background-position: center center; - background-repeat: no-repeat; - cursor: pointer; - &.fb { - 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='%23f0f0f0' stroke='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-facebook'%3E%3Cpath d='M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z'%3E%3C/path%3E%3C/svg%3E"); - background-color: #1565c0; - } - &.instagram { - 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-instagram'%3E%3Crect x='2' y='2' width='20' height='20' rx='5' ry='5'%3E%3C/rect%3E%3Cpath d='M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z'%3E%3C/path%3E%3Cline x1='17.5' y1='6.5' x2='17.5' y2='6.5'%3E%3C/line%3E%3C/svg%3E"); - background-color: #ec407a; - } - &.twitter { - 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='%23f0f0f0' stroke='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-twitter'%3E%3Cpath d='M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z'%3E%3C/path%3E%3C/svg%3E"); - background-color: #03a9f4; - } - } -} - -[type="search"] { - z-index: 1000; - position: fixed; - top: 3.5rem; - height: 3rem; - left: -320px; - width: 320px; - 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}); - 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; - @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; - } - } - } - &:hover, &:focus { - border-bottom: $__1px solid var(#{$search-hover-border-color-var}); - } - &:focus { - 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), inset 0 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; - outline: none; - 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.375rem; - 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; - } - } -} diff --git a/docs/sponsors/DO_Logo_icon_blue.svg b/docs/sponsors/DO_Logo_icon_blue.svg deleted file mode 100644 index e48c2351f..000000000 --- a/docs/sponsors/DO_Logo_icon_blue.svg +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/string.html b/docs/string.html deleted file mode 100644 index c90f504f6..000000000 --- a/docs/string.html +++ /dev/null @@ -1,312 +0,0 @@ -String - 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
-byteSize('Hello World'); // 11
-

capitalize

Capitalizes the first letter of a string.

Use array destructuring and String.prototype.toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.prototype.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', true); // 'Foobar'
-

capitalizeEveryWord

Capitalizes the first letter of every word in a string.

Use String.prototype.replace() to match the first character of each word and String.prototype.toUpperCase() to capitalize it.

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
-
capitalizeEveryWord('hello world!'); // 'Hello World!'
-

compactWhitespace

Returns a string with whitespaces compacted.

Use String.prototype.replace() with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space.

const compactWhitespace = str => str.replace(/\s{2,}/g, ' ');
-
compactWhitespace('Lorem    Ipsum'); // 'Lorem Ipsum'
-compactWhitespace('Lorem \n Ipsum'); // 'Lorem Ipsum'
-

CSVToArray

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

Use Array.prototype.slice() and Array.prototype.indexOf('\n') to remove the first row (title row) if omitFirstRow is true. Use String.prototype.split('\n') to create a string for each row, then String.prototype.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('col1,col2\na,b\nc,d', ',', true); // [['a','b'],['c','d']];
-

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.prototype.slice() and Array.prototype.indexOf('\n') and String.prototype.split(delimiter) to separate the first row (title row) into values. Use String.prototype.split('\n') to create a string for each row, then Array.prototype.map() and String.prototype.split(delimiter) to separate the values in each row. Use Array.prototype.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)
-    .split('\n')
-    .map(v => {
-      const values = v.split(delimiter);
-      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'}];
-

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.prototype.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', true); // 'fOOBAR'
-

escapeHTML

Escapes a string for use in HTML.

Use String.prototype.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 =>
-      ({
-        '&': '&amp;',
-        '<': '&lt;',
-        '>': '&gt;',
-        "'": '&#39;',
-        '"': '&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.prototype.replace() to escape special characters.

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-
escapeRegExp('(test)'); // \\(test\\)
-

fromCamelCase

Converts a string from camelcase.

Use String.prototype.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('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'
-fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
-

indentString

Indents each line in the provided string.

Use String.replace and a regular expression to add the character specified by indent count times at the start of each line. Omit the third parameter, indent, to use a default indentation character of ' '.

const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count));
-
indentString('Lorem\nIpsum', 2); // '  Lorem\n  Ipsum'
-indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum'
-

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.prototype.replace() with an appropriate regular expression to remove unnecessary characters, String.prototype.split(''), Array.prototype.sort() and Array.prototype.join('') on both strings to normalize them, then check if their normalized forms are equal.

const isAnagram = (str1, str2) => {
-  const normalize = str =>
-    str
-      .toLowerCase()
-      .replace(/[^a-z0-9]/gi, '')
-      .split('')
-      .sort()
-      .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
-isLowerCase('a3@$'); // true
-isLowerCase('Ab4'); // false
-

isUpperCase

Checks if a string is upper case.

Convert the given string to upper case, using String.prototype.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.prototype.split('') and Array.prototype.map() to call the provided function, fn, for each character in str. Use Array.prototype.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.prototype.slice() to grab the portion of the characters that will remain unmasked and use String.padStart() to fill the beginning of the string with the mask character up to the original length. 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(-num).padStart(`${cc}`.length, mask);
-
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 = ' ') =>
-  str.padStart((str.length + length) / 2, char).padEnd(length, char);
-
pad('cat', 8); // '  cat   '
-pad(String(42), 6, '0'); // '004200'
-pad('foobar', 3); // 'foobar'
-

Recommended Resource - JavaScript: From Fundamentals to Functional JS

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.

palindrome

Returns true if the given string is a palindrome, false otherwise.

Convert the string to String.prototype.toLowerCase() and use String.prototype.replace() to remove non-alphanumeric characters from it. Then, use the spread operator (...) to split the string into individual characters, Array.prototype.reverse(), String.prototype.join('') and compare it to the original, unreversed string, after converting it to String.prototype.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') => {
-  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(1, 'apple'); // 'apple'
-pluralize(2, 'apple'); // 'apples'
-pluralize(2, 'person', 'people'); // 'people'
-
-const PLURALS = {
-  person: 'people',
-  radius: 'radii'
-};
-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.prototype.reverse() to reverse the order of the characters in the string. Combine characters to get a string using String.prototype.join('').

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

sortCharactersInString

Alphabetically sorts the characters in a string.

Use the spread operator (...), Array.prototype.sort() and String.localeCompare() to sort the characters in str, recombine using String.prototype.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.prototype.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.prototype.map() to combine the letter with each partial permutation, then Array.prototype.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('')
-    .reduce(
-      (acc, letter, i) =>
-        acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),
-      []
-    );
-};
-
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 => {
-  let s =
-    str &&
-    str
-      .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
-      .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
-      .join('');
-  return s.slice(0, 1).toLowerCase() + s.slice(1);
-};
-
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 =>
-  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('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 =>
-  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('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"
-

toTitleCase

Converts a string to title case.

Break the string into words, using a regexp, and combine them capitalizing the first letter of each word and adding a whitespace between them.

const toTitleCase = 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.charAt(0).toUpperCase() + x.slice(1))
-    .join(' ');
-
toTitleCase('some_database_field_name'); // 'Some Database Field Name'
-toTitleCase('Some label that needs to be title-cased'); // 'Some Label That Needs To Be Title Cased'
-toTitleCase('some-package-name'); // 'Some Package Name'
-toTitleCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'Some Mixed String With Spaces Underscores And Hyphens'
-

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.prototype.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 =>
-      ({
-        '&amp;': '&',
-        '&lt;': '<',
-        '&gt;': '>',
-        '&#39;': "'",
-        '&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.prototype.join('/') to combine URL segments, then a series of String.prototype.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, '/')
-    .replace(/^(.+):\//, '$1://')
-    .replace(/^file:/, 'file:/')
-    .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.prototype.split() with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use Array.prototype.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 diff --git a/docs/style.css b/docs/style.css deleted file mode 100644 index 369a595e0..000000000 --- a/docs/style.css +++ /dev/null @@ -1 +0,0 @@ -@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;--card-page-back-color:#eee;--border-color:#eee;--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}body.card-page{background:var(--card-page-back-color)}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;white-space:pre-wrap}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}.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);padding-top:5rem;margin-top:-4.25rem}.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));margin-left:calc(1.5 * var(--universal-margin));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{margin-left:calc(1.5 * var(--universal-margin));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;padding-top:calc(3 * var(--universal-padding))}.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:4rem;height:2rem;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:6.5rem;left:-320px;width:320px;transition:left 0.3s ease;z-index:1100;height:calc(100vh - 6.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:0;padding:calc(2.5 * var(--universal-padding)) calc(2 * var(--universal-padding)) calc(1 * var(--universal-padding)) calc(1 * var(--universal-padding));color:var(--nav-fore-color);font-size:1.5rem}nav h4.collapse{display:block;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-chevron-down'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");background-position:right 0.5rem top 1.5rem;background-repeat:no-repeat}nav h4.collapse+ul{position:absolute;transform:scaleY(0);transform-origin:top;transition:transform 0.3s ease}nav h4.collapse.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='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-chevron-up'%3E%3Cpolyline points='18 15 12 9 6 15'%3E%3C/polyline%3E%3C/svg%3E");padding-bottom:calc(0.125 * var(--universal-padding))}nav h4.collapse.toggled+ul{position:relative;transform:scaleY(1)}nav h4+h4{border-top:.0625rem solid var(--nav-link-border-color)}nav h4>a{display:block;line-height:1}nav h4>a:hover,nav h4>a:focus{text-decoration:none}nav ul{width:100%;margin-left:-0.75rem;background:var(--nav-back-color)}nav ul+h4{border-top:.0625rem solid var(--nav-link-border-color)}nav li{margin:calc(0.5 * var(--universal-margin));margin-left:var(--universal-margin);margin-bottom:0;border-left:.0625rem solid var(--nav-link-border-color)}nav li:hover{text-decoration:none;background:var(--nav-link-hover-color)}nav li+li{margin-top:0}nav a{display:block;padding:calc(2 * var(--universal-padding)) calc(1.5 * var(--universal-padding))}nav a:link,nav a:visited{color:var(--nav-link-fore-color)}nav button.social{width:33.333%;margin:0;border:0;border-radius:0;box-sizing:border-box;height:4rem;background-position:center center;background-repeat:no-repeat;cursor:pointer}nav button.social.fb{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='%23f0f0f0' stroke='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-facebook'%3E%3Cpath d='M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z'%3E%3C/path%3E%3C/svg%3E");background-color:#1565c0}nav button.social.instagram{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-instagram'%3E%3Crect x='2' y='2' width='20' height='20' rx='5' ry='5'%3E%3C/rect%3E%3Cpath d='M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z'%3E%3C/path%3E%3Cline x1='17.5' y1='6.5' x2='17.5' y2='6.5'%3E%3C/line%3E%3C/svg%3E");background-color:#ec407a}nav button.social.twitter{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='%23f0f0f0' stroke='%23f0f0f0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-twitter'%3E%3Cpath d='M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z'%3E%3C/path%3E%3C/svg%3E");background-color:#03a9f4}[type="search"]{z-index:1000;position:fixed;top:3.5rem;height:3rem;left:-320px;width:320px;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);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}@media screen and (max-width: 320px){[type="search"]{width:100%}}@media screen and (min-width: 768px){[type="search"]{width:33vw;left:-33vw}}@media screen and (min-width: 1280px){[type="search"]{width:25vw;left:-25vw}}[type="search"].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){[type="search"].col-nav+main.col-centered,[type="search"].col-nav+main.col-centered+footer.col-full-width{grid-column:5/13}}@media screen and (min-width: 1280px){[type="search"].col-nav+main.col-centered{grid-column:4/12;padding-left:8vw}[type="search"].col-nav+main.col-centered+footer.col-full-width{grid-column:4/13}}[type="search"]:hover,[type="search"]:focus{border-bottom:.0625rem solid var(--search-hover-border-color)}[type="search"]:focus{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),inset 0 -.0625rem 0 0 var(--search-hover-border-color)}.menu-button{position:fixed;top:0;left:0;z-index:1000;box-sizing:border-box;outline:none;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.375rem;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 deleted file mode 100644 index 884a97704..000000000 --- a/docs/type.html +++ /dev/null @@ -1,191 +0,0 @@ -Type - 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 =>
-  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.prototype.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
-is(Set, new Set()); // true
-is(WeakMap, new WeakMap()); // true
-is(WeakSet, new WeakSet()); // true
-is(String, ''); // true
-is(String, new String('')); // true
-is(Number, 1); // true
-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
-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
-isBoolean(false); // true
-

isEmpty

Returns true if the a value is an empty object, collection, 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([]); // true
-isEmpty({}); // true
-isEmpty(''); // true
-isEmpty([1, 2]); // false
-isEmpty({ a: 1, b: 2 }); // false
-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
-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
-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. To safeguard against NaN, check if val === val (as NaN has a typeof equal to number and is the only value not equal to itself).

const isNumber = val => typeof val === 'number' && val === val;
-
isNumber(1); // true
-isNumber('1'); // false
-isNumber(NaN); // false
-

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
-

Recommended Resource - JavaScript: From Fundamentals to Functional JS

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.

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
-isPlainObject(new Map()); // false
-

isPrimitive

Returns a boolean determining if the passed value is primitive or not.

Create an object from val and compare it with val to determine if the passed value is primitive (i.e. not equal to the created object).

const isPrimitive = val => Object(val) !== val;
-
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 =>
-  obj !== null &&
-  (typeof obj === 'object' || typeof obj === 'function') &&
-  typeof obj.then === 'function';
-
isPromiseLike({
-  then: function() {
-    return '';
-  }
-}); // true
-isPromiseLike(null); // false
-isPromiseLike({}); // false
-

isString

Checks if the given argument is a string. Only works for string primitives.

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 string is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided string is a valid JSON.

const isValidJSON = str => {
-  try {
-    JSON.parse(str);
-    return true;
-  } catch (e) {
-    return false;
-  }
-};
-
isValidJSON('{"name":"Adam","age":20}'); // true
-isValidJSON('{"name":"Adam",age:"20"}'); // false
-isValidJSON(null); // true
-
\ No newline at end of file diff --git a/docs/uncategorized.html b/docs/uncategorized.html deleted file mode 100644 index 8448fb252..000000000 --- a/docs/uncategorized.html +++ /dev/null @@ -1,78 +0,0 @@ -Uncategorized - 30 seconds of code

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



Uncategorized

pipeLog

Use console.log in a pipeline as this function simply encloses it and returns the passed value. This is especially useful for debugging when you want to log a variable's value before its usage.

Logs a value and returns it.

const pipeLog = data => console.log(data) || data;
-
pipeLog(1); // logs `1` and returns `1`
-
\ No newline at end of file diff --git a/docs/utility.html b/docs/utility.html deleted file mode 100644 index 8abdcda06..000000000 --- a/docs/utility.html +++ /dev/null @@ -1,289 +0,0 @@ -Utility - 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.prototype.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;
-const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi
-

coalesce

Returns the first non-null/undefined argument.

Use Array.prototype.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.prototype.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.prototype.map(), String.prototype.split() and Array.prototype.join() to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form. Array.prototype.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('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.prototype.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('google.com'); // {}
-

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('');
-  else if (h.length === 8) alpha = true;
-  h = parseInt(h, 16);
-  return (
-    'rgb' +
-    (alpha ? 'a' : '') +
-    '(' +
-    (h >>> (alpha ? 24 : 16)) +
-    ', ' +
-    ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) +
-    ', ' +
-    ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
-    (alpha ? `, ${h & 0x000000ff}` : '') +
-    ')'
-  );
-};
-
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) => {
-  const request = new XMLHttpRequest();
-  request.open('GET', url, true);
-  request.onload = () => callback(request.responseText);
-  request.onerror = () => err(request);
-  request.send();
-};
-
httpGet(
-  'https://jsonplaceholder.typicode.com/posts/1',
-  console.log
-); /*
-Logs: {
-  "userId": 1,
-  "id": 1,
-  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
-  "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) => {
-  const request = new XMLHttpRequest();
-  request.open('POST', url, true);
-  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
-  request.onload = () => callback(request.responseText);
-  request.onerror = () => err(request);
-  request.send(data);
-};
-
const newPost = {
-  userId: 1,
-  id: 1337,
-  title: 'Foo',
-  body: 'bar bar bar'
-};
-const data = JSON.stringify(newPost);
-httpPost(
-  'https://jsonplaceholder.typicode.com/posts',
-  data,
-  console.log
-); /*
-Logs: {
-  "userId": 1,
-  "id": 1337,
-  "title": "Foo",
-  "body": "bar bar bar"
-}
-*/
-httpPost(
-  'https://jsonplaceholder.typicode.com/posts',
-  null, // does not send a body
-  console.log
-); /*
-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.prototype.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.prototype.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();
-    return performance.now() - before;
-  });
-  return times.indexOf(Math.min(...times));
-};
-
mostPerformant([
-  () => {
-    // Loops through the entire array before returning `false`
-    [1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number');
-  },
-  () => {
-    // Only needs to reach index `1` before returning false
-    [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.prototype.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.prototype.split(';') to separate key-value pairs from each other. Use Array.prototype.map() and String.prototype.split('=') to separate keys from values in each pair. Use Array.prototype.reduce() and decodeURIComponent() to create an object with all key-value pairs.

const parseCookie = str =>
-  str
-    .split(';')
-    .map(v => v.split('='))
-    .reduce((acc, v) => {
-      acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
-      return acc;
-    }, {});
-
parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' }
-

Recommended Resource - JavaScript: From Fundamentals to Functional JS

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.

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(-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 = () => {
-  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 => {
-  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) =>
-  Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
-
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 => {
-  const int = parseInt(num),
-    digits = [int % 10, int % 100],
-    ordinals = ['st', 'nd', 'rd', 'th'],
-    oPattern = [1, 2, 3, 4],
-    tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
-  return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])
-    ? 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) =>
-  /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;
-
yesNo('Y'); // true
-yesNo('yes'); // true
-yesNo('No'); // false
-yesNo('Foo', true); // true
-
\ No newline at end of file diff --git a/scripts/extract.js b/scripts/extract.js index 3cc0b43c1..78657498c 100644 --- a/scripts/extract.js +++ b/scripts/extract.js @@ -62,6 +62,7 @@ const completeData = { meta: { specification: 'http://jsonapi.org/format/', type: 'snippetArray', + scope: SNIPPETS_PATH, }, }; const listingData = { @@ -80,6 +81,7 @@ const listingData = { meta: { specification: 'http://jsonapi.org/format/', type: 'snippetListingArray', + scope: SNIPPETS_PATH, }, }; @@ -88,6 +90,7 @@ const archiveCompleteData = { meta: { specification: 'http://jsonapi.org/format/', type: 'snippetArray', + scope: SNIPPETS_ARCHIVE_PATH, } }; const archiveListingData = { @@ -106,6 +109,7 @@ const archiveListingData = { meta: { specification: 'http://jsonapi.org/format/', type: 'snippetListingArray', + scope: SNIPPETS_ARCHIVE_PATH, }, }; @@ -125,6 +129,7 @@ const glossaryData = { meta: { specification: 'http://jsonapi.org/format/', type: 'glossaryTermArray', + scope: GLOSSARY_PATH, }, }; diff --git a/snippet_data/archivedSnippetList.json b/snippet_data/archivedSnippetList.json index 1ff27b823..7e3a92657 100644 --- a/snippet_data/archivedSnippetList.json +++ b/snippet_data/archivedSnippetList.json @@ -380,6 +380,7 @@ ], "meta": { "specification": "http://jsonapi.org/format/", - "type": "snippetListingArray" + "type": "snippetListingArray", + "scope": "./snippets_archive" } } \ No newline at end of file diff --git a/snippet_data/archivedSnippets.json b/snippet_data/archivedSnippets.json index 3682eddb4..9fd5cface 100644 --- a/snippet_data/archivedSnippets.json +++ b/snippet_data/archivedSnippets.json @@ -530,6 +530,7 @@ ], "meta": { "specification": "http://jsonapi.org/format/", - "type": "snippetArray" + "type": "snippetArray", + "scope": "./snippets_archive" } } \ No newline at end of file diff --git a/snippet_data/glossaryTerms.json b/snippet_data/glossaryTerms.json index 641422af1..215d861da 100644 --- a/snippet_data/glossaryTerms.json +++ b/snippet_data/glossaryTerms.json @@ -1389,6 +1389,7 @@ ], "meta": { "specification": "http://jsonapi.org/format/", - "type": "glossaryTermArray" + "type": "glossaryTermArray", + "scope": "./glossary" } } \ No newline at end of file diff --git a/snippet_data/snippetList.json b/snippet_data/snippetList.json index 385251184..647c1554c 100644 --- a/snippet_data/snippetList.json +++ b/snippet_data/snippetList.json @@ -5537,6 +5537,7 @@ ], "meta": { "specification": "http://jsonapi.org/format/", - "type": "snippetListingArray" + "type": "snippetListingArray", + "scope": "./snippets" } } \ No newline at end of file diff --git a/snippet_data/snippets.json b/snippet_data/snippets.json index 35e2a0ba3..3f3219066 100644 --- a/snippet_data/snippets.json +++ b/snippet_data/snippets.json @@ -2055,7 +2055,7 @@ "text": "Encode a set of form elements as an `object`.\n\nUse the `FormData` constructor to convert the HTML `form` to `FormData`, `Array.from()` to convert to an array.\nCollect the object from the array, using `Array.prototype.reduce()`.\n\n", "codeBlocks": { "es6": "const formToObject = form =>\n Array.from(new FormData(form)).reduce(\n (acc, [key, value]) => ({\n ...acc,\n [key]: value\n }),\n {}\n );", - "es5": "function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar formToObject = function formToObject(form) {\n return Array.from(new FormData(form)).reduce(function (acc, _ref) {\n var _ref2 = _slicedToArray(_ref, 2),\n key = _ref2[0],\n value = _ref2[1];\n\n return _objectSpread2({}, acc, _defineProperty({}, key, value));\n }, {});\n};", + "es5": "function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar formToObject = function formToObject(form) {\n return Array.from(new FormData(form)).reduce(function (acc, _ref) {\n var _ref2 = _slicedToArray(_ref, 2),\n key = _ref2[0],\n value = _ref2[1];\n\n return _objectSpread({}, acc, _defineProperty({}, key, value));\n }, {});\n};", "example": "formToObject(document.querySelector('#form')); // { email: 'test@email.com', name: 'Test Name' }" }, "tags": [ @@ -4481,7 +4481,7 @@ "text": "Given a flat array of objects linked to one another, it will nest them recursively.\nUseful for nesting comments, such as the ones on reddit.com.\n\nUse recursion.\nUse `Array.prototype.filter()` to filter the items where the `id` matches the `link`, then `Array.prototype.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.\nOmit 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).\nOmit the third argument, `link`, to use `'parent_id'` as the default property which links the object to another one by its `id`.\n\n", "codeBlocks": { "es6": "const nest = (items, id = null, link = 'parent_id') =>\n items\n .filter(item => item[link] === id)\n .map(item => ({ ...item, children: nest(items, item.id) }));", - "es5": "function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar nest = function nest(items) {\n var id = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n var link = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'parent_id';\n return items.filter(function (item) {\n return item[link] === id;\n }).map(function (item) {\n return _objectSpread2({}, item, {\n children: nest(items, item.id)\n });\n });\n};", + "es5": "function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar nest = function nest(items) {\n var id = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n var link = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'parent_id';\n return items.filter(function (item) {\n return item[link] === id;\n }).map(function (item) {\n return _objectSpread({}, item, {\n children: nest(items, item.id)\n });\n });\n};", "example": "// One top level comment\nconst comments = [\n { id: 1, parent_id: null },\n { id: 2, parent_id: 1 },\n { id: 3, parent_id: 1 },\n { id: 4, parent_id: 2 },\n { id: 5, parent_id: 4 }\n];\nconst nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]" }, "tags": [ @@ -5683,7 +5683,7 @@ "text": "Replaces the names of multiple object keys with the values provided.\n\nUse `Object.keys()` in combination with `Array.prototype.reduce()` and the spread operator (`...`) to get the object's keys and rename them according to `keysMap`.\n\n", "codeBlocks": { "es6": "const renameKeys = (keysMap, obj) =>\n Object.keys(obj).reduce(\n (acc, key) => ({\n ...acc,\n ...{ [keysMap[key] || key]: obj[key] }\n }),\n {}\n );", - "es5": "function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar renameKeys = function renameKeys(keysMap, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n return _objectSpread2({}, acc, {}, _defineProperty({}, keysMap[key] || key, obj[key]));\n }, {});\n};", + "es5": "function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar renameKeys = function renameKeys(keysMap, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n return _objectSpread({}, acc, {}, _defineProperty({}, keysMap[key] || key, obj[key]));\n }, {});\n};", "example": "const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };\nrenameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }" }, "tags": [ @@ -7637,6 +7637,7 @@ ], "meta": { "specification": "http://jsonapi.org/format/", - "type": "snippetArray" + "type": "snippetArray", + "scope": "./snippets" } } \ No newline at end of file diff --git a/sponsored_by_DigitalOcean.png b/sponsored_by_DigitalOcean.png deleted file mode 100644 index 65fb1e134..000000000 Binary files a/sponsored_by_DigitalOcean.png and /dev/null differ diff --git a/src/docs/components/Meta.js b/src/docs/components/Meta.js new file mode 100644 index 000000000..c077739e6 --- /dev/null +++ b/src/docs/components/Meta.js @@ -0,0 +1,78 @@ +import React from 'react'; +import Helmet from 'react-helmet'; +import { useStaticQuery, graphql } from 'gatsby'; +import '../styles/index.scss'; + +// =================================================== +// Page metadata (using Helmet) +// =================================================== +const Meta = ({ description = '', lang = 'en', meta = [], title }) => { + const { site, file } = useStaticQuery( + graphql` + query { + site { + siteMetadata { + title + description + author + } + } + file(relativePath: { eq: "logo.png" }) { + id + childImageSharp { + fluid(maxHeight: 400) { + src + } + } + } + } + `, + ); + + const metaDescription = description || site.siteMetadata.description; + + return ( + + ); +}; + +export default Meta; diff --git a/src/docs/components/SVGs/BackArrowIcon.js b/src/docs/components/SVGs/BackArrowIcon.js new file mode 100644 index 000000000..789edf859 --- /dev/null +++ b/src/docs/components/SVGs/BackArrowIcon.js @@ -0,0 +1,22 @@ +import React from 'react'; + +const BackArrowIcon = ({ className, onClick }) => ( + + + + +); + +export default BackArrowIcon; diff --git a/src/docs/components/SVGs/ClipboardIcon.js b/src/docs/components/SVGs/ClipboardIcon.js new file mode 100644 index 000000000..e57f84b37 --- /dev/null +++ b/src/docs/components/SVGs/ClipboardIcon.js @@ -0,0 +1,22 @@ +import React from 'react'; + +const ClipboardIcon = ({ className, onClick }) => ( + + + + +); + +export default ClipboardIcon; diff --git a/src/docs/components/SVGs/CollapseClosedIcon.js b/src/docs/components/SVGs/CollapseClosedIcon.js new file mode 100644 index 000000000..a72270988 --- /dev/null +++ b/src/docs/components/SVGs/CollapseClosedIcon.js @@ -0,0 +1,23 @@ +import React from 'react'; + +const CollapseClosedIcon = ({ className, onClick }) => ( + + + + + +); + +export default CollapseClosedIcon; diff --git a/src/docs/components/SVGs/CollapseOpenIcon.js b/src/docs/components/SVGs/CollapseOpenIcon.js new file mode 100644 index 000000000..bcd04cb22 --- /dev/null +++ b/src/docs/components/SVGs/CollapseOpenIcon.js @@ -0,0 +1,22 @@ +import React from 'react'; + +const CollapseOpenIcon = ({ className, onClick }) => ( + + + + +); + +export default CollapseOpenIcon; diff --git a/src/docs/components/SVGs/DarkModeIcon.js b/src/docs/components/SVGs/DarkModeIcon.js new file mode 100644 index 000000000..318423094 --- /dev/null +++ b/src/docs/components/SVGs/DarkModeIcon.js @@ -0,0 +1,21 @@ +import React from 'react'; + +const DarkModeIcon = ({ className, onClick }) => ( + + + +); + +export default DarkModeIcon; diff --git a/src/docs/components/SVGs/GithubIcon.js b/src/docs/components/SVGs/GithubIcon.js new file mode 100644 index 000000000..5d2b2bb25 --- /dev/null +++ b/src/docs/components/SVGs/GithubIcon.js @@ -0,0 +1,21 @@ +import React from 'react'; + +const GithubIcon = ({ className, onClick }) => ( + + + +); + +export default GithubIcon; diff --git a/src/docs/components/SVGs/LightModeIcon.js b/src/docs/components/SVGs/LightModeIcon.js new file mode 100644 index 000000000..bb13cb19e --- /dev/null +++ b/src/docs/components/SVGs/LightModeIcon.js @@ -0,0 +1,29 @@ +import React from 'react'; + +const LightModeIcon = ({ className, onClick }) => ( + + + + + + + + + + + +); + +export default LightModeIcon; diff --git a/src/docs/components/SVGs/ListIcon.js b/src/docs/components/SVGs/ListIcon.js new file mode 100644 index 000000000..853b1a7b2 --- /dev/null +++ b/src/docs/components/SVGs/ListIcon.js @@ -0,0 +1,26 @@ +import React from 'react'; + +const ListIcon = ({ className, onClick }) => ( + + + + + + + + +); + +export default ListIcon; diff --git a/src/docs/components/SVGs/SearchIcon.js b/src/docs/components/SVGs/SearchIcon.js new file mode 100644 index 000000000..763ae3ea9 --- /dev/null +++ b/src/docs/components/SVGs/SearchIcon.js @@ -0,0 +1,24 @@ +import React from 'react'; + +const SearchIcon = ({ className, onClick }) => { + return ( + + + + + ); +}; + +export default SearchIcon; diff --git a/src/docs/components/SVGs/ShareIcon.js b/src/docs/components/SVGs/ShareIcon.js new file mode 100644 index 000000000..8e78b671e --- /dev/null +++ b/src/docs/components/SVGs/ShareIcon.js @@ -0,0 +1,25 @@ +import React from 'react'; + +const ShareIcon = ({ className, onClick }) => ( + + + + + + + +); + +export default ShareIcon; diff --git a/src/docs/components/Search.js b/src/docs/components/Search.js new file mode 100644 index 000000000..5b2903d43 --- /dev/null +++ b/src/docs/components/Search.js @@ -0,0 +1,28 @@ +import React from 'react'; + +// =================================================== +// Simple, stateful search component +// =================================================== +const Search = ({ defaultValue = '', setSearchQuery, className = '' }) => { + const [value, setValue] = React.useState(defaultValue); + + React.useEffect(() => { + setSearchQuery(value); + }, [value]); + + return ( + { + setValue(e.target.value); + }} + /> + ); +}; + +export default Search; diff --git a/src/docs/components/Shell.js b/src/docs/components/Shell.js new file mode 100644 index 000000000..4bc30d674 --- /dev/null +++ b/src/docs/components/Shell.js @@ -0,0 +1,148 @@ +import React from 'react'; +import { graphql, useStaticQuery } from 'gatsby'; +import { connect } from 'react-redux'; +import AniLink from 'gatsby-plugin-transition-link/AniLink'; +import ReactCSSTransitionReplace from 'react-css-transition-replace'; +import config from '../../../config'; + +import { toggleDarkMode } from '../state/app'; + +import SearchIcon from './SVGs/SearchIcon'; +import GithubIcon from './SVGs/GithubIcon'; +import DarkModeIcon from './SVGs/DarkModeIcon'; +import LightModeIcon from './SVGs/LightModeIcon'; +import ListIcon from './SVGs/ListIcon'; + +// =================================================== +// Application-level UI component +// =================================================== +const Shell = ({ + isDarkMode, + isSearch, + isList, + dispatch, + withIcon = true, + withTitle = true, + children, +}) => { + const data = useStaticQuery(graphql` + query SiteTitleQuery { + site { + siteMetadata { + title + description + } + } + file(relativePath: { eq: "30s-icon.png" }) { + id + childImageSharp { + original { + src + } + } + } + snippetDataJson(meta: { type: { eq: "snippetListingArray" } }) { + data { + title + id + attributes { + tags + } + } + } + } + `); + let viewportWidth = typeof window !== 'undefined' && window.innerWidth; + + return ( +
+ {/* Menu */} +
+ + + + + + + {/* eslint-disable-next-line */} + + + + {/* + The use of React.Fragment here will cause a lot of errors to show up in webber:dev. + Truth is, this is the only decent way I found to deal with this module's odd behavior. + Keep as is, unless you can provide a better solution, in which case please send a PR. + */} + + {isDarkMode ? ( + dispatch(toggleDarkMode(!isDarkMode))} + /> + ) : ( + dispatch(toggleDarkMode(!isDarkMode))} + /> + )} + +
+ {/* Content */} +
+ {withTitle ? ( +

+ {data.site.siteMetadata.title} + {withIcon ? ( + Logo + ) : ( + '' + )} +

+ ) : ( + '' + )} + {children} +
+
+ ); +}; + +export default connect( + state => ({ + isDarkMode: state.app.isDarkMode, + lastPageTitle: state.app.lastPageTitle, + lastPageUrl: state.app.lastPageUrl, + searchQuery: state.app.searchQuery, + }), + null, +)(Shell); diff --git a/src/docs/components/SimpleCard.js b/src/docs/components/SimpleCard.js new file mode 100644 index 000000000..cd93b6af9 --- /dev/null +++ b/src/docs/components/SimpleCard.js @@ -0,0 +1,21 @@ +import React from 'react'; + +// =================================================== +// Generic card (displays textual content) +// =================================================== +const SimpleCard = ({ + title, + children, + isDarkMode +}) => ( +
+

+ {title} +

+
+ {children} +
+
+); + +export default SimpleCard; diff --git a/src/docs/components/SnippetCard.js b/src/docs/components/SnippetCard.js new file mode 100644 index 000000000..987204c51 --- /dev/null +++ b/src/docs/components/SnippetCard.js @@ -0,0 +1,175 @@ +import React from 'react'; +import { CopyToClipboard } from 'react-copy-to-clipboard'; +import config from '../../../config'; + +import { getTextualContent, getCodeBlocks, optimizeAllNodes } from '../util'; +import ClipboardIcon from './SVGs/ClipboardIcon'; +// import ShareIcon from './SVGs/ShareIcon'; +import AniLink from 'gatsby-plugin-transition-link/AniLink'; +import CollapseOpenIcon from './SVGs/CollapseOpenIcon'; +import CollapseClosedIcon from './SVGs/CollapseClosedIcon'; +import ReactCSSTransitionReplace from 'react-css-transition-replace'; + +// =================================================== +// Snippet Card HOC - check components below for more +// =================================================== +const SnippetCard = ({ short, snippetData, ...rest }) => { + let difficulty = snippetData.tags.includes('advanced') + ? 'advanced' + : snippetData.tags.includes('beginner') + ? 'beginner' + : 'intermediate'; + return short ? ( + + ) : ( + + ); +}; + +// =================================================== +// Simple card corner for difficulty display +// =================================================== +const CardCorner = ({ difficulty = 'intermediate' }) => ( +
+); + +// =================================================== +// Full snippet view (tags, code, title, description) +// =================================================== +const FullCard = ({ snippetData, difficulty, isDarkMode }) => { + const [examplesOpen, setExamplesOpen] = React.useState(false); + const tags = snippetData.tags; + let cardCodeHtml = `${optimizeAllNodes( + getCodeBlocks(snippetData.html).code, + )}`; + let cardExamplesHtml = `${optimizeAllNodes( + getCodeBlocks(snippetData.html).example, + )}`; + return ( +
+ +

{snippetData.title}

+ {tags.map(tag => ( + {tag} + ))} +
+
+ { + let tst = document.createElement('div'); + tst.classList = 'toast'; + tst.innerHTML = 'Snippet copied to clipboard!'; + document.body.appendChild(tst); + setTimeout(function() { + tst.style.opacity = 0; + setTimeout(function() { + document.body.removeChild(tst); + }, 300); + }, 1700); + }} + > + + + {/* */} +
+        
+        
+          {examplesOpen && (
+            
+          )}
+        
+      
+
+ ); +}; + +// =================================================== +// Short snippet view (title, description, code*) +// =================================================== +const ShortCard = ({ snippetData, difficulty, isDarkMode }) => { + let cardCodeHtml = `${optimizeAllNodes( + getCodeBlocks(snippetData.html).code, + )}`; + return ( +
+ +

+ + {snippetData.title} + +

+
+
+ { + let tst = document.createElement('div'); + tst.classList = 'toast'; + tst.innerHTML = 'Snippet copied to clipboard!'; + document.body.appendChild(tst); + setTimeout(function() { + tst.style.opacity = 0; + setTimeout(function() { + document.body.removeChild(tst); + }, 300); + }, 1700); + }} + > + + +
+      
+
+ ); +}; + +export default SnippetCard; diff --git a/src/docs/pages/404.js b/src/docs/pages/404.js new file mode 100644 index 000000000..5239aa371 --- /dev/null +++ b/src/docs/pages/404.js @@ -0,0 +1,60 @@ +import React from 'react'; +import { connect } from 'react-redux'; +import AniLink from 'gatsby-plugin-transition-link/AniLink'; + +import Shell from '../components/Shell'; +import Meta from '../components/Meta'; + +// =================================================== +// Not found page +// =================================================== +const NotFoundPage = ({ isDarkMode }) => ( + <> + + +

404

+
+

+ Page not found +
+

+

+ Seems like you have reached a page that does not exist. +

+ + + + + +   Go home + +
+
+ +); + +export default connect( + state => ({ + isDarkMode: state.app.isDarkMode, + lastPageTitle: state.app.lastPageTitle, + lastPageUrl: state.app.lastPageUrl, + searchQuery: state.app.searchQuery, + }), + null, +)(NotFoundPage); diff --git a/src/docs/pages/about.js b/src/docs/pages/about.js new file mode 100644 index 000000000..e7fed6886 --- /dev/null +++ b/src/docs/pages/about.js @@ -0,0 +1,99 @@ +import React from 'react'; +import { connect } from 'react-redux'; + +import Shell from '../components/Shell'; +import Meta from '../components/Meta'; +import SimpleCard from '../components/SimpleCard'; + +// =================================================== +// About page +// =================================================== +const AboutPage = ({ isDarkMode }) => ( + <> + + +

About

+

+ A few word about us, our goals and our projects. +

+ +

+ The core goal of 30 seconds is to provide a quality resource for beginner and advanced developers alike. We want to help improve the software development 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. +

+
+ +

+ The 30 seconds movement started back in December, 2017, with the release of 30 seconds of code by Angelos Chalaris. Since then, hundreds of developers have contributed snippets to over 6 repositories, creating a thriving community of people willing to help each other write better code. +

+

+ In late 2018, the 30 seconds organization was formed on GitHub, in order to expand upon existing projects and ensure that they will remain high-quality resources in the future. +

+
+ +

+ The 30 seconds movement and, to some extent, the associated GitHub organization consists of all the people who have invested time and ideas to be part of this amazing community. Meanwhile, these fine folks are currently responsible for maintaining the codebases and dealing with organizational matters: +

+
+ +
+ fejes713 + Stefan Fejes +
+
+ flxwu + Felix Wu +
+
+ atomiks + atomiks +
+
+
+ + + +
+ sohelamin + Sohel Amin +
+
+
+ +

+ In order for the code provided via the 30 seconds projects to be as accessible and useful as possible, all of the snippets in these collections 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. +

+

+ Logos, names and trademarks are not to be used without the explicit consent of the maintainers or owners of the 30 seconds GitHub organization. The only exception to this is the usage of the 30-seconds-of- name in open source projects, licensed under the CC0-1.0 License and hosted on GitHub, if their README and website clearly states that they are unofficial projects and in no way affiliated with the organization. +

+
+
+ +); + +export default connect( + state => ({ + isDarkMode: state.app.isDarkMode, + lastPageTitle: state.app.lastPageTitle, + lastPageUrl: state.app.lastPageUrl, + searchQuery: state.app.searchQuery, + }), + null, +)(AboutPage); diff --git a/src/docs/pages/index.js b/src/docs/pages/index.js new file mode 100644 index 000000000..a4128fe19 --- /dev/null +++ b/src/docs/pages/index.js @@ -0,0 +1,158 @@ +import React from 'react'; +import { graphql } from 'gatsby'; +import { connect } from 'react-redux'; +import { pushNewPage, pushNewQuery } from '../state/app'; + +import Shell from '../components/Shell'; +import Meta from '../components/Meta'; +import Search from '../components/Search'; +import SnippetCard from '../components/SnippetCard'; + +import { getRawCodeBlocks as getCodeBlocks } from '../util'; + +// =================================================== +// Home page (splash and search) +// =================================================== +const IndexPage = props => { + console.log(props); + const snippets = props.data.snippetDataJson.data.map(snippet => ({ + title: snippet.title, + html: props.data.allMarkdownRemark.edges.find( + v => v.node.frontmatter.title === snippet.title, + ).node.html, + tags: snippet.attributes.tags, + text: snippet.attributes.text, + id: snippet.id, + code: getCodeBlocks( + props.data.allMarkdownRemark.edges.find( + v => v.node.frontmatter.title === snippet.title, + ).node.rawMarkdownBody, + ).code, + })); + + const [searchQuery, setSearchQuery] = React.useState(props.searchQuery); + const [searchResults, setSearchResults] = React.useState(snippets); + + React.useEffect(() => { + props.dispatch(pushNewQuery(searchQuery)); + let q = searchQuery.toLowerCase(); + let results = snippets; + if (q.trim().length) + results = snippets.filter( + v => + v.tags.filter(t => t.indexOf(q) !== -1).length || + v.title.toLowerCase().indexOf(q) !== -1, + ); + setSearchResults(results); + }, [searchQuery]); + + React.useEffect(() => { + props.dispatch(pushNewPage('Search', '/search')); + }, []); + + return ( + <> + + + Logo +

{props.data.site.siteMetadata.title}

+

+ {props.data.site.siteMetadata.description} +

+ + {searchQuery.length === 0 ? ( +

+ Start typing a keyword to see matching snippets. +

+ ) : searchResults.length === 0 ? ( +

+ We couldn't find any results for the keyword{' '} + {searchQuery}. +

+ ) : ( + <> +

+ Click on a snippet's name to view its code. +

+

Search results

+ {searchResults.map(snippet => ( + + ))} + + )} +
+ + ); +}; + +export default connect( + state => ({ + isDarkMode: state.app.isDarkMode, + lastPageTitle: state.app.lastPageTitle, + lastPageUrl: state.app.lastPageUrl, + searchQuery: state.app.searchQuery, + }), + null, +)(IndexPage); + +export const indexPageQuery = graphql` + query snippetList { + site { + siteMetadata { + title + description + author + } + } + file(relativePath: { eq: "30s-icon.png" }) { + id + childImageSharp { + original { + src + } + } + } + snippetDataJson(meta: { type: { eq: "snippetListingArray" }, scope: {eq: "./snippets"} }) { + data { + id + title + attributes { + tags + text + } + } + } + allMarkdownRemark( + limit: 1000 + sort: { fields: [frontmatter___title], order: ASC } + ) { + totalCount + edges { + node { + id + html + rawMarkdownBody + fields { + slug + } + frontmatter { + title + tags + } + } + } + } + } +`; diff --git a/src/docs/pages/list.js b/src/docs/pages/list.js new file mode 100644 index 000000000..5623ef677 --- /dev/null +++ b/src/docs/pages/list.js @@ -0,0 +1,155 @@ +import React from 'react'; +import { graphql } from 'gatsby'; +import { connect } from 'react-redux'; +import { pushNewPage } from '../state/app'; +import { capitalize } from '../util'; + +import Shell from '../components/Shell'; +import Meta from '../components/Meta'; +import AniLink from 'gatsby-plugin-transition-link/AniLink'; +import SnippetCard from '../components/SnippetCard'; + +import { getRawCodeBlocks as getCodeBlocks } from '../util'; +import SimpleCard from '../components/SimpleCard'; + +// =================================================== +// Snippet list page +// =================================================== +const ListPage = props => { + const snippets = props.data.snippetDataJson.data.map(snippet => ({ + title: snippet.title, + html: props.data.allMarkdownRemark.edges.find( + v => v.node.frontmatter.title === snippet.title, + ).node.html, + tags: snippet.attributes.tags, + text: snippet.attributes.text, + id: snippet.id, + code: getCodeBlocks( + props.data.allMarkdownRemark.edges.find( + v => v.node.frontmatter.title === snippet.title, + ).node.rawMarkdownBody, + ).code, + })); + const tags = snippets.reduce((acc, snippet) => { + if (!snippet.tags) return acc; + const primaryTag = snippet.tags[0]; + if (!acc.includes(primaryTag)) acc.push(primaryTag); + return acc; + }, []); + const staticPages = [ + { + url: 'about', + title: 'About', + description: 'A few word about us, our goals and our projects.' + } + ]; + + React.useEffect(() => { + props.dispatch(pushNewPage('Snippet List', '/list')); + }, []); + + return ( + <> + + +

Snippet List

+

+ Click on a snippet’s name to view its code or a tag name to view all + snippets in that category. +

+ {tags.map(tag => ( + <> +

+ + {capitalize(tag)} + +

+ {snippets + .filter(snippet => snippet.tags[0] === tag) + .map(snippet => ( + + ))} + + ))} +
+ {staticPages.map(page => ( + + {page.title} + + )} + > +

{page.description}

+
+ ))} +
+ + ); +}; + +export default connect( + state => ({ + isDarkMode: state.app.isDarkMode, + lastPageTitle: state.app.lastPageTitle, + lastPageUrl: state.app.lastPageUrl, + searchQuery: state.app.searchQuery, + }), + null, +)(ListPage); + +export const listPageQuery = graphql` + query snippetListing { + site { + siteMetadata { + title + description + author + } + } + snippetDataJson(meta: { type: { eq: "snippetListingArray" }, scope: {eq: "./snippets"} }) { + data { + id + title + attributes { + tags + text + } + } + } + allMarkdownRemark( + limit: 1000 + sort: { fields: [frontmatter___title], order: ASC } + ) { + totalCount + edges { + node { + id + html + rawMarkdownBody + fields { + slug + } + frontmatter { + title + tags + } + } + } + } + } +`; diff --git a/src/docs/pages/search.js b/src/docs/pages/search.js new file mode 100644 index 000000000..b6747cd7f --- /dev/null +++ b/src/docs/pages/search.js @@ -0,0 +1,151 @@ +import React from 'react'; +import { graphql } from 'gatsby'; +import { connect } from 'react-redux'; +import { pushNewPage, pushNewQuery } from '../state/app'; + +import Shell from '../components/Shell'; +import Meta from '../components/Meta'; +import Search from '../components/Search'; +import SnippetCard from '../components/SnippetCard'; + +import { getRawCodeBlocks as getCodeBlocks } from '../util'; + +// =================================================== +// Search page +// =================================================== +const SearchPage = props => { + const snippets = props.data.snippetDataJson.data.map(snippet => ({ + title: snippet.title, + html: props.data.allMarkdownRemark.edges.find( + v => v.node.frontmatter.title === snippet.title, + ).node.html, + tags: snippet.attributes.tags, + text: snippet.attributes.text, + id: snippet.id, + code: getCodeBlocks( + props.data.allMarkdownRemark.edges.find( + v => v.node.frontmatter.title === snippet.title, + ).node.rawMarkdownBody, + ).code, + })); + + const [searchQuery, setSearchQuery] = React.useState(props.searchQuery); + const [searchResults, setSearchResults] = React.useState(snippets); + + React.useEffect(() => { + props.dispatch(pushNewQuery(searchQuery)); + let q = searchQuery.toLowerCase(); + let results = snippets; + if (q.trim().length) + results = snippets.filter( + v => + v.tags.filter(t => t.indexOf(q) !== -1).length || + v.title.toLowerCase().indexOf(q) !== -1, + ); + setSearchResults(results); + }, [searchQuery]); + + React.useEffect(() => { + props.dispatch(pushNewPage('Search', '/search')); + }, []); + + return ( + <> + + + +

Click on a snippet's name to view its code.

+ {/* Display page background or results depending on state */} + {searchQuery.length === 0 ? ( + <> +
+

+ Start typing a keyword to see matching snippets. +

+
+ + ) : searchResults.length === 0 ? ( + <> +
+

+ No results found +
+

+

+ We couldn't find any results for the keyword{' '} + {searchQuery}. +

+
+ + ) : ( + <> +

Search results

+ {searchResults.map(snippet => ( + + ))} + + )} +
+ + ); +}; + +export default connect( + state => ({ + isDarkMode: state.app.isDarkMode, + lastPageTitle: state.app.lastPageTitle, + lastPageUrl: state.app.lastPageUrl, + searchQuery: state.app.searchQuery, + }), + null, +)(SearchPage); + +export const searchPageQuery = graphql` + query searchSnippetList { + site { + siteMetadata { + title + description + author + } + } + snippetDataJson(meta: { type: { eq: "snippetListingArray" }, scope: {eq: "./snippets"} }) { + data { + id + title + attributes { + tags + text + } + } + } + allMarkdownRemark( + limit: 1000 + sort: { fields: [frontmatter___title], order: ASC } + ) { + totalCount + edges { + node { + id + html + rawMarkdownBody + fields { + slug + } + frontmatter { + title + tags + } + } + } + } + } +`; diff --git a/src/docs/state/ReduxWrapper.js b/src/docs/state/ReduxWrapper.js new file mode 100644 index 000000000..5daacf556 --- /dev/null +++ b/src/docs/state/ReduxWrapper.js @@ -0,0 +1,13 @@ +import React from 'react'; +import { Provider } from 'react-redux'; +import { createStore as reduxCreateStore } from 'redux'; +import rootReducer from '.'; + +const createStore = () => reduxCreateStore(rootReducer); + +// =================================================== +// Wrapper for Gatsby +// =================================================== +export default ({ element }) => ( + {element} +); diff --git a/src/docs/state/app.js b/src/docs/state/app.js new file mode 100644 index 000000000..546e6fde4 --- /dev/null +++ b/src/docs/state/app.js @@ -0,0 +1,49 @@ +// Defalt state +const initialState = { + isDarkMode: false, + lastPageTitle: 'Home', + lastPageUrl: '/', + searchQuery: '', +}; + +// Actions +const TOGGLE_DARKMODE = 'TOGGLE_DARKMODE'; +const PUSH_NEW_PAGE = 'PUSH_NEW_PAGE'; +const PUSH_NEW_QUERY = 'PUSH_NEW_QUERY'; +export const toggleDarkMode = isDarkMode => ({ + type: TOGGLE_DARKMODE, + isDarkMode, +}); +export const pushNewPage = (pageTitle, pageUrl) => ({ + type: PUSH_NEW_PAGE, + pageTitle, + pageUrl, +}); +export const pushNewQuery = query => ({ + type: PUSH_NEW_QUERY, + query, +}); + +// Reducer +export default (state = initialState, action) => { + switch (action.type) { + case TOGGLE_DARKMODE: + return { + ...state, + isDarkMode: action.isDarkMode, + }; + case PUSH_NEW_PAGE: + return { + ...state, + lastPageTitle: action.pageTitle, + lastPageUrl: action.pageUrl, + }; + case PUSH_NEW_QUERY: + return { + ...state, + searchQuery: action.query, + }; + default: + return state; + } +}; diff --git a/src/docs/state/index.js b/src/docs/state/index.js new file mode 100644 index 000000000..1ee96d387 --- /dev/null +++ b/src/docs/state/index.js @@ -0,0 +1,4 @@ +import { combineReducers } from 'redux'; +import app from './app'; + +export default combineReducers({ app }); diff --git a/src/docs/styles/_button.scss b/src/docs/styles/_button.scss new file mode 100644 index 000000000..f3e2384f0 --- /dev/null +++ b/src/docs/styles/_button.scss @@ -0,0 +1,79 @@ +// =================================================== +// Buttons +// =================================================== +.button, a.button { + color: var(--button-fore-color); + font-weight: 500; + font-size: 1.125rem; + line-height: 1.4; + transition: 0.3s ease all; + padding: 0.625rem 0.875rem; + margin-top: 0.75rem; + border-radius: 1rem; + display: inline-block; + box-shadow: 0px 4px 8px var(--button-shadow-color); + border: none; + cursor: pointer; + &:hover, &:focus { + box-shadow: 0px 8px 16px var(--button-shadow-color); + text-decoration: none; + outline: none; + } + &.button-a { + background: var(--button-back-color-a); + } + &.button-b { + background: var(--button-back-color-b); + } + svg { + vertical-align: sub; + } + @media screen and (min-width: $layout-large-breakpoint) { + font-size: 1.375rem; + line-height: 1.35; + } +} + +// Home button (404 page) +.button.button-home { + @media screen and (min-width: $layout-large-breakpoint) { + margin-top: 1.375rem; + } +} + +// Copy and share buttons (snippet card) +.button.button-copy { + position: absolute; + top: -32px; + right: 24px; + padding: 0.5rem 0.625rem; +} +.button.button-social-sh { + position: absolute; + top: -32px; + right: 80px; + padding: 0.5rem 0.625rem; +} + +// Show/hide examples button (snippet card) +.button.button-example-toggler { + margin: -2rem 0px -1rem 0px; + background: var(--pre-back-color); + border-radius: 0px 0px 0.125rem 0.125rem; + width: calc(100%); + text-align: left; + display: block; + font-size: 0.875rem; + line-height: 1.35; + text-transform: uppercase; + font-weight: 300; + color: var(--button-example-toggler-fore-color); + box-shadow: none; + font-family: 'Roboto Mono', Menlo, Consolas, monospace; + &:hover, &:focus { + box-shadow: none; + } + svg { + margin-right: 0.125rem; + } +} \ No newline at end of file diff --git a/src/docs/styles/_card.scss b/src/docs/styles/_card.scss new file mode 100644 index 000000000..680a41e3d --- /dev/null +++ b/src/docs/styles/_card.scss @@ -0,0 +1,150 @@ +// =================================================== +// Cards +// =================================================== +.card { + position: relative; + transition: all 0.3s ease; + margin: 1rem 1.25rem; + background: var(--card-back-color); + color: var(--card-fore-color); + box-shadow: 0px 0px 1px var(--card-shadow-color-a), 0px 6px 12px var(--card-shadow-color-b); + border-radius: 0.125rem; + padding: 1rem; + .card-title { + font-size: 1.125rem; + line-height: 1.375; + font-weight: 500; + margin: 0px 0px 0.125rem; + a, a:link, a:visited { + font-weight: 500; + transition: 0.3s ease all; + color: var(--card-fore-color); + } + } + .card-description { + margin: 0.125rem -0.5rem 0.125rem; + font-size: 0.875rem; + color: var(--card-fore-color-light); + line-height: 1.35; + font-weight: 500; + } + .card-bottom { + position: relative; + background: blue; + margin-left: -1rem; + margin-right: -1rem; + border-radius: 0.125rem; + border-top-left-radius: 22px; + } + .card-code { + margin: 1.5rem 0px -1rem 0px; + background: var(--pre-back-color); + width: calc(100% - 36px); + border-radius: 1.375rem 0px 0.125rem 0.125rem; + line-height: 1.15; + padding: 2.25rem 1.125rem 2.25rem; + } + .card-examples { + transition: all 0.3s ease; + position: relative; + margin: 0.5rem 0px -1rem 0px; + background: var(--pre-back-color); + width: calc(100% - 52px); + border-radius: 0px 0px 0.125rem 0.125rem; + line-height: 1.15; + padding: 0.5rem 1.125rem 2.25rem 2.125rem; + &::before { + display: block; + content: ''; + position: absolute; + left: 21px; + top: 0; + width: 1px; + opacity: 0.75; + height: calc(100% - 24px); + background: var(--button-example-toggler-fore-color); + } + } + &.short { + .card-bottom { + display: none; + @media screen and (min-width: $layout-large-breakpoint) { + display: block; + } + } + } + &:not(.short) { + background: linear-gradient(to bottom, var(--card-back-color) 0px, var(--card-back-color) calc(100% - 17px), var(--pre-back-color) calc(100% - 16px)); + } +} + +// Card expertise corners +.card-corner { + box-sizing: border-box; + position: absolute; + top: 24px; + right: 16px; + width: 0.5rem; + height: 0.5rem; + border-radius: 0.5rem; + background: var(--corner-color); + &.beginner { + --corner-color: var(--beginner-color); + } + &.intermediate { + --corner-color: var(--intermediate-color); + } + &.advanced { + --corner-color: var(--advanced-color); + } + &.intermediate, &.advanced { + &::before { + display: block; + position: absolute; + content: ''; + top: 0px; + right: 12px; + width: 0.5rem; + height: 0.5rem; + border-radius: 0.5rem; + background: var(--corner-color); + } + } + &.advanced { + &::after { + display: block; + position: absolute; + content: ''; + top: 0px; + right: 24px; + width: 0.5rem; + height: 0.5rem; + border-radius: 0.5rem; + background: var(--corner-color); + } + } +} + +// Tags +.tag { + transition: 0.3s ease all; + border: 2px solid var(--tag-border-color); + border-radius: 0.25rem; + color: var(--tag-fore-color); + text-transform: uppercase; + margin: 0px 0.375rem 0.25rem 0px; + display: inline-block; + padding: 0.125rem 0.25rem; + letter-spacing: 0.25px; + font-size: 0.625rem; + line-height: 1.4; + font-weight: 500; + &:first-of-type { + margin-top: 0.375rem; + } +} + +// Animation for card example +.roll-up-height { + transition: height 0.3s ease-in-out; +} \ No newline at end of file diff --git a/src/docs/styles/_code.scss b/src/docs/styles/_code.scss new file mode 100644 index 000000000..cb6b91330 --- /dev/null +++ b/src/docs/styles/_code.scss @@ -0,0 +1,121 @@ +// Style code +code, kbd, pre { + font-size: 0.875em; +} +code, kbd, pre, code *, pre *, kbd *, code[class*="language-"], pre[class*="language-"] { + font-family: 'Roboto Mono', Menlo, Consolas, monospace; +} + +code { + background: var(--code-back-color); + color: var(--code-fore-color); + padding: 0.125rem 0.375rem; + border-radius: 0.125rem; +} +pre { + overflow: auto; // Responsiveness + background: var(--pre-back-color); + color: var(--pre-fore-color); + padding: 0.375rem; + margin: 0.5rem; + 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: 1rem; + overflow: auto; + margin: 0.5rem 0; + white-space: pre-wrap; +} + +pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, +code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { + background: var(--pre-selected-color); +} + +pre[class*="language-"]::selection, pre[class*="language-"] ::selection, +code[class*="language-"]::selection, code[class*="language-"] ::selection { + background: var(--pre-selected-color); +} + +: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); + } + &.punctuation { + color: var(--token-color-b); + } + &.property, &.tag, &.boolean, &.constant, &.symbol, &.deleted, &.function { + color: var(--token-color-c); + } + &.number, &.class-name { + color: var(--token-color-d); + } + &.selector, &.attr-name, &.string, &.char, &.builtin, &.inserted { + color: var(--token-color-e); + } + &.operator, &.entity, &.url, &.atrule, &.attr-value, &.keyword, &.interpolation-punctuation { + color: var(--token-color-f); + } + &.regex { + color: var(--token-color-g); + } + &.important, &.variable { + color: var(--token-color-h); + } + &.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); +} + +p > code { + &, &[class*="language-"] { + color: var(--code-fore-color); + background: var(--code-back-color); + &::-moz-selection, & ::-moz-selection { + background: var(--code-selected-color); + } + &::selection, & ::selection { + background: var(--code-selected-color); + } + } +} \ No newline at end of file diff --git a/src/docs/styles/_colors.scss b/src/docs/styles/_colors.scss new file mode 100644 index 000000000..38ad0d519 --- /dev/null +++ b/src/docs/styles/_colors.scss @@ -0,0 +1,140 @@ +:root { + // Interface color palette + --back-color: #F5F6FA; + --back-color-dark: #D7DDF3; + --fore-color: #404454; + --fore-color-light: #575E7A; + --fore-color-lighter: #666E8F; + --fore-color-dark: #1F253D; + --fore-color-darker: #060709; + + // Scrollbar + --scrollbar-back-color: #D7DDF3; + --scrollbar-fore-color: #666E8F; + + // Menu color palette + --menu-back-color: #FFFFFF; + --menu-border-color: #E4E6EC; + --menu-fore-color: #53586A; + --menu-active-fore-color: #2747C7; + + // Card corner palette + --beginner-color: #7CB342; + --intermediate-color: #FFB300; + --advanced-color: #D66361; + + // Search color palette + --search-back-color: #FFFFFF; + --search-fore-color: #0D0E17; + --search-placeholder-color: #C5C6CD; + --search-shadow-color: rgba(0, 32, 128, 0.1); + --search-shadow-focus-color: rgba(0, 32, 128, 0.17); + + // Button color palette + --button-back-color-a: #3B3EFC; + --button-back-color-b: #DC325F; + --button-fore-color: #FFFFFF; + --button-shadow-color: rgba(0, 0, 0, 0.25); + --button-shadow-focus-color: rgba(0, 0, 0, 0.29); + --button-example-toggler-fore-color: #607d8b; + + // Card color palette + --card-back-color: #FFFFFF; + --card-fore-color: #212121; + --card-fore-color-light: #424242; + --card-shadow-color-a: rgba(240, 242, 247, 0.1); + --card-shadow-color-b: rgba(0, 32, 128, 0.1); + + // Pre & Code color palette + --pre-fore-color: #e57373; + --pre-back-color: #1e253d; + --pre-selected-color: #041248; + + // Token color palette + --token-color-a: #7f99a5; // Comments + --token-color-b: #bdbdbd; // Punctuation + --token-color-c: #64b5f6; // Functions + --token-color-d: #ff8f00; // Numbers + --token-color-e: #c5e1a5; // Strings + --token-color-f: #ce93d8; // Keywords + --token-color-g: #26c6da; // Regular expressions + --token-color-h: #e57373; // Variables + + // Tag color palette + --tag-border-color: #D7DDF3; + --tag-fore-color: #616B8F; + + // Toast color palette + --toast-back-color: #05A864; + --toast-fore-color: #FFFFFF; + --toast-shadow-color: rgba(0, 32, 128, 0.26); + + // Link color palette + --a-link-color: #0277bd; + --a-visited-color: #01579b; + + // Code color palette + --code-fore-color: #0324AB; + --code-back-color: #EDF0FC; + --code-selected-color: #BDEDFE; +} + +// Dark mode colors +.page-container.dark { + // Interface color palette + --back-color: #2A314C; + --back-color-dark: #8993BE; + --fore-color: #ABAFBF; + --fore-color-light: #858CA8; + --fore-color-lighter: #707899; + --fore-color-dark: #B4BCD9; + --fore-color-darker: #FCFCFD; + + // Scrollbar + --scrollbar-back-color: #434E76; + --scrollbar-fore-color: #707899; + + // Menu color palette + --menu-back-color: #434E76; + --menu-border-color: #13151B; + --menu-fore-color: #959AAC; + --menu-active-fore-color: #CDD4EF; + + // Card corner palette remains unchanged for consistency + + // Search color palette + --search-back-color: #434E76; + --search-fore-color: #E8E9F2; + --search-placeholder-color: #999EBD; + --search-shadow-color: rgba(1, 8, 30, 0.24); + --search-shadow-focus-color: rgba(1, 8, 30, 0.31); + + // Button color palette remains unchanged for consistency + + // Card color palette + --card-back-color: #434E76; + --card-fore-color: #F0F0F0; + --card-fore-color-light: #D6D6D6; // previously C0C0C0, careful + --card-shadow-color-b: rgba(1, 8, 30, 0.24); + + // Pre & Code color palette remains unchanged for consistency + + // Token color palette remains unchanged for consistency + + // Tag color palette + --tag-border-color: #2A3765; + --tag-fore-color: #BEC1CB; // previously 999DAD, careful + + // Toast color palette + --toast-shadow-color: rgba(1, 8, 30, 0.44); + + // Link color palette + --a-link-color: #6DC7FD; + --a-visited-color: #5DB7FE; + + // Code color palette + --code-fore-color: #d1dafe; + --code-back-color: #4f5fa0; + --code-selected-color: #0dbcfb; + +} \ No newline at end of file diff --git a/src/docs/styles/_fonts.scss b/src/docs/styles/_fonts.scss new file mode 100644 index 000000000..42e20aed6 --- /dev/null +++ b/src/docs/styles/_fonts.scss @@ -0,0 +1,89 @@ +// Load external fonts - progressive loading should help alleviate performance issues +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: local('Roboto Mono'), local('RobotoMono-Regular'), url(../../../assets/RobotoMono-Regular.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-face { + font-family: 'Roboto Mono'; + font-style: italic; + font-weight: 400; + font-display: swap; + src: local('Roboto Mono Italic'), local('RobotoMono-Italic'), url(../../../assets/RobotoMono-Italic.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-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: local('Roboto Mono Medium'), local('RobotoMono-Medium'), url(../../../assets/RobotoMono-Medium.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: 'Noto Sans'; + font-style: normal; + font-weight: 300; + font-display: swap; + src: local('Noto Sans Light'), local('NotoSans-Light'), url(../../../assets/NotoSans-Light.ttf) format('truetype'); + 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-face { + font-family: 'Noto Sans'; + font-style: italic; + font-weight: 300; + font-display: swap; + src: local('Noto Sans LightItalic'), local('NotoSans-LightItalic'), url(../../../assets/NotoSans-LightItalic.ttf) format('truetype'); + 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-face { + font-family: 'Noto Sans'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: local('Noto Sans'), local('NotoSans-Regular'), url(../../../assets/NotoSans-Regular.ttf) format('truetype'); + 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-face { + font-family: 'Noto Sans'; + font-style: italic; + font-weight: 400; + font-display: swap; + src: local('Noto Sans Italic'), local('NotoSans-Italic'), url(../../../assets/NotoSans-Italic.ttf) format('truetype'); + 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-face { + font-family: 'Noto Sans'; + font-style: normal; + font-weight: 500; + font-display: swap; + src: local('Noto Sans Medium'), local('NotoSans-Medium'), url(../../../assets/NotoSans-Medium.ttf) format('truetype'); + 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-face { + font-family: 'Noto Sans'; + font-style: italic; + font-weight: 500; + font-display: swap; + src: local('Noto Sans Medium Italic'), local('NotoSans-MediumItalic'), url(../../../assets/NotoSans-MediumItalic.ttf) format('truetype'); + 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-face { + font-family: 'Noto Sans'; + font-style: normal; + font-weight: 600; + font-display: swap; + src: local('Noto Sans SemiBold'), local('NotoSans-SemiBold'), url(../../../assets/NotoSans-SemiBold.ttf) format('truetype'); + 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-face { + font-family: 'Noto Sans'; + font-style: italic; + font-weight: 600; + font-display: swap; + src: local('Noto Sans SemiBold Italic'), local('NotoSans-SemiBoldItalic'), url(../../../assets/NotoSans-SemiBoldItalic.ttf) format('truetype'); + 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; +} \ No newline at end of file diff --git a/src/docs/styles/_layout.scss b/src/docs/styles/_layout.scss new file mode 100644 index 000000000..7057cd837 --- /dev/null +++ b/src/docs/styles/_layout.scss @@ -0,0 +1,340 @@ +// =================================================== +// Layout +// =================================================== +// Grid container +.page-container { + overflow: hidden; + transition: 0.3s ease all; + background: var(--back-color); + display: grid; + width: 100vw; + height: 100vh; + grid-template-areas: "content" "menu"; + grid-template-columns: 100%; + grid-template-rows: calc(100vh - 62px) 62px; + // Medium screen size (mobile landscape, tablet) + @media screen and (min-width: $layout-medium-breakpoint) { + grid-template-areas: "menu content"; + grid-template-columns: 62px calc(100vw - 62px); + grid-template-rows: 100%; + } + // Large screen size (desktop, laptop) + @media screen and (min-width: $layout-large-breakpoint) { + grid-template-areas: "menu . content ."; + grid-template-columns: 62px calc((100vw - 830px) / 2) 768px calc((100vw - 830px) / 2); + } +} +// Menu container +header.menu { + grid-area: menu; +} +// Content container +.content { + transition: 0.3s ease all; + grid-area: content; + overflow: auto; + background: var(--back-color); + &::-webkit-scrollbar-track { + background-color: var(--scrollbar-back-color); + margin: 0.5rem 0; + border-radius: 0.125rem; + } + &::-webkit-scrollbar { + width: 4px; + background: transparent; + } + &::-webkit-scrollbar-thumb { + background-color: var(--scrollbar-fore-color); + border: 1px solid var(--scrollbar-fore-color-lighter); + border-radius: 0.125rem; + } +} + +// Website title +h1.website-title { + transition: 0.3s ease all; + font-size: 0.875rem; + font-weight: 500; + color: var(--fore-color-lighter); + line-height: 1.5; + position: relative; + top: 4px; + margin: 1.5rem 1.25rem 0.125rem; + @media screen and (min-width: $layout-large-breakpoint) { + font-size: 1rem; + line-height: 1.375; + } +} +// Website logo +img.website-logo { + transition: 0.3s ease all; + position: absolute; + top: 8px; + right: 0px; + width: 48px; + height: 48px; +} +// Homepage logo +.index-logo { + transition: 0.3s ease all; + display: block; + margin: 1.5rem 1.25rem 0.5rem; + vertical-align: middle; + @media screen and (min-width: 144px) { + max-width: 128px; + margin: 1.5rem auto 0.5rem; + } + @media screen and (min-width: $layout-medium-breakpoint) { + display: inline-block; + margin: 1.5rem 2rem 0.5rem 1.25rem; + } +} +// Homepage title +.index-title { + transition: 0.3s ease all; + font-size: 2rem; + color: var(--fore-color-dark); + @media screen and (min-width: $layout-medium-breakpoint) { + display: inline-block; + } + margin: 0.75rem 1.25rem; + text-align: center; +} +// Homepage subtitle +.index-sub-title { + transition: 0.3s ease all; + font-size: 0.875rem; + line-height: 1.5; + margin: 1rem 1.25rem 1.25rem; + color: var(--fore-color); + text-align: center; + @media screen and (min-width: $layout-medium-breakpoint) { + font-size: 1rem; + } +} + +// Page title +.page-title { + font-size: 2.25rem; + font-weight: 400; + line-height: 1.36; + letter-spacing: 0.03em; + color: var(--fore-color-darker); + margin: 0 1.25rem; + @media screen and (min-width: $layout-large-breakpoint) { + font-size: 2.5rem; + line-height: 1.35; + } +} +// Page subtitle +.page-sub-title { + transition: 0.3s ease all; + font-size: 1.125rem; + line-height: 1.35; + margin: 1rem 1.25rem 0.5rem; + color: var(--fore-color); + @media screen and (min-width: $layout-large-breakpoint) { + font-size: 1.25rem; + } +} +// Page light subtitle +p.light-sub { + transition: 0.3s ease all; + color: var(--fore-color-light); + font-size: 0.875rem; + line-height: 1.5; + margin: 0.125rem 1.25rem 0px; + @media screen and (min-width: $layout-large-breakpoint) { + font-size: 1rem; + line-height: 1.375; + } +} +// Category/tag title +.tag-title { + transition: 0.3s ease all; + font-size: 1.125rem; + color: var(-fore-color-dark); + line-height: 1.375; + a { + &, &:link, &:visited { + color: var(--fore-color-dark); + } + } + font-weight: 400; + cursor: pointer; + margin: 1.5rem 1.25rem 0.5rem; +} + +// Return to previous page link +a.link-back { + transition: 0.3s ease all; + font-size: 1.125rem; + line-height: 1.35; + display: block; + margin: 1rem 1.25rem 1.5rem; + font-weight: 500; + &, &:link, &:visited { + color: var(--fore-color-dark); + } + &:hover, &:focus { + text-decoration: none; + } + svg { + vertical-align: middle; + } +} + +// About page maintainers card +.flex-row { + display: flex; + flex: 0 1 auto; + flex-flow: row wrap; + .flex-item { + flex: 0 0 auto; + max-width: calc(50% - 24px); + flex-basis: calc(50% - 24px); + margin: 12px; + @media screen and (min-width: $layout-large-breakpoint) { + max-width: calc(25% - 24px); + flex-basis: calc(25% - 24px); + } + .media-section { + max-width: 100%; + height: auto; + border-radius: 0.5rem; + } + .button-section { + font-size: 0.875rem; + font-weight: 600; + text-align: center; + width: 100%; + display: block; + &, &:link, &:visited { + font-weight: 600; + color: var(--card-fore-color); + } + } + } +} + +// Page background graphic +.page-graphic { + position: relative; + box-sizing: border-box; + transition: all 0.3s ease; + margin-top: 100px; + width: 100%; + height: calc(50vmin); + &::before { + top: 0; + right: 27.5vmin; + position: absolute; + content: ''; + width: 45vmin; + height: 44vmin; + background-position-x: 52.5%, center; + background-position-y: 1%, top; + background-repeat: no-repeat; + background-size: 45vmin, 44vmin; + } + padding-top: 46vmin; + text-align: center; + @media screen and (orientation: landscape) and (max-height: calc(#{$layout-medium-breakpoint} - 1px)) { + margin-top: 2rem; + padding-top: 38vmin; + height: 40vmin; + &::before { + right: calc(50vw - 45vmin / 2 - 31px); + } + } + @media screen and (min-width: $layout-large-breakpoint) { + padding-top: 2vmin; + padding-right: 400px; + &::before { + background-size: 395px, 393px; + height: 400px; + width: 400px; + right: 1.125rem; + margin-top: -2vmin; + background-position-x: 95.5%, 93%; + } + } +} + +// Empty page text +.empty-page-text { + transition: color 0.3s ease, background 0.3s ease; + text-align: center; + margin: 2.25rem auto 0.75rem; + max-width: 200px; + font-size: 1rem; + line-height: 1.5; + color: var(--fore-color-darker); + font-weight: 400; + @media screen and (min-width: $layout-medium-breakpoint) { + max-width: 400px; + } + @media screen and (min-width: $layout-large-breakpoint) { + font-size: 1.75rem; + line-height: 1.35; + margin: 2.25rem auto 1.375rem 1.25rem; + &.search-page-text { + margin-top: 12vmin; + font-size: 1.375rem; + line-height: 1.375; + } + } +} +.empty-page-subtext { + transition: all 0.3s ease; + text-align: center; + font-size: 14px; + font-weight: 400; + line-height: 1.5; + max-width: 200px; + color: var(--fore-color-darker); + margin: 0.5rem auto; + @media screen and (min-width: $layout-medium-breakpoint) { + max-width: 256px; + } + @media screen and (min-width: $layout-large-breakpoint) { + font-size: 1.125rem; + line-height: 1.375; + } +} +// Background graphic styles and dark mode +.search-empty::before { + background-image: url("data:image/svg+xml,%3Csvg width='154' height='148' viewBox='0 0 154 148' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cline x1='72.7688' y1='68.1962' x2='88.5602' y2='83.9877' stroke='%23575E7A' stroke-width='2'/%3E%3Crect x='97.8234' y='75.055' width='76.9574' height='23.2664' rx='11.6332' transform='rotate(45 97.8234 75.055)' stroke='%23575E7A' stroke-width='2'/%3E%3Cpath d='M81.3085 50.7431C81.9744 47.8236 82.3261 44.7844 82.3261 41.6631C82.3261 35.0791 80.7613 28.8607 77.9834 23.3593' stroke='%23575E7A' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M56.2702 3.70245C51.7367 1.95686 46.8116 1 41.663 1C19.2055 1 1 19.2055 1 41.663C1 64.1206 19.2055 82.3261 41.663 82.3261C59.2695 82.3261 74.2624 71.1364 79.9182 55.4806' stroke='%23575E7A' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M62.1442 6.52702C65.6967 8.6023 68.9061 11.2009 71.6667 14.2172' stroke='%23575E7A' stroke-width='2' stroke-linecap='round'/%3E%3C/svg%3E"), url("data:image/svg+xml,%3Csvg width='152' height='150' viewBox='0 0 152 150' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M147.38 72.8499C153.437 95.1096 155.456 105.228 141.323 129.511C127.191 153.794 94.8556 149.747 72.6806 149.747C32.5402 149.747 0 117.131 0 76.8971C0 36.6632 34.5591 0 74.6995 0C114.84 0 141.323 50.5902 147.38 72.8499Z' fill='%23D7DDF3'/%3E%3C/svg%3E"); +} +.search-no-results::before { + background-image: url("data:image/svg+xml,%3Csvg width='154' height='148' viewBox='0 0 154 148' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cline x1='72.7688' y1='68.1962' x2='88.5602' y2='83.9877' stroke='%23575E7A' stroke-width='2'/%3E%3Crect x='97.8234' y='75.055' width='76.9574' height='23.2664' rx='11.6332' transform='rotate(45 97.8234 75.055)' stroke='%23575E7A' stroke-width='2'/%3E%3Cpath d='M81.3085 50.7432C81.9744 47.8236 82.3261 44.7844 82.3261 41.6631C82.3261 35.0792 80.7613 28.8607 77.9834 23.3593' stroke='%23575E7A' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M56.2702 3.70245C51.7367 1.95686 46.8116 1 41.663 1C19.2055 1 1 19.2055 1 41.663C1 64.1206 19.2055 82.3261 41.663 82.3261C59.2695 82.3261 74.2624 71.1364 79.9182 55.4806' stroke='%23575E7A' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M62.1442 6.52701C65.6967 8.60229 68.9061 11.2009 71.6667 14.2172' stroke='%23575E7A' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M11.3086 38.2034C11.3086 38.2034 13.5167 41.5575 16.9242 41.3193C20.3318 41.081 22.0516 37.4522 22.0516 37.4522M18.1449 58.7766C18.1449 58.7766 23.8094 54.872 31.061 54.3649C38.3125 53.8578 43.9281 56.9737 43.9281 56.9737M34.2526 36.599C34.2526 36.599 36.2089 39.9708 39.8682 39.7149C43.5276 39.459 44.9956 35.8478 44.9956 35.8478' stroke='%23575E7A' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E%0A"), url("data:image/svg+xml,%3Csvg width='152' height='150' viewBox='0 0 152 150' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M147.38 72.8499C153.437 95.1096 155.456 105.228 141.323 129.511C127.191 153.794 94.8556 149.747 72.6806 149.747C32.5402 149.747 0 117.131 0 76.8971C0 36.6632 34.5591 0 74.6995 0C114.84 0 141.323 50.5902 147.38 72.8499Z' fill='%23D7DDF3'/%3E%3C/svg%3E"); +} +.page-not-found::before { + background-image: url("data:image/svg+xml,%3Csvg width='160' height='109' viewBox='0 0 160 109' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 7.99999C1 4.134 4.13401 1 8 1H95.1429H152C155.866 1 159 4.13401 159 8V100.571C159 104.437 155.866 107.571 152 107.571H8C4.13401 107.571 1 104.437 1 100.571V7.99999Z' stroke='%23575E7A' stroke-width='2'/%3E%3Cline x1='1' y1='17.8571' x2='83.5714' y2='17.8571' stroke='%23575E7A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='100.429' y1='17.8571' x2='116.714' y2='17.8571' stroke='%23575E7A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='128.429' y1='17.8571' x2='159' y2='17.8571' stroke='%23575E7A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Ccircle cx='8.57138' cy='9.7142' r='1.85714' stroke='%23575E7A' stroke-width='2'/%3E%3Ccircle cx='17.7142' cy='9.7142' r='1.85714' stroke='%23575E7A' stroke-width='2'/%3E%3Ccircle cx='26.8573' cy='9.7142' r='1.85714' stroke='%23575E7A' stroke-width='2'/%3E%3Cline x1='33.9856' y1='38.2856' x2='41.4608' y2='45.7608' stroke='%23575E7A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='34.4762' y1='45.761' x2='41.9513' y2='38.2858' stroke='%23575E7A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='105.414' y1='38.2856' x2='112.889' y2='45.7608' stroke='%23575E7A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='105.905' y1='45.761' x2='113.38' y2='38.2858' stroke='%23575E7A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M49.8545 69.0772C49.8545 69.0772 57.5257 73.6485 72.1402 73.6485C86.7117 73.6485 94.4259 69.0771 94.4259 69.0771' stroke='%23575E7A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M72.1526 78.5698C72.3093 86.3002 68.3437 92.6498 63.2953 92.7521C58.2469 92.8544 54.0273 86.6706 53.8707 78.9402C53.8129 76.0901 54.3155 73.4277 55.2261 71.1969' stroke='%23575E7A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M64.6687 73.7268C64.8334 73.1997 64.5396 72.6388 64.0125 72.4741C63.4853 72.3093 62.9245 72.6031 62.7597 73.1303L64.6687 73.7268ZM61.8707 88.7359C61.9615 89.2807 62.4768 89.6487 63.0215 89.5579C63.5663 89.4671 63.9343 88.9519 63.8435 88.4071L61.8707 88.7359ZM62.7597 73.1303C61.2791 77.8683 60.9909 83.4569 61.8707 88.7359L63.8435 88.4071C63.009 83.4002 63.2922 78.1317 64.6687 73.7268L62.7597 73.1303Z' fill='%23575E7A'/%3E%3C/svg%3E%0A"), url("data:image/svg+xml,%3Csvg width='172' height='170' viewBox='0 0 172 170' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M85.7456 16.9208C110.886 -6.48267 132.959 -4.28052 156.498 15.4794C180.037 35.2393 174.047 84.4687 153.005 119.028C128.204 159.761 84.2197 174.845 40.8539 167.344C-2.51188 159.842 -6.55002 107.678 7.88005 65.9713C22.3101 24.2642 60.6055 40.3243 85.7456 16.9208Z' fill='%23D7DDF3'/%3E%3C/svg%3E%0A"); + background-position-x: 53.5%, center; + background-position-y: 8.5%, top; + background-size: 41vmin, 44vmin; + &::before { + background-size: 395px, 393px; + height: 400px; + width: 400px; + right: 1.125rem; + margin-top: -15vmin; + background-position-x: 95.5%, 93%; + } + @media screen and (min-width: $layout-large-breakpoint) { + background-size: 367px, 393px; + background-position-x: 96.5%, 93%; + } +} +.page-container.dark { + .search-empty::before { + background-image: url("data:image/svg+xml,%3Csvg width='154' height='148' viewBox='0 0 154 148' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cline x1='72.7688' y1='68.1962' x2='88.5602' y2='83.9877' stroke='%238993BE' stroke-width='2'/%3E%3Crect x='97.8234' y='75.055' width='76.9574' height='23.2664' rx='11.6332' transform='rotate(45 97.8234 75.055)' stroke='%238993BE' stroke-width='2'/%3E%3Cpath d='M81.3085 50.7431C81.9744 47.8236 82.3261 44.7844 82.3261 41.6631C82.3261 35.0791 80.7613 28.8607 77.9834 23.3593' stroke='%238993BE' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M56.2702 3.70245C51.7367 1.95686 46.8116 1 41.663 1C19.2055 1 1 19.2055 1 41.663C1 64.1206 19.2055 82.3261 41.663 82.3261C59.2695 82.3261 74.2624 71.1364 79.9182 55.4806' stroke='%238993BE' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M62.1442 6.52702C65.6967 8.6023 68.9061 11.2009 71.6667 14.2172' stroke='%238993BE' stroke-width='2' stroke-linecap='round'/%3E%3C/svg%3E"), url("data:image/svg+xml,%3Csvg width='152' height='150' viewBox='0 0 152 150' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M147.38 72.8499C153.437 95.1096 155.456 105.228 141.323 129.511C127.191 153.794 94.8556 149.747 72.6806 149.747C32.5402 149.747 0 117.131 0 76.8971C0 36.6632 34.5591 0 74.6995 0C114.84 0 141.323 50.5902 147.38 72.8499Z' fill='%23555C7C'/%3E%3C/svg%3E"); + } + .search-no-results::before { + background-image: url("data:image/svg+xml,%3Csvg width='154' height='148' viewBox='0 0 154 148' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cline x1='72.7688' y1='68.1962' x2='88.5602' y2='83.9877' stroke='%238993BE' stroke-width='2'/%3E%3Crect x='97.8234' y='75.055' width='76.9574' height='23.2664' rx='11.6332' transform='rotate(45 97.8234 75.055)' stroke='%238993BE' stroke-width='2'/%3E%3Cpath d='M81.3085 50.7432C81.9744 47.8236 82.3261 44.7844 82.3261 41.6631C82.3261 35.0792 80.7613 28.8607 77.9834 23.3593' stroke='%238993BE' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M56.2702 3.70245C51.7367 1.95686 46.8116 1 41.663 1C19.2055 1 1 19.2055 1 41.663C1 64.1206 19.2055 82.3261 41.663 82.3261C59.2695 82.3261 74.2624 71.1364 79.9182 55.4806' stroke='%238993BE' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M62.1442 6.52701C65.6967 8.60229 68.9061 11.2009 71.6667 14.2172' stroke='%238993BE' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='M11.3086 38.2034C11.3086 38.2034 13.5167 41.5575 16.9242 41.3193C20.3318 41.081 22.0516 37.4522 22.0516 37.4522M18.1449 58.7766C18.1449 58.7766 23.8094 54.872 31.061 54.3649C38.3125 53.8578 43.9281 56.9737 43.9281 56.9737M34.2526 36.599C34.2526 36.599 36.2089 39.9708 39.8682 39.7149C43.5276 39.459 44.9956 35.8478 44.9956 35.8478' stroke='%238993BE' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E%0A"), url("data:image/svg+xml,%3Csvg width='152' height='150' viewBox='0 0 152 150' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M147.38 72.8499C153.437 95.1096 155.456 105.228 141.323 129.511C127.191 153.794 94.8556 149.747 72.6806 149.747C32.5402 149.747 0 117.131 0 76.8971C0 36.6632 34.5591 0 74.6995 0C114.84 0 141.323 50.5902 147.38 72.8499Z' fill='%23555C7C'/%3E%3C/svg%3E"); + } + .page-not-found::before { + background-image: url("data:image/svg+xml,%3Csvg width='160' height='109' viewBox='0 0 160 109' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 7.99999C1 4.134 4.13401 1 8 1H95.1429H152C155.866 1 159 4.13401 159 8V100.571C159 104.437 155.866 107.571 152 107.571H8C4.13401 107.571 1 104.437 1 100.571V7.99999Z' stroke='%238993BE' stroke-width='2'/%3E%3Cline x1='1' y1='17.8571' x2='83.5714' y2='17.8571' stroke='%238993BE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='100.429' y1='17.8571' x2='116.714' y2='17.8571' stroke='%238993BE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='128.429' y1='17.8571' x2='159' y2='17.8571' stroke='%238993BE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Ccircle cx='8.57138' cy='9.7142' r='1.85714' stroke='%238993BE' stroke-width='2'/%3E%3Ccircle cx='17.7142' cy='9.7142' r='1.85714' stroke='%238993BE' stroke-width='2'/%3E%3Ccircle cx='26.8573' cy='9.7142' r='1.85714' stroke='%238993BE' stroke-width='2'/%3E%3Cline x1='33.9856' y1='38.2856' x2='41.4608' y2='45.7608' stroke='%238993BE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='34.4762' y1='45.761' x2='41.9513' y2='38.2858' stroke='%238993BE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='105.414' y1='38.2856' x2='112.889' y2='45.7608' stroke='%238993BE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cline x1='105.905' y1='45.761' x2='113.38' y2='38.2858' stroke='%238993BE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M49.8545 69.0772C49.8545 69.0772 57.5257 73.6485 72.1402 73.6485C86.7117 73.6485 94.4259 69.0771 94.4259 69.0771' stroke='%238993BE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M72.1526 78.5698C72.3093 86.3002 68.3437 92.6498 63.2953 92.7521C58.2469 92.8544 54.0273 86.6706 53.8707 78.9402C53.8129 76.0901 54.3155 73.4277 55.2261 71.1969' stroke='%238993BE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M64.6687 73.7268C64.8334 73.1997 64.5396 72.6388 64.0125 72.4741C63.4853 72.3093 62.9245 72.6031 62.7597 73.1303L64.6687 73.7268ZM61.8707 88.7359C61.9615 89.2807 62.4768 89.6487 63.0215 89.5579C63.5663 89.4671 63.9343 88.9519 63.8435 88.4071L61.8707 88.7359ZM62.7597 73.1303C61.2791 77.8683 60.9909 83.4569 61.8707 88.7359L63.8435 88.4071C63.009 83.4002 63.2922 78.1317 64.6687 73.7268L62.7597 73.1303Z' fill='%238993BE'/%3E%3C/svg%3E%0A"), url("data:image/svg+xml,%3Csvg width='172' height='170' viewBox='0 0 172 170' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M85.7456 16.9208C110.886 -6.48267 132.959 -4.28052 156.498 15.4794C180.037 35.2393 174.047 84.4687 153.005 119.028C128.204 159.761 84.2197 174.845 40.8539 167.344C-2.51188 159.842 -6.55002 107.678 7.88005 65.9713C22.3101 24.2642 60.6055 40.3243 85.7456 16.9208Z' fill='%23555C7C'/%3E%3C/svg%3E%0A"); + } +} diff --git a/src/docs/styles/_menu.scss b/src/docs/styles/_menu.scss new file mode 100644 index 000000000..2ecb14f6b --- /dev/null +++ b/src/docs/styles/_menu.scss @@ -0,0 +1,84 @@ +// =================================================== +// Menu +// =================================================== +.menu { + // z-index: 8; + transition: 0.3s ease all; + // Menu container + background: var(--menu-back-color); + border-top: 1px solid var(--menu-border-color); + @media screen and (max-width: calc(#{$layout-medium-breakpoint} - 1px)) { + position: fixed; + bottom: 0; + width: 100vw; + z-index: 1001; + } + @media screen and (min-width: $layout-medium-breakpoint) { + border-top: none; + border-right: 1px solid var(--menu-border-color); + padding-top: 17vh; + } + @media screen and (min-width: $layout-large-breakpoint) { + padding-top: 23.5vh; + } + // Menu buttons + .menu-button { + cursor: pointer; + transition: 0.3s ease all; + background: transparent; + color: var(--menu-fore-color); + display: inline-block; + width: 25%; + height: 61px; + margin: 0; + text-align: center; + margin-top: 0.5rem; + border: none; + line-height: 61px; + @media screen and (min-width: $layout-medium-breakpoint) { + height: 12.5vh; + width: 100%; + margin-top: 1vh; + margin-bottom: 4vh; + } + @media screen and (min-width: $layout-large-breakpoint) { + margin-bottom: 1vh; + } + &:hover, &:focus { + outline: 0; + color: var(--menu-active-fore-color); + } + &.active { + color: var(--menu-active-fore-color); + svg { + color: var(--menu-active-fore-color); + } + } + svg { + color: var(--menu-fore-color); + } + &:last-of-type { + vertical-align: top; + } + } +} + +// Animate transition between light and dark mode +.cross-fade-leave { + transform: scale(1); +} +.cross-fade-leave.cross-fade-leave-active { + transition: all 0.3s cubic-bezier(0.47, 0, 0.745, 0.715); + transform: scale(0.1); +} +.cross-fade-enter { + transform: scale(0.1); +} +.cross-fade-enter.cross-fade-enter-active { + transition: all 0.3s cubic-bezier(0.215, 0.610, 0.355, 1); + transform: scale(0.95) +} +.cross-fade-height { + height: 61px; + transition: height 0.15s ease-in-out 0.15s; +} \ No newline at end of file diff --git a/src/docs/styles/_reset.scss b/src/docs/styles/_reset.scss new file mode 100644 index 000000000..e4744fb45 --- /dev/null +++ b/src/docs/styles/_reset.scss @@ -0,0 +1,135 @@ +// Set up some basic styling for everything +html { + font-size: 16px; + scroll-behavior: smooth; +} +html, * { + font-family: 'Noto Sans', Helvetica, sans-serif; + line-height: 1.5; + // Prevent adjustments of font size after orientation changes in mobile. + -webkit-text-size-adjust: 100%; +} +* { + font-size: 1rem; + font-weight: 400; +} +// Apply fixes and defaults as necessary for modern browsers only +a, b, del, em, i, ins, q, span, strong, u { + transition: 0.3s ease all; + font-size: 1em; // Fix for elements inside headings not displaying properly. +} +body { + margin: 0; + color: var(--fore-color); + background: var(--background-color); + overflow-x: hidden; + &.card-page { + background: var(--card-page-color); + } +} +// 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: 1.2; + margin: 0.75rem 0.5rem; +} +h1 { + font-size: 6rem; + &.landing-title { + font-size: 3rem; + text-align: center; + & small { + display: block; + margin-top: 0.5rem; + color: var(--secondary-fore-color); + } + margin-bottom: 4rem; + } +} +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: 0.5rem; +} +ol, ul { + margin: 0.5rem; + padding-left: 1rem; +} +b, strong { + font-weight: 600; +} +hr { + // Fixes and defaults for styling + box-sizing: content-box; + border: 0; + // Actual styling using variables + line-height: 1.25em; + margin: 0.5rem; + height: 1px; + background: linear-gradient(to right, transparent, var(--border-color) 20%, var(--border-color) 80%, transparent); +} +sup, sub, code, kbd { + line-height: 0; + position: relative; + vertical-align: baseline; +} +a { + text-decoration: none; + &:link{ + color: var(--a-link-color); + } + &:visited { + color: var(--a-visited-color); + } + &:hover, &:focus { + text-decoration: underline; + } +} diff --git a/src/docs/styles/_search.scss b/src/docs/styles/_search.scss new file mode 100644 index 000000000..ccdae2fb7 --- /dev/null +++ b/src/docs/styles/_search.scss @@ -0,0 +1,57 @@ +// =================================================== +// Search +// =================================================== +[type="search"].search-box { + transition: 0.3s ease all; + margin: 0.25rem 0.875rem; + width: calc(100% - 1.75rem); + background: var(--search-back-color); + box-shadow: 0px 4px 8px var(--search-shadow-color); + &:focus { + box-shadow: 0px 6px 12px var(--search-shadow-focus-color); + } + border-radius: 1.125rem; + outline: none; + box-sizing: border-box; + border: none; + padding-left: 2.5rem; + font-size: 1.125rem; + font-weight: 300; + line-height: 2; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24' fill='none' stroke='%23C5C6CD' stroke-width='1.5' stroke-linecap='round' strokelinejoin='round' className='feather feather-search'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position-x: 10px; + background-position-y: 8px; + color: var(--search-fore-color); + &::placeholder { + color: var(--search-placeholder-color); + } + @media screen and (min-width: $layout-large-breakpoint) { + font-size: 1.375rem; + line-height: 1.8; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23C5C6CD' stroke-width='1.5' stroke-linecap='round' strokelinejoin='round' className='feather feather-search'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E"); + } +} +// Dark mode +.page-container.dark [type="search"].search-box { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24' fill='none' stroke='%23999EBD' stroke-width='1.5' stroke-linecap='round' strokelinejoin='round' className='feather feather-search'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E"); + @media screen and (min-width: $layout-large-breakpoint) { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23999EBD' stroke-width='1.5' stroke-linecap='round' strokelinejoin='round' className='feather feather-search'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E"); + } +} + +.search-box::-webkit-input-placeholder { + font-family: 'Noto Sans', Helvetica, sans-serif; +} + +.search-box:-ms-input-placeholder { + font-family: 'Noto Sans', Helvetica, sans-serif; +} + +.search-box:-moz-placeholder { + font-family: 'Noto Sans', Helvetica, sans-serif; +} + +.search-box::-moz-placeholder { + font-family: 'Noto Sans', Helvetica, sans-serif; +} \ No newline at end of file diff --git a/src/docs/styles/_toast.scss b/src/docs/styles/_toast.scss new file mode 100644 index 000000000..ef1de925b --- /dev/null +++ b/src/docs/styles/_toast.scss @@ -0,0 +1,33 @@ +// =================================================== +// Toast +// =================================================== +.toast { + position: fixed; + bottom: 16px; + margin-bottom: 0; + font-size: 0.75rem; + line-height: 1.5; + left: 50%; + transform: translate(-50%, -50%); + z-index: 1111; + color: var(--toast-fore-color); + background: var(--toast-back-color); + border-radius: 2rem; + padding: 0.375rem 1.375rem 0.375rem 2.75rem; + box-shadow: 0px 0.25rem 0.5rem var(--toast-shadow-color); + transition: all 0.3s ease; + // Toast icon + &::before { + position: absolute; + content: ''; + display: block; + top: 1px; + left: 1px; + height: 28px; + background: white; + width: 28px; + border-radius: 100%; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2305A864' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-check'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E"); + background-position: center; + } +} \ No newline at end of file diff --git a/src/docs/styles/index.scss b/src/docs/styles/index.scss new file mode 100644 index 000000000..5efbdc51e --- /dev/null +++ b/src/docs/styles/index.scss @@ -0,0 +1,14 @@ +// Layout breakpoints +$layout-medium-breakpoint: 600px; +$layout-large-breakpoint: 900px; + +@import 'fonts'; +@import 'colors'; +@import 'reset'; +@import 'layout'; +@import 'menu'; +@import 'search'; +@import 'button'; +@import 'card'; +@import 'code'; +@import 'toast'; diff --git a/src/docs/templates/SnippetPage.js b/src/docs/templates/SnippetPage.js new file mode 100644 index 000000000..2dfbf3800 --- /dev/null +++ b/src/docs/templates/SnippetPage.js @@ -0,0 +1,113 @@ +import React from 'react'; +import { graphql } from 'gatsby'; +import { connect } from 'react-redux'; + +import Meta from '../components/Meta'; +import Shell from '../components/Shell'; +import SnippetCard from '../components/SnippetCard'; +import BackArrowIcon from '../components/SVGs/BackArrowIcon'; +import AniLink from 'gatsby-plugin-transition-link/AniLink'; + +// =================================================== +// Individual snippet page template +// =================================================== +const SnippetPage = props => { + const post = props.data.markdownRemark; + const postData = props.data.snippetDataJson.data.find( + v => v.title === post.frontmatter.title, + ); + + return ( + <> + + + + +   Back to {props.lastPageTitle} + + + + + ); +}; + +export default connect( + state => ({ + isDarkMode: state.app.isDarkMode, + lastPageTitle: state.app.lastPageTitle, + lastPageUrl: state.app.lastPageUrl, + searchQuery: state.app.searchQuery, + }), + null, +)(SnippetPage); + +export const pageQuery = graphql` + query BlogPostBySlug($slug: String!) { + logo: file(absolutePath: { regex: "/logo_reverse_md.png/" }) { + id + childImageSharp { + fixed(height: 45, width: 45) { + src + } + } + } + site { + siteMetadata { + title + author + } + } + allMarkdownRemark { + edges { + node { + fields { + slug + } + fileAbsolutePath + frontmatter { + title + } + } + } + } + markdownRemark(fields: { slug: { eq: $slug } }) { + id + fields { + slug + } + excerpt(pruneLength: 160) + html + frontmatter { + title + } + } + snippetDataJson(meta: { type: { eq: "snippetArray" }, scope: {eq: "./snippets"} }) { + data { + title + id + attributes { + text + codeBlocks { + es6 + example + } + tags + } + } + } + } +`; diff --git a/src/docs/templates/TagPage.js b/src/docs/templates/TagPage.js new file mode 100644 index 000000000..182ce604a --- /dev/null +++ b/src/docs/templates/TagPage.js @@ -0,0 +1,89 @@ +import React from 'react'; +import { graphql } from 'gatsby'; +import { connect } from 'react-redux'; +import { pushNewPage } from '../state/app'; + +import Meta from '../components/Meta'; +import Shell from '../components/Shell'; +import SnippetCard from '../components/SnippetCard'; + +import { capitalize, getRawCodeBlocks as getCodeBlocks } from '../util'; + +// =================================================== +// Individual snippet category/tag page +// =================================================== +const TagRoute = props => { + const posts = props.data.allMarkdownRemark.edges; + const tag = props.pageContext.tag; + + React.useEffect(() => { + props.dispatch(pushNewPage(capitalize(tag), props.path)); + }, []); + + return ( + <> + + +

{capitalize(tag)}

+

Click on a snippet's name to view its code.

+ {posts && + posts.map(({ node }) => ( + v.trim()), + id: node.fields.slug.slice(1), + }} + isDarkMode={props.isDarkMode} + /> + ))} +
+ + ); +}; + +export default connect( + state => ({ + isDarkMode: state.app.isDarkMode, + lastPageTitle: state.app.lastPageTitle, + lastPageUrl: state.app.lastPageUrl, + searchQuery: state.app.searchQuery, + }), + null, +)(TagRoute); + +export const tagPageQuery = graphql` + query TagPage($tagRegex: String) { + site { + siteMetadata { + title + } + } + allMarkdownRemark( + limit: 1000 + sort: { fields: [frontmatter___title], order: ASC } + filter: { frontmatter: { tags: { regex: $tagRegex } } } + ) { + totalCount + edges { + node { + excerpt(pruneLength: 400) + id + html + rawMarkdownBody + fields { + slug + } + frontmatter { + title + tags + } + } + } + } + } +`; diff --git a/src/docs/util/index.js b/src/docs/util/index.js new file mode 100644 index 000000000..8900689ec --- /dev/null +++ b/src/docs/util/index.js @@ -0,0 +1,112 @@ +const config = require('../../../config'); + +// Capitalizes the first letter of a string +const capitalize = (str, lowerRest = false) => + str.slice(0, 1).toUpperCase() + + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1)); + +// Get the textual content in a gatsby page +const getTextualContent = str => { + const regex = /([\s\S]*?)
{ + results.push(match); + }); + } + return results[1]; +}; + +// Gets the code blocks in a gatsby page +const getCodeBlocks = str => { + const regex = //g; + let results = []; + let m = null; + while ((m = regex.exec(str)) !== null) { + if (m.index === regex.lastIndex) regex.lastIndex += 1; + // eslint-disable-next-line + m.forEach((match, groupIndex) => { + results.push(match); + }); + } + const replacer = new RegExp( + `
([\\s\\S]*?)
`, + 'g', + ); + results = results.map(v => v.replace(replacer, '$1').trim()); + return { + code: results[0], + example: results[1], + }; +}; + +// Optimizes nodes in an HTML string +const optimizeNodes = (data, regexp, replacer) => { + let count = 0; + let output = data; + do { + output = output.replace(regexp, replacer); + count = 0; + while (regexp.exec(output) !== null) ++count; + } while (count > 0); + return output; +}; +const optimizeAllNodes = html => { + let output = html; + // Optimize punctuation nodes + output = optimizeNodes( + output, + /([^\0<]*?)<\/span>([\n\r\s]*)([^\0]*?)<\/span>/gm, + (match, p1, p2, p3) => + `${p1}${p2}${p3}`, + ); + // Optimize operator nodes + output = optimizeNodes( + output, + /([^\0<]*?)<\/span>([\n\r\s]*)([^\0]*?)<\/span>/gm, + (match, p1, p2, p3) => + `${p1}${p2}${p3}`, + ); + // Optimize keyword nodes + output = optimizeNodes( + output, + /([^\0<]*?)<\/span>([\n\r\s]*)([^\0]*?)<\/span>/gm, + (match, p1, p2, p3) => `${p1}${p2}${p3}`, + ); + return output; +}; + +// Gets the code blocks for a snippet file. +const getRawCodeBlocks = str => { + const regex = /```[.\S\s]*?```/g; + let results = []; + let m = null; + while ((m = regex.exec(str)) !== null) { + if (m.index === regex.lastIndex) regex.lastIndex += 1; + // eslint-disable-next-line + m.forEach((match, groupIndex) => { + results.push(match); + }); + } + const replacer = new RegExp( + `\`\`\`${config.language}([\\s\\S]*?)\`\`\``, + 'g', + ); + results = results.map(v => v.replace(replacer, '$1').trim()); + return { + code: results[0], + example: results[1], + }; +}; + +module.exports = { + capitalize, + getTextualContent, + getCodeBlocks, + optimizeNodes, + optimizeAllNodes, + getRawCodeBlocks, +};