diff --git a/docs/index.html b/docs/index.html index 8c99c14f4..e4b6fc497 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,33 +1,51 @@ -
30 seconds of codeCurated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.
312
snippets
120
contributors
3348
commits
20852
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 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.
Our sophisticated robot helpers pick new snippets from our collection daily, so that you can discover new snippets to enhance your projects:
Converts a string from camelcase.
Use String.replace() to remove underscores, hyphens, and spaces and convert words to camelcase. Omit the second argument to use a default separator of _.
const fromCamelCase = (str, separator = '_') => - str - .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') - .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') - .toLowerCase(); -
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name' -fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized' -fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property' -
Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.
Use Array.reduce() to combine elements into a string. Omit the second argument, separator, to use a default separator of ','. Omit the third argument, end, to use the same value as separator by default.
const join = (arr, separator = ',', end = separator) => - arr.reduce( - (acc, val, i) => - i === arr.length - 2 - ? acc + val + end - : i === arr.length - 1 - ? acc + val - : acc + val + separator, - '' - ); -
join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // "pen,pineapple,apple&pen" -join(['pen', 'pineapple', 'apple', 'pen'], ','); // "pen,pineapple,apple,pen" -join(['pen', 'pineapple', 'apple', 'pen']); // "pen,pineapple,apple,pen" -
Returns the highest index at which value should be inserted into array in order to maintain its sort order.
Check if the array is sorted in descending order (loosely). Use Array.reverse() and Array.findIndex() to find the appropriate last index where the element should be inserted.
const sortedLastIndex = (arr, n) => { - const isDescending = arr[0] > arr[arr.length - 1]; - const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el)); - return index === -1 ? 0 : arr.length - index; +30 seconds of code
30 seconds of code
Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.312
snippets120
contributors3349
commits20862
starsOur 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:
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) +httpPost
Makes a
POSTrequest to the passed URL.Use
XMLHttpRequestweb api to make apostrequest to the givenurl. Set the value of anHTTPrequest header withsetRequestHeadermethod. Handle theonloadevent, by calling the givencallbacktheresponseText. Handle theonerrorevent, by running the providederrfunction. Omit the third argument,data, to send no data to the providedurl. Omit the fourth argument,err, to log errors to the console'serrorstream 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); }; -sortedLastIndex([10, 20, 30, 30, 40], 30); // 4 +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 +} +*/ +maxN
Returns the
nmaximum elements from the provided array. Ifnis greater than or equal to the provided array's length, then return the original array(sorted in descending order).Use
Array.sort()combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. UseArray.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]Getting started
- If you are new to JavaScript, we suggest you start by taking a look at the Beginner's snippets
- If you want to level up your JavaScript skills, check out the full Snippet collection
- If you want to see how the project was built and contribute, visit our Github repository
- If you want to check out some more complex snippets, you can visit the Archive
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:
- 30 seconds of CSS by atomiks
- 30 seconds of Interviews by fejes713
- 30 seconds of Python by kriadmin
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!
1Create
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.
2Tag
Run
npm run taggerfrom 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.3Test
You can optionally test your snippet to make our job easier. Simply run
npm run testerto generate the test files for your snippet. Find the related folder for you snippet under the test directory and write some tests. Remember to runnpm run testeragain to make sure your tests are passing.4Pull 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.