diff --git a/docs/adapter.html b/docs/adapter.html index 5cfdc927f..36f33fa90 100644 --- a/docs/adapter.html +++ b/docs/adapter.html @@ -149,4 +149,4 @@ Object.assig 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 + \ No newline at end of file diff --git a/docs/archive.html b/docs/archive.html index f319124cf..e6b71c266 100644 --- a/docs/archive.html +++ b/docs/archive.html @@ -239,4 +239,4 @@ window.speechSynthesis.speak(msg); };
speechSynthesis('Hello, World'); // // plays the message
-

\ No newline at end of file +
\ No newline at end of file diff --git a/docs/array.html b/docs/array.html index 57b23c77e..97f9ad25d 100644 --- a/docs/array.html +++ b/docs/array.html @@ -518,4 +518,4 @@ [
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 + \ No newline at end of file diff --git a/docs/beginner.html b/docs/beginner.html index 06f319cca..9c57840f2 100644 --- a/docs/beginner.html +++ b/docs/beginner.html @@ -135,4 +135,4 @@

truncateString

Truncates a string up to a specified length.

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

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

\ No newline at end of file +
\ No newline at end of file diff --git a/docs/browser.html b/docs/browser.html index 11df27a04..710bf273d 100644 --- a/docs/browser.html +++ b/docs/browser.html @@ -331,4 +331,4 @@ recorder.sta (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) );
UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/date.html b/docs/date.html index 8992ea30a..e435d08d4 100644 --- a/docs/date.html +++ b/docs/date.html @@ -115,4 +115,4 @@ };
tomorrow(); // 2017-12-27 (if current date is 2017-12-26)
 tomorrow(true); // 2017-12-27T00:00:00 (if current date is 2017-12-26)
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/function.html b/docs/function.html index f341313b6..996af8fe8 100644 --- a/docs/function.html +++ b/docs/function.html @@ -269,4 +269,4 @@ console.log< };
var f = n => (n > 50 ? false : [-n, n + 10]);
 unfold(f, 10); // [-10, -20, -30, -40, -50]
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/index.html b/docs/index.html index a85fa3212..07fcfad76 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,263 +1,22 @@ - - - - - - - - 30 seconds of code - - - - - - - - - - - - - -
-

logo 30 seconds of code

-

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

- -
-
-
-
-
- -

295
snippets

-
-
- -

113
contributors

-
-
- -

3029
commits

-
-
- -

19461
stars

-
-
-
-
-
-
-
-

Our philosophy

-

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


-
-
-
-
-
-
-
-
-

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

-
-

-
-
-
-
-

Today's picks

-

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

-
- - -

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);
+30 seconds of code

logo 30 seconds of code

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

295
snippets

113
contributors

3029
commits

19461
stars

Our philosophy

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


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


Today's picks

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

compose

Performs right-to-left function composition.

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

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

deepFlatten

Deep flattens an array.

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

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

palindrome

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

Convert string String.toLowerCase() and use String.replace() to remove non-alphanumeric characters from it. Then, String.split('') into individual characters, Array.reverse(), String.join('') and compare to the original, unreversed string, after converting it String.tolowerCase().

const palindrome = str => {
+  const s = str.toLowerCase().replace(/[\W_]/g, '');
+  return (
+    s ===
+    s
+      .split('')
+      .reverse()
+      .join('')
+  );
 };
-
binomialCoefficient(8, 2); // 28
-
-

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

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

Getting started

-
-
-
-
-
-

Related projects

-

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

-
-
-
-
-
-

Top contributors

-
- - -
- flxwu - Felix Wu -
-
- atomiks - atomiks -
- -
- kriadmin - Rohit Tanwar -
- - -
-
-
-
-
-

How to contribute

-

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

-
- 1 -
-

Create

-

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

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

Tag

-

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

-
-
-
- 3 -
-

Test

-

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

-
-
-
- 4 -
-

Pull request

-

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

-
-
-

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

-
-
-
-
- - - - +}; \ No newline at end of file diff --git a/docs/math.html b/docs/math.html index 7897cb4c0..f7acff94e 100644 --- a/docs/math.html +++ b/docs/math.html @@ -272,4 +272,4 @@ own individual rating by supplying it as the third argument. Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
toSafeInteger('3.2'); // 3
 toSafeInteger(Infinity); // 9007199254740991
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/node.html b/docs/node.html index 02c227a18..3f98383fa 100644 --- a/docs/node.html +++ b/docs/node.html @@ -151,4 +151,4 @@ console.log< (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) );
UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/object.html b/docs/object.html index 006298a4f..ce9c7460d 100644 --- a/docs/object.html +++ b/docs/object.html @@ -329,4 +329,4 @@ Foo.prototypereturn acc; }, {});
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/string.html b/docs/string.html index 4217f04a3..1f22cdf4d 100644 --- a/docs/string.html +++ b/docs/string.html @@ -258,4 +258,4 @@

words

Converts a given string into an array of words.

Use String.split() with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use Array.filter() to remove any empty strings. Omit the second argument to use the default regexp.

const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
 
words('I love javaScript!!'); // ["I", "love", "javaScript"]
 words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/type.html b/docs/type.html index e70353aa6..d79b0c8c7 100644 --- a/docs/type.html +++ b/docs/type.html @@ -178,4 +178,4 @@
isValidJSON('{"name":"Adam","age":20}'); // true
 isValidJSON('{"name":"Adam",age:"20"}'); // false
 isValidJSON(null); // true
-
\ No newline at end of file + \ No newline at end of file diff --git a/docs/utility.html b/docs/utility.html index 7a7d9e905..fc656d644 100644 --- a/docs/utility.html +++ b/docs/utility.html @@ -269,4 +269,4 @@ Logs: { yesNo('yes'); // true yesNo('No'); // false yesNo('Foo', true); // true - \ No newline at end of file + \ No newline at end of file diff --git a/scripts/web.js b/scripts/web.js index e52df1529..101f0d976 100644 --- a/scripts/web.js +++ b/scripts/web.js @@ -149,6 +149,22 @@ if(!util.isTravisCI() || (util.isTravisCI() && (process.env['TRAVIS_EVENT_TYPE'] contribs = resContributors.headers.link.split('&').slice(-1)[0].replace(/[^\d]/g,''), stars = resStars.headers.link.split('&').slice(-1)[0].replace(/[^\d]/g,''); indexStaticFile = indexStaticFile.replace(/\$snippet-count/g, Object.keys(snippets).length).replace(/\$commit-count/g,commits).replace(/\$contrib-count/g,contribs).replace(/\$star-count/g,stars); + indexStaticFile = minify(indexStaticFile, { + collapseBooleanAttributes: true, + collapseWhitespace: true, + decodeEntities: false, + minifyCSS: true, + minifyJS: true, + keepClosingSlash: true, + processConditionalComments: true, + removeAttributeQuotes: false, + removeComments: true, + removeEmptyAttributes: false, + removeOptionalTags: false, + removeScriptTypeAttributes: false, + removeStyleLinkTypeAttributes: false, + trimCustomFragments: true + }); // Generate 'index.html' file fs.writeFileSync(path.join(docsPath, 'index.html'), indexStaticFile); console.log(`${chalk.green('SUCCESS!')} index.html file generated!`); diff --git a/static-parts/index.html b/static-parts/index.html index 5633b5258..7db80bafe 100644 --- a/static-parts/index.html +++ b/static-parts/index.html @@ -109,36 +109,36 @@

Top contributors

- flxwu + flxwu Felix Wu
- atomiks + atomiks atomiks
@@ -199,7 +199,7 @@ window.onload = function(){ runCounter(counters[1],0,values[1],steps[1]); runCounter(counters[2],0,values[2],steps[2]); runCounter(counters[3],0,values[3],steps[3]); - document.querySelector('button.next').addEventListener('click', e => { + document.querySelector('button.next').addEventListener('click', function(e){ let selected = document.getElementById('pick-slider').querySelector('.selected'); if(selected == Array.from(document.querySelectorAll('.card.fluid.pick')).slice(-1)[0]) { @@ -211,7 +211,7 @@ window.onload = function(){ selected.className = 'card fluid pick'; }); - document.querySelector('button.previous').addEventListener('click', e => { + document.querySelector('button.previous').addEventListener('click', function(e){ let selected = document.getElementById('pick-slider').querySelector('.selected'); if(selected == document.querySelector('.card.fluid.pick')) { @@ -248,7 +248,7 @@ window.onload = function(){ }, false); } -const runCounter = (selector, start, end, increment = 1, duration = 2000) => { +function runCounter(selector, start, end, increment = 1, duration = 2000){ let current = start, step = end > start ? increment : -increment, timer = setInterval(function() { @@ -259,7 +259,7 @@ const runCounter = (selector, start, end, increment = 1, duration = 2000) => { }, Math.abs(Math.floor(duration / (end - start)))); }; -const elementIsVisibleInViewport = (el, partiallyVisible = false) => { +function elementIsVisibleInViewport(el, partiallyVisible = false) { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible