30 seconds of codeCurated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.
318
snippets
121
contributors
3456
commits
21222
stars
The core goal of 30 seconds of code is to provide a quality resource for beginner and advanced JavaScript developers alike. We want to help improve the JavaScript ecosystem, by lowering the barrier of entry for newcomers and help seasoned veterans pick up new tricks and remember old ones. In order to achieve this, we have collected hundreds of snippets that can be of use in a wide range of situations. We welcome new contributors and we like fresh ideas, as long as the code is short and easy to grasp in about 30 seconds. The only catch, if you may, is that a few of our snippets are not perfectly optimized for large, enterprise applications and they might not be deemed production-ready.
In order for 30 seconds of code to be as accessible and useful as possible, all of the snippets in the collection are licensed under the CC0-1.0 License, meaning they are absolutely free to use in any project you like. If you like what we do, you can always credit us, but that is not mandatory.
Our sophisticated robot helpers pick new snippets from our collection daily, so that you can discover new snippets to enhance your projects:
Flatten an object with the paths for keys.
Use recursion. Use Object.keys(obj) combined with Array.reduce() to convert every leaf node to a flattened path node. If the value of a key is an object, the function calls itself with the appropriate prefix to create the path using Object.assign(). Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object. You should always omit the second argument, prefix, unless you want every key to have a prefix.
const flattenObject = (obj, prefix = '') => Object.keys(obj).reduce((acc, k) => { const pre = prefix.length ? prefix + '.' : ''; if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k)); else acc[pre + k] = obj[k]; return acc; }, {});
flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }
Returns an object containing the parameters of the current URL.
Use String.match() with an appropriate regular expression to get all key-value pairs, Array.reduce() to map and combine them into a single object. Pass location.search as the argument to apply to the current url.
const getURLParameters = url => (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {} );
getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'} getURLParameters('google.com'); // {}
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'
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:
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!
Start by creating a snippet, according to the snippet template. Make sure to follow these simple guidelines:
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.
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.
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.