From a387a4d6f7bf000a32a1f58d33619ac59d1613ec Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 23 Jun 2018 12:42:22 +0300 Subject: [PATCH 1/8] Update analyze.js --- scripts/analyze.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/analyze.js b/scripts/analyze.js index cbe1286ec..3d535915b 100644 --- a/scripts/analyze.js +++ b/scripts/analyze.js @@ -22,15 +22,15 @@ let snippetTokens = {data: snippetsData.data.map(snippet => { attributes: { codeLength: snippet.attributes.codeBlocks[0].trim().length, tokenCount: tokens.length, - functionCount: tokens.filter(t => t.type == 'function').length, - operatorCount: tokens.filter(t => t.type == 'operator').length, - keywordCount: tokens.filter(t => t.type == 'keyword').length, - distinctFunctionCount: [...new Set(tokens.filter(t => t.type == 'function').map(t => t.content))].length + functionCount: tokens.filter(t => t.type === 'function').length, + operatorCount: tokens.filter(t => t.type === 'operator').length, + keywordCount: tokens.filter(t => t.type === 'keyword').length, + distinctFunctionCount: [...new Set(tokens.filter(t => t.type === 'function').map(t => t.content))].length }, meta: { hash: snippet.meta.hash } - } + }; }), meta: { specification: "http://jsonapi.org/format/"}}; let snippetArchiveTokens = {data: snippetsArchiveData.data.map(snippet => { let tokens = prism.tokenize(snippet.attributes.codeBlocks[0], prism.languages.javascript, 'javascript'); From 770922a9d2d4cc4f902441aa937206dbc0b47a35 Mon Sep 17 00:00:00 2001 From: catchonme Date: Sat, 23 Jun 2018 18:46:47 +0800 Subject: [PATCH 2/8] fix type and make strict equal --- README.md | 76 ++++++++++++++++++------------------- snippets/matchesWith.md | 2 +- snippets/unflattenObject.md | 2 +- 3 files changed, 40 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 0fe4fa652..94613e8c3 100644 --- a/README.md +++ b/README.md @@ -503,16 +503,16 @@ const firstTwoMax = ary(Math.max, 2);
[⬆ Back to top](#table-of-contents) -### 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. - +### call + +Given a key and a set of arguments, call them when given a context. Primarily useful in composition. + +Use a closure to call a stored key with stored arguments. + ```js const call = (key, ...args) => context => context[key](...args); -``` - +``` +
Examples @@ -524,23 +524,23 @@ const map = call.bind(null, 'map'); Promise.resolve([1, 2, 3]) .then(map(x => 2 * x)) .then(console.log); //[ 2, 4, 6 ] -``` +```

[⬆ Back to top](#table-of-contents) -### collectInto - -Changes a function that accepts an array into a variadic function. - -Given a function, return a closure that collects all inputs into an array-accepting function. - +### collectInto + +Changes a function that accepts an array into a variadic function. + +Given a function, return a closure that collects all inputs into an array-accepting function. + ```js const collectInto = fn => (...args) => fn(args); -``` - +``` +
Examples @@ -550,23 +550,23 @@ 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) -``` +```

[⬆ Back to top](#table-of-contents) -### flip - -Flip takes a function as an argument, then makes the first argument the last. - -Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. - +### flip + +Flip takes a function as an argument, then makes the first argument the last. + +Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. + ```js const flip = fn => (first, ...rest) => fn(...rest, first); -``` - +``` +
Examples @@ -578,7 +578,7 @@ let mergePerson = mergeFrom.bind(null, a); mergePerson(b); // == b b = {}; Object.assign(b, a); // == b -``` +```
@@ -754,23 +754,23 @@ rearged('b', 'c', 'a'); // ['a', 'b', 'c']
[⬆ Back to top](#table-of-contents) -### spreadOver - -Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. - -Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function. - +### spreadOver + +Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. + +Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function. + ```js const spreadOver = fn => argsArr => fn(...argsArr); -``` - +``` +
Examples ```js const arrayMax = spreadOver(Math.max); arrayMax([1, 2, 3]); // 3 -``` +```
@@ -6694,7 +6694,7 @@ const matchesWith = (obj, source, fn) => key => obj.hasOwnProperty(key) && fn ? fn(obj[key], source[key], key, obj, source) - : obj[key] == source[key] + : obj[key] === source[key] ); ``` @@ -7114,7 +7114,7 @@ truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex ### unflattenObject ![advanced](/advanced.svg) -Unlatten an object with the paths for keys. +Unflatten an object with the paths for keys. Use `Object.keys(obj)` combined with `Array.reduce()` to convert flattened path node to a leaf node. If the value of a key contains a dot delimiter (`.`), use `Array.split('.')`, string transformations and `JSON.parse()` to create an object, then `Object.assign()` to create the leaf node. diff --git a/snippets/matchesWith.md b/snippets/matchesWith.md index a04814191..ba47ce63a 100644 --- a/snippets/matchesWith.md +++ b/snippets/matchesWith.md @@ -11,7 +11,7 @@ const matchesWith = (obj, source, fn) => key => obj.hasOwnProperty(key) && fn ? fn(obj[key], source[key], key, obj, source) - : obj[key] == source[key] + : obj[key] === source[key] ); ``` diff --git a/snippets/unflattenObject.md b/snippets/unflattenObject.md index b4f78bd96..1d4f6a9e6 100644 --- a/snippets/unflattenObject.md +++ b/snippets/unflattenObject.md @@ -1,6 +1,6 @@ ### unflattenObject -Unlatten an object with the paths for keys. +Unflatten an object with the paths for keys. Use `Object.keys(obj)` combined with `Array.reduce()` to convert flattened path node to a leaf node. If the value of a key contains a dot delimiter (`.`), use `Array.split('.')`, string transformations and `JSON.parse()` to create an object, then `Object.assign()` to create the leaf node. From d56e750cb0a68a9581d6c0c9f23b2455a60f406f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 23 Jun 2018 16:36:25 +0300 Subject: [PATCH 3/8] Update matchesWith.md --- snippets/matchesWith.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/matchesWith.md b/snippets/matchesWith.md index ba47ce63a..a04814191 100644 --- a/snippets/matchesWith.md +++ b/snippets/matchesWith.md @@ -11,7 +11,7 @@ const matchesWith = (obj, source, fn) => key => obj.hasOwnProperty(key) && fn ? fn(obj[key], source[key], key, obj, source) - : obj[key] === source[key] + : obj[key] == source[key] ); ``` From 51029ecbd3837ed98c789122f581bca412102696 Mon Sep 17 00:00:00 2001 From: 30secondsofcode <30secondsofcode@gmail.com> Date: Sat, 23 Jun 2018 13:39:46 +0000 Subject: [PATCH 4/8] Travis build: 16 --- README.md | 74 ++++++++++++++++++++++++------------------------ docs/object.html | 2 +- 2 files changed, 38 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 94613e8c3..8ce0393a2 100644 --- a/README.md +++ b/README.md @@ -503,16 +503,16 @@ const firstTwoMax = ary(Math.max, 2);
[⬆ Back to top](#table-of-contents) -### 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. - +### call + +Given a key and a set of arguments, call them when given a context. Primarily useful in composition. + +Use a closure to call a stored key with stored arguments. + ```js const call = (key, ...args) => context => context[key](...args); -``` - +``` +
Examples @@ -524,23 +524,23 @@ const map = call.bind(null, 'map'); Promise.resolve([1, 2, 3]) .then(map(x => 2 * x)) .then(console.log); //[ 2, 4, 6 ] -``` +```

[⬆ Back to top](#table-of-contents) -### collectInto - -Changes a function that accepts an array into a variadic function. - -Given a function, return a closure that collects all inputs into an array-accepting function. - +### collectInto + +Changes a function that accepts an array into a variadic function. + +Given a function, return a closure that collects all inputs into an array-accepting function. + ```js const collectInto = fn => (...args) => fn(args); -``` - +``` +
Examples @@ -550,23 +550,23 @@ 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) -``` +```

[⬆ Back to top](#table-of-contents) -### flip - -Flip takes a function as an argument, then makes the first argument the last. - -Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. - +### flip + +Flip takes a function as an argument, then makes the first argument the last. + +Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. + ```js const flip = fn => (first, ...rest) => fn(...rest, first); -``` - +``` +
Examples @@ -578,7 +578,7 @@ let mergePerson = mergeFrom.bind(null, a); mergePerson(b); // == b b = {}; Object.assign(b, a); // == b -``` +```
@@ -754,23 +754,23 @@ rearged('b', 'c', 'a'); // ['a', 'b', 'c']
[⬆ Back to top](#table-of-contents) -### spreadOver - -Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. - -Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function. - +### spreadOver + +Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. + +Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function. + ```js const spreadOver = fn => argsArr => fn(...argsArr); -``` - +``` +
Examples ```js const arrayMax = spreadOver(Math.max); arrayMax([1, 2, 3]); // 3 -``` +```
@@ -6694,7 +6694,7 @@ const matchesWith = (obj, source, fn) => key => obj.hasOwnProperty(key) && fn ? fn(obj[key], source[key], key, obj, source) - : obj[key] === source[key] + : obj[key] == source[key] ); ``` diff --git a/docs/object.html b/docs/object.html index 801f6a078..495957bef 100644 --- a/docs/object.html +++ b/docs/object.html @@ -327,7 +327,7 @@ Foo.prototype// { '1': ['a', 'c'], '2': ['b'] }

truthCheckCollection

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

Use Array.every() to check if each passed object has the specified property and if it returns a truthy value.

const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
 
truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true
-

unflattenObjectadvanced

Unlatten an object with the paths for keys.

Use Object.keys(obj) combined with Array.reduce() to convert flattened path node to a leaf node. If the value of a key contains a dot delimiter (.), use Array.split('.'), string transformations and JSON.parse() to create an object, then Object.assign() to create the leaf node. Otherwise, add the appropriate key-value pair to the accumulator object.

const unflattenObject = obj =>
+

unflattenObjectadvanced

Unflatten an object with the paths for keys.

Use Object.keys(obj) combined with Array.reduce() to convert flattened path node to a leaf node. If the value of a key contains a dot delimiter (.), use Array.split('.'), string transformations and JSON.parse() to create an object, then Object.assign() to create the leaf node. Otherwise, add the appropriate key-value pair to the accumulator object.

const unflattenObject = obj =>
   Object.keys(obj).reduce((acc, k) => {
     if (k.indexOf('.') !== -1) {
       const keys = k.split('.');

From 9746b0bea91365d189b591777d890438ee577473 Mon Sep 17 00:00:00 2001
From: 30secondsofcode <30secondsofcode@gmail.com>
Date: Sat, 23 Jun 2018 19:31:04 +0000
Subject: [PATCH 5/8] Travis build: 18 [cron]

---
 docs/index.html            |   35 +-
 snippet_data/snippets.json |   12 +-
 test/elo/elo.js            |   11 +-
 test/equals/equals.js      |    2 +-
 test/testlog               | 3194 ++++++++++++++++++------------------
 5 files changed, 1632 insertions(+), 1622 deletions(-)

diff --git a/docs/index.html b/docs/index.html
index 348c46c2a..abe267a2f 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -1,17 +1,28 @@
-30 seconds of code

logo 30 seconds of code

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

309
snippets

118
contributors

3316
commits

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

any

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

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

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

hide

Hides all the elements specified.

Use the spread operator (...) and Array.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
-

longestItem

Takes any number of iterable objects or objects with a length property and returns the longest one.

Use Array.sort() to sort all arguments by length, return the first (longest) one.

const longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0];
-
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'
+30 seconds of code

logo 30 seconds of code

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

309
snippets

120
contributors

3333
commits

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

median

Returns the median of an array of numbers.

Find the middle of the array, use Array.sort() to sort the values. Return the number at the midpoint if length is odd, otherwise the average of the two middle numbers.

const median = arr => {
+  const mid = Math.floor(arr.length / 2),
+    nums = [...arr].sort((a, b) => a - b);
+  return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
+};
+
median([5, 6, 50, 1, -5]); // 5
+

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
+

unescapeHTML

Unescapes escaped HTML characters.

Use String.replace() with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).

const unescapeHTML = str =>
+  str.replace(
+    /&amp;|&lt;|&gt;|&#39;|&quot;/g,
+    tag =>
+      ({
+        '&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>'
 

Getting started


Related projects

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


How to contribute

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

1

Create

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

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

Tag

Run npm run tagger from your terminal, then open the tag_database file and tag your snippet appropriately. Multitagging is also supported, just make sure the first tag you specify is on of the major tags and the one that is most relevant to the 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.


30 seconds of code

logo 30 seconds of code

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

309
snippets

120
contributors

3333
commits

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

median

Returns the median of an array of numbers.

Find the middle of the array, use Array.sort() to sort the values. Return the number at the midpoint if length is odd, otherwise the average of the two middle numbers.

const median = arr => {
-  const mid = Math.floor(arr.length / 2),
-    nums = [...arr].sort((a, b) => a - b);
-  return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
+30 seconds of code

logo 30 seconds of code

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

309
snippets

120
contributors

3334
commits

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

ary

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

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

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

digitize

Converts a number to an array of digits.

Convert the number to a string, using the spread operator (...) to build an array. Use Array.map() and parseInt() to transform each value to an integer.

const digitize = n => [...`${n}`].map(i => parseInt(i));
+
digitize(123); // [1, 2, 3]
+

primes

Generates primes up to a given number, using the Sieve of Eratosthenes.

Generate an array from 2 to the given number. Use Array.filter() to filter out the values divisible by any number from 2 to the square root of the provided number.

const primes = num => {
+  let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2),
+    sqroot = Math.floor(Math.sqrt(num)),
+    numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2);
+  numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x)));
+  return arr;
 };
-
median([5, 6, 50, 1, -5]); // 5
-

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
-

unescapeHTML

Unescapes escaped HTML characters.

Use String.replace() with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).

const unescapeHTML = str =>
-  str.replace(
-    /&amp;|&lt;|&gt;|&#39;|&quot;/g,
-    tag =>
-      ({
-        '&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>'
+
primes(10); // [2,3,5,7]
 

Getting started


Related projects

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


How to contribute

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

1

Create

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

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

Tag

Run npm run tagger from your terminal, then open the tag_database file and tag your snippet appropriately. Multitagging is also supported, just make sure the first tag you specify is on of the major tags and the one that is most relevant to the 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.


30 seconds of code

logo 30 seconds of code

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

309
snippets

120
contributors

3334
commits

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

ary

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

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

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

digitize

Converts a number to an array of digits.

Convert the number to a string, using the spread operator (...) to build an array. Use Array.map() and parseInt() to transform each value to an integer.

const digitize = n => [...`${n}`].map(i => parseInt(i));
-
digitize(123); // [1, 2, 3]
-

primes

Generates primes up to a given number, using the Sieve of Eratosthenes.

Generate an array from 2 to the given number. Use Array.filter() to filter out the values divisible by any number from 2 to the square root of the provided number.

const primes = num => {
-  let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2),
-    sqroot = Math.floor(Math.sqrt(num)),
-    numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2);
-  numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x)));
-  return arr;
+30 seconds of code

logo 30 seconds of code

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

309
snippets

120
contributors

3335
commits

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

equals

Performs a deep comparison between two values to determine if they are equivalent.

Check if the two values are identical, if they are both Date objects with the same time, using Date.getTime() or if they are both non-object values with an equivalent value (strict comparison). Check if only one value is null or undefined or if their prototypes differ. If none of the above conditions are met, use Object.keys() to check if both values have the same number of keys, then use Array.every() to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.

const equals = (a, b) => {
+  if (a === b) return true;
+  if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
+  if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
+  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]));
 };
-
primes(10); // [2,3,5,7]
+
equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
+

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

unescapeHTML

Unescapes escaped HTML characters.

Use String.replace() with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).

const unescapeHTML = str =>
+  str.replace(
+    /&amp;|&lt;|&gt;|&#39;|&quot;/g,
+    tag =>
+      ({
+        '&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>'
 

Getting started


Related projects

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


How to contribute

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

1

Create

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

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

Tag

Run npm run tagger from your terminal, then open the tag_database file and tag your snippet appropriately. Multitagging is also supported, just make sure the first tag you specify is on of the major tags and the one that is most relevant to the 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.


30 seconds of code

logo 30 seconds of code

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

309
snippets

120
contributors

3335
commits

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

equals

Performs a deep comparison between two values to determine if they are equivalent.

Check if the two values are identical, if they are both Date objects with the same time, using Date.getTime() or if they are both non-object values with an equivalent value (strict comparison). Check if only one value is null or undefined or if their prototypes differ. If none of the above conditions are met, use Object.keys() to check if both values have the same number of keys, then use Array.every() to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.

const equals = (a, b) => {
-  if (a === b) return true;
-  if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
-  if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
-  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]));
+30 seconds of code

logo 30 seconds of code

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

309
snippets

120
contributors

3336
commits

20789
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);
 };
-
equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
-

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

unescapeHTML

Unescapes escaped HTML characters.

Use String.replace() with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).

const unescapeHTML = str =>
-  str.replace(
-    /&amp;|&lt;|&gt;|&#39;|&quot;/g,
-    tag =>
-      ({
-        '&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>'
+
binomialCoefficient(8, 2); // 28
+

overArgs

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

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

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

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'
 

Getting started


Related projects

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


How to contribute

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

1

Create

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

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

Tag

Run npm run tagger from your terminal, then open the tag_database file and tag your snippet appropriately. Multitagging is also supported, just make sure the first tag you specify is on of the major tags and the one that is most relevant to the 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.