UNPKG

30s

Version:

A command-line application for 30 seconds of code snippets

1 lines 240 kB
[{"code":"const all = (arr, fn = Boolean) => arr.every(fn);","example":"all([4, 2, 3], x => x > 1); // true\nall([1, 2, 3]); // true","id":"all","tags":["array","function","beginner"],"description":"Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.\nUse `Array.prototype.every()` to test if all elements in the collection return `true` based on `fn`.\nOmit the second argument, `fn`, to use `Boolean` as a default."},{"code":"const allEqual = arr => arr.every(val => val === arr[0]);","example":"allEqual([1, 2, 3, 4, 5, 6]); // false\nallEqual([1, 1, 1, 1]); // true","id":"allEqual","tags":["array","function","beginner"],"description":"Check if all elements in an array are equal.\nUse `Array.prototype.every()` to check if all the elements of the array are the same as the first one."},{"code":"const any = (arr, fn = Boolean) => arr.some(fn);","example":"any([0, 1, 2, 0], x => x >= 2); // true\nany([0, 0, 1, 0]); // true","id":"any","tags":["array","function","beginner"],"description":"Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.\nUse `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`.\nOmit the second argument, `fn`, to use `Boolean` as a default."},{"code":"const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;","example":"approximatelyEqual(Math.PI / 2.0, 1.5708); // true","id":"approximatelyEqual","tags":["math","beginner"],"description":"Checks if two numbers are approximately equal to each other.\nUse `Math.abs()` to compare the absolute difference of the two values to `epsilon`.\nOmit the third parameter, `epsilon`, to use a default value of `0.001`."},{"code":"const arrayToCSV = (arr, delimiter = ',') =>\n arr.map(v => v.map(x => `\"${x}\"`).join(delimiter)).join('\\n');","example":"arrayToCSV([['a', 'b'], ['c', 'd']]); // '\"a\",\"b\"\\n\"c\",\"d\"'\narrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '\"a\";\"b\"\\n\"c\";\"d\"'","id":"arrayToCSV","tags":["array","string","utility","intermediate"],"description":"Converts a 2D array to a comma-separated values (CSV) string.\nUse `Array.prototype.map()` and `Array.prototype.join(delimiter)` to combine individual 1D arrays (rows) into strings.\nUse `Array.prototype.join('\\n')` to combine all rows into a CSV string, separating each row with a newline.\nOmit the second argument, `delimiter`, to use a default delimiter of `,`."},{"code":"const arrayToHtmlList = (arr, listID) =>\n (el => (\n (el = document.querySelector('#' + listID)),\n (el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))\n ))();","example":"arrayToHtmlList(['item 1', 'item 2'], 'myListID');","id":"arrayToHtmlList","tags":["browser","array","intermediate"],"description":"Converts the given array elements into `<li>` tags and appends them to the list of the given id.\nUse `Array.prototype.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags."},{"code":"const ary = (fn, n) => (...args) => fn(...args.slice(0, n));","example":"const firstTwoMax = ary(Math.max, 2);\n[[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]","id":"ary","tags":["adapter","function","intermediate"],"description":"Creates a function that accepts up to `n` arguments, ignoring any additional arguments.\nCall the provided function, `fn`, with up to `n` arguments, using `Array.prototype.slice(0,n)` and the spread operator (`...`)."},{"code":"const atob = str => Buffer.from(str, 'base64').toString('binary');","example":"atob('Zm9vYmFy'); // 'foobar'","id":"atob","tags":["node","string","utility","beginner"],"description":"Decodes a string of data which has been encoded using base-64 encoding.\nCreate a `Buffer` for the given string with base-64 encoding and use `Buffer.toString('binary')` to return the decoded string."},{"code":"const attempt = (fn, ...args) => {\n try {\n return fn(...args);\n } catch (e) {\n return e instanceof Error ? e : new Error(e);\n }\n};","example":"var elements = attempt(function(selector) {\n return document.querySelectorAll(selector);\n}, '>_>');\nif (elements instanceof Error) elements = []; // elements = []","id":"attempt","tags":["function","intermediate"],"description":"Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.\nUse a `try... catch` block to return either the result of the function or an appropriate error."},{"code":"const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;","example":"average(...[1, 2, 3]); // 2\naverage(1, 2, 3); // 2","id":"average","tags":["math","array","beginner"],"description":"Returns the average of two or more numbers.\nUse `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array."},{"code":"const averageBy = (arr, fn) =>\n arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /\n arr.length;","example":"averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5\naverageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5","id":"averageBy","tags":["math","array","function","intermediate"],"description":"Returns the average of an array, after mapping each element to a value using the provided function.\nUse `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."},{"code":"const bifurcate = (arr, filter) =>\n arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);","example":"bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]","id":"bifurcate","tags":["array","intermediate"],"description":"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.\nUse `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`."},{"code":"const bifurcateBy = (arr, fn) =>\n arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);","example":"bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]","id":"bifurcateBy","tags":["array","function","intermediate"],"description":"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.\nUse `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on the value returned by `fn` for each element."},{"code":"const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);","example":"function greet(greeting, punctuation) {\n return greeting + ' ' + this.user + punctuation;\n}\nconst freddy = { user: 'fred' };\nconst freddyBound = bind(greet, freddy);\nconsole.log(freddyBound('hi', '!')); // 'hi fred!'","id":"bind","tags":["function","object","intermediate"],"description":"Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.\nReturn a `function` that uses `Function.prototype.apply()` to apply the given `context` to `fn`.\nUse `Array.prototype.concat()` to prepend any additional supplied parameters to the arguments."},{"code":"const bindAll = (obj, ...fns) =>\n fns.forEach(\n fn => (\n (f = obj[fn]),\n (obj[fn] = function() {\n return f.apply(obj);\n })\n )\n );","example":"var view = {\n label: 'docs',\n click: function() {\n console.log('clicked ' + this.label);\n }\n};\nbindAll(view, 'click');\njQuery(element).on('click', view.click); // Logs 'clicked docs' when clicked.","id":"bindAll","tags":["object","function","intermediate"],"description":"Binds methods of an object to the object itself, overwriting the existing method.\nUse `Array.prototype.forEach()` to return a `function` that uses `Function.prototype.apply()` to apply the given context (`obj`) to `fn` for each function specified."},{"code":"const bindKey = (context, fn, ...boundArgs) => (...args) =>\n context[fn].apply(context, [...boundArgs, ...args]);","example":"const freddy = {\n user: 'fred',\n greet: function(greeting, punctuation) {\n return greeting + ' ' + this.user + punctuation;\n }\n};\nconst freddyBound = bindKey(freddy, 'greet');\nconsole.log(freddyBound('hi', '!')); // 'hi fred!'","id":"bindKey","tags":["function","object","intermediate"],"description":"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.\nReturn a `function` that uses `Function.prototype.apply()` to bind `context[fn]` to `context`.\nUse the spread operator (`...`) to prepend any additional supplied parameters to the arguments."},{"code":"const binomialCoefficient = (n, k) => {\n if (Number.isNaN(n) || Number.isNaN(k)) return NaN;\n if (k < 0 || k > n) return 0;\n if (k === 0 || k === n) return 1;\n if (k === 1 || k === n - 1) return n;\n if (n - k < k) k = n - k;\n let res = n;\n for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;\n return Math.round(res);\n};","example":"binomialCoefficient(8, 2); // 28","id":"binomialCoefficient","tags":["math","intermediate"],"description":"Evaluates the binomial coefficient of two integers `n` and `k`.\nUse `Number.isNaN()` to check if any of the two values is `NaN`.\nCheck if `k` is less than `0`, greater than or equal to `n`, equal to `1` or `n - 1` and return the appropriate result.\nCheck if `n - k` is less than `k` and switch their values accordingly.\nLoop from `2` through `k` and calculate the binomial coefficient.\nUse `Math.round()` to account for rounding errors in the calculation."},{"code":"const bottomVisible = () =>\n document.documentElement.clientHeight + window.scrollY >=\n (document.documentElement.scrollHeight || document.documentElement.clientHeight);","example":"bottomVisible(); // true","id":"bottomVisible","tags":["browser","intermediate"],"description":"Returns `true` if the bottom of the page is visible, `false` otherwise.\nUse `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible."},{"code":"const btoa = str => Buffer.from(str, 'binary').toString('base64');","example":"btoa('foobar'); // 'Zm9vYmFy'","id":"btoa","tags":["node","string","utility","beginner"],"description":"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.\nCreate a `Buffer` for the given string with binary encoding and use `Buffer.toString('base64')` to return the encoded string."},{"code":"const byteSize = str => new Blob([str]).size;","example":"byteSize('😀'); // 4\nbyteSize('Hello World'); // 11","id":"byteSize","tags":["string","beginner"],"description":"Returns the length of a string in bytes.\nConvert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`."},{"code":"const call = (key, ...args) => context => context[key](...args);","example":"Promise.resolve([1, 2, 3])\n .then(call('map', x => 2 * x))\n .then(console.log); // [ 2, 4, 6 ]\nconst map = call.bind(null, 'map');\nPromise.resolve([1, 2, 3])\n .then(map(x => 2 * x))\n .then(console.log); // [ 2, 4, 6 ]","id":"call","tags":["adapter","function","intermediate"],"description":"Given a key and a set of arguments, call them when given a context. Primarily useful in composition.\nUse a closure to call a stored key with stored arguments."},{"code":"const capitalize = ([first, ...rest], lowerRest = false) =>\n first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));","example":"capitalize('fooBar'); // 'FooBar'\ncapitalize('fooBar', true); // 'Foobar'","id":"capitalize","tags":["string","array","intermediate"],"description":"Capitalizes the first letter of a string.\nUse 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.\nOmit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase."},{"code":"const capitalizeEveryWord = str => str.replace(/\\b[a-z]/g, char => char.toUpperCase());","example":"capitalizeEveryWord('hello world!'); // 'Hello World!'","id":"capitalizeEveryWord","tags":["string","regexp","intermediate"],"description":"Capitalizes the first letter of every word in a string.\nUse `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it."},{"code":"const castArray = val => (Array.isArray(val) ? val : [val]);","example":"castArray('foo'); // ['foo']\ncastArray([1]); // [1]","id":"castArray","tags":["utility","array","type","beginner"],"description":"Casts the provided value as an array if it's not one.\nUse `Array.prototype.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly."},{"code":"const chainAsync = fns => {\n let curr = 0;\n const last = fns[fns.length - 1];\n const next = () => {\n const fn = fns[curr++];\n fn === last ? fn() : fn(next);\n };\n next();\n};","example":"chainAsync([\n next => {\n console.log('0 seconds');\n setTimeout(next, 1000);\n },\n next => {\n console.log('1 second');\n setTimeout(next, 1000);\n },\n () => {\n console.log('2 second');\n }\n]);","id":"chainAsync","tags":["function","intermediate"],"description":"Chains asynchronous functions.\nLoop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed."},{"code":"const chunk = (arr, size) =>\n Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>\n arr.slice(i * size, i * size + size)\n );","example":"chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]","id":"chunk","tags":["array","intermediate"],"description":"Chunks an array into smaller arrays of a specified size.\nUse `Array.from()` to create a new array, that fits the number of chunks that will be produced.\nUse `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.\nIf the original array can't be split evenly, the final chunk will contain the remaining elements."},{"code":"const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));","example":"clampNumber(2, 3, 5); // 3\nclampNumber(1, -1, -5); // -1","id":"clampNumber","tags":["math","beginner"],"description":"Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.\nIf `num` falls within the range, return `num`.\nOtherwise, return the nearest number in the range."},{"code":"const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);","example":"const regExp = /lorem ipsum/gi;\nconst regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi","id":"cloneRegExp","tags":["utility","regexp","intermediate"],"description":"Clones a regular expression.\nUse `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regular expression."},{"code":"const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));","example":"coalesce(null, undefined, '', NaN, 'Waldo'); // \"\"","id":"coalesce","tags":["utility","beginner"],"description":"Returns the first non-null/undefined argument.\nUse `Array.prototype.find()` to return the first non `null`/`undefined` argument."},{"code":"const coalesceFactory = valid => (...args) => args.find(valid);","example":"const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));\ncustomCoalesce(undefined, null, NaN, '', 'Waldo'); // \"Waldo\"","id":"coalesceFactory","tags":["utility","intermediate"],"description":"Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function.\nUse `Array.prototype.find()` to return the first argument that returns `true` from the provided argument validation function."},{"code":"const collectInto = fn => (...args) => fn(args);","example":"const Pall = collectInto(Promise.all.bind(Promise));\nlet p1 = Promise.resolve(1);\nlet p2 = Promise.resolve(2);\nlet p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));\nPall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)","id":"collectInto","tags":["adapter","function","array","intermediate"],"description":"Changes a function that accepts an array into a variadic function.\nGiven a function, return a closure that collects all inputs into an array-accepting function."},{"code":"const colorize = (...args) => ({\n black: `\\x1b[30m${args.join(' ')}`,\n red: `\\x1b[31m${args.join(' ')}`,\n green: `\\x1b[32m${args.join(' ')}`,\n yellow: `\\x1b[33m${args.join(' ')}`,\n blue: `\\x1b[34m${args.join(' ')}`,\n magenta: `\\x1b[35m${args.join(' ')}`,\n cyan: `\\x1b[36m${args.join(' ')}`,\n white: `\\x1b[37m${args.join(' ')}`,\n bgBlack: `\\x1b[40m${args.join(' ')}\\x1b[0m`,\n bgRed: `\\x1b[41m${args.join(' ')}\\x1b[0m`,\n bgGreen: `\\x1b[42m${args.join(' ')}\\x1b[0m`,\n bgYellow: `\\x1b[43m${args.join(' ')}\\x1b[0m`,\n bgBlue: `\\x1b[44m${args.join(' ')}\\x1b[0m`,\n bgMagenta: `\\x1b[45m${args.join(' ')}\\x1b[0m`,\n bgCyan: `\\x1b[46m${args.join(' ')}\\x1b[0m`,\n bgWhite: `\\x1b[47m${args.join(' ')}\\x1b[0m`\n});","example":"console.log(colorize('foo').red); // 'foo' (red letters)\nconsole.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background)\nconsole.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)","id":"colorize","tags":["node","utility","string","intermediate"],"description":"Add special characters to text to print in color in the console (combined with `console.log()`).\nUse template literals and special characters to add the appropriate color code to the string output.\nFor background colors, add a special character that resets the background color at the end of the string."},{"code":"const compact = arr => arr.filter(Boolean);","example":"compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]","id":"compact","tags":["array","beginner"],"description":"Removes falsey values from an array.\nUse `Array.prototype.filter()` to filter out falsey values (`false`, `null`, `0`, `\"\"`, `undefined`, and `NaN`)."},{"code":"const compactWhitespace = str => str.replace(/\\s{2,}/g, ' ');","example":"compactWhitespace('Lorem Ipsum'); // 'Lorem Ipsum'\ncompactWhitespace('Lorem \\n Ipsum'); // 'Lorem Ipsum'","id":"compactWhitespace","tags":["string","regexp","beginner"],"description":"Returns a string with whitespaces compacted.\nUse `String.prototype.replace()` with a regular expression to replace all occurences of 2 or more whitespace characters with a single space."},{"code":"const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));","example":"const add5 = x => x + 5;\nconst multiply = (x, y) => x * y;\nconst multiplyAndAdd5 = compose(\n add5,\n multiply\n);\nmultiplyAndAdd5(5, 2); // 15","id":"compose","tags":["function","intermediate"],"description":"Performs right-to-left function composition.\nUse `Array.prototype.reduce()` to perform right-to-left function composition.\nThe last (rightmost) function can accept one or more arguments; the remaining functions must be unary."},{"code":"const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));","example":"const add = (x, y) => x + y;\nconst square = x => x * x;\nconst addAndSquare = composeRight(add, square);\naddAndSquare(1, 2); // 9","id":"composeRight","tags":["function","intermediate"],"description":"Performs left-to-right function composition.\nUse `Array.prototype.reduce()` to perform left-to-right function composition.\nThe first (leftmost) function can accept one or more arguments; the remaining functions must be unary."},{"code":"const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args)));","example":"const average = converge((a, b) => a / b, [\n arr => arr.reduce((a, v) => a + v, 0),\n arr => arr.length\n]);\naverage([1, 2, 3, 4, 5, 6, 7]); // 4","id":"converge","tags":["function","intermediate"],"description":"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.\nUse `Array.prototype.map()` and `Function.prototype.apply()` to apply each function to the given arguments.\nUse the spread operator (`...`) to call `coverger` with the results of all other functions."},{"code":"const copyToClipboard = str => {\n const el = document.createElement('textarea');\n el.value = str;\n el.setAttribute('readonly', '');\n el.style.position = 'absolute';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n const selected =\n document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n if (selected) {\n document.getSelection().removeAllRanges();\n document.getSelection().addRange(selected);\n }\n};","example":"copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.","id":"copyToClipboard","tags":["browser","string","advanced"],"description":"⚠️ **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](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).\nCopy a string to the clipboard. \nOnly works as a result of user action (i.e. inside a `click` event listener).\nCreate a new `<textarea>` element, fill it with the supplied data and add it to the HTML document.\nUse `Selection.getRangeAt()`to store the selected range (if any).\nUse `document.execCommand('copy')` to copy to the clipboard.\nRemove the `<textarea>` element from the HTML document.\nFinally, use `Selection().addRange()` to recover the original selected range (if any)."},{"code":"const countBy = (arr, fn) =>\n arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {\n acc[val] = (acc[val] || 0) + 1;\n return acc;\n }, {});","example":"countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}\ncountBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}","id":"countBy","tags":["array","object","intermediate"],"description":"Groups the elements of an array based on the given function and returns the count of elements in each group.\nUse `Array.prototype.map()` to map the values of an array to a function or property name.\nUse `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results."},{"code":"const counter = (selector, start, end, step = 1, duration = 2000) => {\n let current = start,\n _step = (end - start) * step < 0 ? -step : step,\n timer = setInterval(() => {\n current += _step;\n document.querySelector(selector).innerHTML = current;\n if (current >= end) document.querySelector(selector).innerHTML = end;\n if (current >= end) clearInterval(timer);\n }, Math.abs(Math.floor(duration / (end - start))));\n return timer;\n};","example":"counter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element with id=\"my-id\"","id":"counter","tags":["browser","advanced"],"description":"Creates a counter with the specified range, step and duration for the specified selector.\nCheck if `step` has the proper sign and change it accordingly.\nUse `setInterval()` in combination with `Math.abs()` and `Math.floor()` to calculate the time between each new text draw.\nUse `document.querySelector().innerHTML` to update the value of the selected element.\nOmit the fourth parameter, `step`, to use a default step of `1`.\nOmit the fifth parameter, `duration`, to use a default duration of `2000`ms."},{"code":"const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);","example":"countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3","id":"countOccurrences","tags":["array","intermediate"],"description":"Counts the occurrences of a value in an array.\nUse `Array.prototype.reduce()` to increment a counter each time you encounter the specific value inside the array."},{"code":"const fs = require('fs');\nconst createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);","example":"createDirIfNotExists('test'); // creates the directory 'test', if it doesn't exist","id":"createDirIfNotExists","tags":["node","beginner"],"description":"Creates a directory, if it does not exist.\nUse `fs.existsSync()` to check if the directory exists, `fs.mkdirSync()` to create it."},{"code":"const createElement = str => {\n const el = document.createElement('div');\n el.innerHTML = str;\n return el.firstElementChild;\n};","example":"const el = createElement(\n `<div class=\"container\">\n <p>Hello!</p>\n </div>`\n);\nconsole.log(el.className); // 'container'","id":"createElement","tags":["browser","utility","beginner"],"description":"Creates an element from a string (without appending it to the document). \nIf the given string contains multiple elements, only the first one will be returned.\nUse `document.createElement()` to create a new element.\nSet its `innerHTML` to the string supplied as the argument. \nUse `ParentNode.firstElementChild` to return the element version of the string."},{"code":"const createEventHub = () => ({\n hub: Object.create(null),\n emit(event, data) {\n (this.hub[event] || []).forEach(handler => handler(data));\n },\n on(event, handler) {\n if (!this.hub[event]) this.hub[event] = [];\n this.hub[event].push(handler);\n },\n off(event, handler) {\n const i = (this.hub[event] || []).findIndex(h => h === handler);\n if (i > -1) this.hub[event].splice(i, 1);\n }\n});","example":"const handler = data => console.log(data);\nconst hub = createEventHub();\nlet increment = 0;\n// Subscribe: listen for different types of events\nhub.on('message', handler);\nhub.on('message', () => console.log('Message event fired'));\nhub.on('increment', () => increment++);\n// Publish: emit events to invoke all handlers subscribed to them, passing the data to them as an argument\nhub.emit('message', 'hello world'); // logs 'hello world' and 'Message event fired'\nhub.emit('message', { hello: 'world' }); // logs the object and 'Message event fired'\nhub.emit('increment'); // `increment` variable is now 1\n// Unsubscribe: stop a specific handler from listening to the 'message' event\nhub.off('message', handler);","id":"createEventHub","tags":["browser","event","advanced"],"description":"Creates a pub/sub ([publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods.\nUse `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`.\nFor `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.\nFor `on`, create an array for the event if it does not yet exist, then use `Array.prototype.push()` to add the handler\nto the array.\nFor `off`, use `Array.prototype.findIndex()` to find the index of the handler in the event array and remove it using `Array.prototype.splice()`."},{"code":"const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>\n data\n .slice(omitFirstRow ? data.indexOf('\\n') + 1 : 0)\n .split('\\n')\n .map(v => v.split(delimiter));","example":"CSVToArray('a,b\\nc,d'); // [['a','b'],['c','d']];\nCSVToArray('a;b\\nc;d', ';'); // [['a','b'],['c','d']];\nCSVToArray('col1,col2\\na,b\\nc,d', ',', true); // [['a','b'],['c','d']];","id":"CSVToArray","tags":["string","array","utility","intermediate"],"description":"Converts a comma-separated values (CSV) string to a 2D array.\nUse `Array.prototype.slice()` and `Array.prototype.indexOf('\\n')` to remove the first row (title row) if `omitFirstRow` is `true`.\nUse `String.prototype.split('\\n')` to create a string for each row, then `String.prototype.split(delimiter)` to separate the values in each row.\nOmit the second argument, `delimiter`, to use a default delimiter of `,`.\nOmit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string."},{"code":"const CSVToJSON = (data, delimiter = ',') => {\n const titles = data.slice(0, data.indexOf('\\n')).split(delimiter);\n return data\n .slice(data.indexOf('\\n') + 1)\n .split('\\n')\n .map(v => {\n const values = v.split(delimiter);\n return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});\n });\n};","example":"CSVToJSON('col1,col2\\na,b\\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];\nCSVToJSON('col1;col2\\na;b\\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];","id":"CSVToJSON","tags":["string","array","object","advanced"],"description":"Converts a comma-separated values (CSV) string to a 2D array of objects.\nThe first row of the string is used as the title row.\nUse `Array.prototype.slice()` and `Array.prototype.indexOf('\\n')` and `String.prototype.split(delimiter)` to separate the first row (title row) into values.\nUse `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.\nUse `Array.prototype.reduce()` to create an object for each row's values, with the keys parsed from the title row.\nOmit the second argument, `delimiter`, to use a default delimiter of `,`."},{"code":"const currentURL = () => window.location.href;","example":"currentURL(); // 'https://google.com'","id":"currentURL","tags":["browser","url","beginner"],"description":"Returns the current URL.\nUse `window.location.href` to get current URL."},{"code":"const curry = (fn, arity = fn.length, ...args) =>\n arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);","example":"curry(Math.pow)(2)(10); // 1024\ncurry(Math.min, 3)(10)(50)(2); // 2","id":"curry","tags":["function","recursion","intermediate"],"description":"Curries a function.\nUse recursion.\nIf the number of provided arguments (`args`) is sufficient, call the passed function `fn`.\nOtherwise, return a curried function `fn` that expects the rest of the arguments.\nIf 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`."},{"code":"const dayOfYear = date =>\n Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);","example":"dayOfYear(new Date()); // 272","id":"dayOfYear","tags":["date","beginner"],"description":"Gets the day of the year from a `Date` object.\nUse `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.\nUse `Math.floor()` to appropriately round the resulting day count to an integer."},{"code":"const debounce = (fn, ms = 0) => {\n let timeoutId;\n return function(...args) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => fn.apply(this, args), ms);\n };\n};","example":"window.addEventListener(\n 'resize',\n debounce(() => {\n console.log(window.innerWidth);\n console.log(window.innerHeight);\n }, 250)\n); // Will log the window dimensions at most every 250ms","id":"debounce","tags":["function","intermediate"],"description":"Creates a debounced function that delays invoking the provided function until at least `ms` milliseconds have elapsed since the last time it was invoked.\nEach 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.\nOmit the second argument, `ms`, to set the timeout at a default of 0 ms."},{"code":"const decapitalize = ([first, ...rest], upperRest = false) =>\n first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));","example":"decapitalize('FooBar'); // 'fooBar'\ndecapitalize('FooBar', true); // 'fOOBAR'","id":"decapitalize","tags":["string","array","intermediate"],"description":"Decapitalizes the first letter of a string.\nUse 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.\nOmit the `upperRest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase."},{"code":"const deepClone = obj => {\n let clone = Object.assign({}, obj);\n Object.keys(clone).forEach(\n key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])\n );\n return Array.isArray(obj) && obj.length\n ? (clone.length = obj.length) && Array.from(clone)\n : Array.isArray(obj)\n ? Array.from(obj)\n : clone;\n};","example":"const a = { foo: 'bar', obj: { a: 1, b: 2 } };\nconst b = deepClone(a); // a !== b, a.obj !== b.obj","id":"deepClone","tags":["object","recursion","intermediate"],"description":"Creates a deep clone of an object.\nUse recursion.\nUse `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.\nUse `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned."},{"code":"const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));","example":"deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]","id":"deepFlatten","tags":["array","recursion","intermediate"],"description":"Deep flattens an array.\nUse recursion.\nUse `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.\nRecursively flatten each element that is an array."},{"code":"const deepFreeze = obj =>\n Object.keys(obj).forEach(\n prop =>\n !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])\n ) || Object.freeze(obj);","example":"'use strict';\nconst o = deepFreeze([1, [2, 3]]);\no[0] = 3; // not allowed\no[1][0] = 4; // not allowed as well","id":"deepFreeze","tags":["object","recursion","intermediate"],"description":"Deep freezes an object.\nCalls `Object.freeze(obj)` recursively on all unfrozen properties of passed object that are `instanceof` object."},{"code":"const deepMapKeys = (obj, f) =>\n Array.isArray(obj)\n ? obj.map(val => deepMapKeys(val, f))\n : typeof obj === 'object'\n ? Object.keys(obj).reduce((acc, current) => {\n const val = obj[current];\n acc[f(current)] =\n val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);\n return acc;\n }, {})\n : obj;","example":"const obj = {\n foo: '1',\n nested: {\n child: {\n withArray: [\n {\n grandChild: ['hello']\n }\n ]\n }\n }\n};\nconst upperKeysObj = deepMapKeys(obj, key => key.toUpperCase());\n/*\n{\n \"FOO\":\"1\",\n \"NESTED\":{\n \"CHILD\":{\n \"WITHARRAY\":[\n {\n \"GRANDCHILD\":[ 'hello' ]\n }\n ]\n }\n }\n}\n*/","id":"deepMapKeys","tags":["object","recursion","advanced"],"description":"Deep maps an object keys.\nCreates an object with the same values as the provided object and keys generated by running the provided function for each key.\nUse `Object.keys(obj)` to iterate over the object's keys. \nUse `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`."},{"code":"const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);","example":"defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }","id":"defaults","tags":["object","intermediate"],"description":"Assigns default values for all properties in an object that are `undefined`.\nUse `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."},{"code":"const defer = (fn, ...args) => setTimeout(fn, 1, ...args);","example":"// Example A:\ndefer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'\n// Example B:\ndocument.querySelector('#someElement').innerHTML = 'Hello';\nlongRunningFunction(); // Browser will not update the HTML until this has finished\ndefer(longRunningFunction); // Browser will update the HTML then run the function","id":"defer","tags":["function","intermediate"],"description":"Defers invoking a function until the current call stack has cleared.\nUse `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."},{"code":"const degreesToRads = deg => (deg * Math.PI) / 180.0;","example":"degreesToRads(90.0); // ~1.5708","id":"degreesToRads","tags":["math","beginner"],"description":"Converts an angle from degrees to radians.\nUse `Math.PI` and the degree to radian formula to convert the angle from degrees to radians."},{"code":"const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);","example":"delay(\n function(text) {\n console.log(text);\n },\n 1000,\n 'later'\n); // Logs 'later' after one second.","id":"delay","tags":["function","intermediate"],"description":"Invokes the provided function after `wait` milliseconds.\nUse `setTimeout()` to delay execution of `fn`.\nUse the spread (`...`) operator to supply the function with an arbitrary number of arguments."},{"code":"const detectDeviceType = () =>\n /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)\n ? 'Mobile'\n : 'Desktop';","example":"detectDeviceType(); // \"Mobile\" or \"Desktop\"","id":"detectDeviceType","tags":["browser","intermediate"],"description":"Detects wether the website is being opened in a mobile device or a desktop/laptop.\nUse a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop."},{"code":"const difference = (a, b) => {\n const s = new Set(b);\n return a.filter(x => !s.has(x));\n};","example":"difference([1, 2, 3], [1, 2, 4]); // [3]","id":"difference","tags":["array","math","beginner"],"description":"Returns the difference between two arrays.\nCreate a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values not contained in `b`."},{"code":"const differenceBy = (a, b, fn) => {\n const s = new Set(b.map(fn));\n return a.map(fn).filter(el => !s.has(el));\n};","example":"differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1]\ndifferenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [2]","id":"differenceBy","tags":["array","function","intermediate"],"description":"Returns the difference between two arrays, after applying the provided function to each array element of both.\nCreate 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()`"},{"code":"const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);","example":"differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]","id":"differenceWith","tags":["array","function","intermediate"],"description":"Filters out all values from an array for which the comparator function does not return `true`.\nUse `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values."},{"code":"const dig = (obj, target) =>\n target in obj\n ? obj[target]\n : Object.values(obj).reduce((acc, val) => {\n if (acc !== undefined) return acc;\n if (typeof val === 'object') return dig(val, target);\n }, undefined);","example":"const data = {\n level1: {\n level2: {\n level3: 'some data'\n }\n }\n};\ndig(data, 'level3'); // 'some data'\ndig(data, 'level4'); // undefined","id":"dig","tags":["object","recursion","intermediate"],"description":"Returns the target value in a nested JSON object, based on the given key.\nUse the `in` operator to check if `target` exists in `obj`.\nIf 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."},{"code":"const digitize = n => [...`${n}`].map(i => parseInt(i));","example":"digitize(123); // [1, 2, 3]","id":"digitize","tags":["math","array","beginner"],"description":"Converts a number to an array of digits.\nConvert the number to a string, using the spread operator (`...`) to build an array.\nUse `Array.prototype.map()` and `parseInt()` to transform each value to an integer."},{"code":"const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);","example":"distance(1, 1, 2, 3); // 2.23606797749979","id":"distance","tags":["math","beginner"],"description":"Returns the distance between two points.\nUse `Math.hypot()` to calculate the Euclidean distance between two points."},{"code":"const drop = (arr, n = 1) => arr.slice(n);","example":"drop([1, 2, 3]); // [2,3]\ndrop([1, 2, 3], 2); // [3]\ndrop([1, 2, 3], 42); // []","id":"drop","tags":["array","beginner"],"description":"Returns a new array with `n` elements removed from the left.\nUse `Array.prototype.slice()` to slice the remove the specified number of elements from the left."},{"code":"const dropRight = (arr, n = 1) => arr.slice(0, -n);","example":"dropRight([1, 2, 3]); // [1,2]\ndropRight([1, 2, 3], 2); // [1]\ndropRight([1, 2, 3], 42); // []","id":"dropRight","tags":["array","beginner"],"description":"Returns a new array with `n` elements removed from the right.\nUse `Array.prototype.slice()` to slice the remove the specified number of elements from the right."},{"code":"const dropRightWhile = (arr, func) => {\n while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);\n return arr;\n};","example":"dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]","id":"dropRightWhile","tags":["array","function","intermediate"],"description":"Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array.\nLoop through the array, using `Array.prototype.slice()` to drop the last element of the array until the returned value from the function is `true`.\nReturns the remaining elements."},{"code":"const dropWhile = (arr, func) => {\n while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);\n return arr;\n};","example":"dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]","id":"dropWhile","tags":["array","function","intermediate"],"description":"Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.\nLoop through the array, using `Array.prototype.slice()` to drop the first element of the array until the returned value from the function is `true`.\nReturns the remaining elements."},{"code":"const elementContains = (parent, child) => parent !== child && parent.contains(child);","example":"elementContains(document.querySelector('head'), document.querySelector('title')); // true\nelementContains(document.querySelector('body'), document.querySelector('body')); // false","id":"elementContains","tags":["browser","intermediate"],"description":"Returns `true` if the `parent` element contains the `child` element, `false` otherwise.\nCheck that `parent` is not the same element as `child`, use `parent.contains(child)` to check if the `parent` element contains the `child` element."},{"code":"const elementIsVisibleInViewport = (el, partiallyVisible = false) => {\n const { top, left, bottom, right } = el.getBoundingClientRect();\n const { innerHeight, innerWidth } = window;\n return partiallyVisible\n ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&\n ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))\n : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;\n};","example":"// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}\nelementIsVisibleInViewport(el); // false - (not fully visible)\nelementIsVisibleInViewport(el, true); // true - (partially visible)","id":"elementIsVisibleInViewport","tags":["browser","advanced"],"description":"Returns `true` if the element specified is visible in the viewport, `false` otherwise.\nUse `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values\nto determine if a given element is visible in the viewport.\nOmit the second argument to determine if the element is entirely visible, or specify `true` to determine if\nit is partially visible."},{"code":"const elo = ([...ratings], kFactor = 32, selfRating) => {\n const [a, b] = ratings;\n const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));\n const newRating = (rating, i) =>\n (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));\n if (ratings.length === 2) return [newRating(a, 1), newRating(b, 0)];\n for (let i = 0, len = ratings.length; i < len; i++) {\n let j = i;\n while (j < len - 1) {\n j++;\n [ratings[i], ratings[j]] = elo([ratings[i], ratings[j]], kFactor);\n }\n }\n return ratings;\n};","example":"// Standard 1v1s\nelo([1200, 1200]); // [1216, 1184]\nelo([1200, 1200], 64); // [1232, 1168]\n// 4 player FFA, all same rank\nelo([1200, 1200, 1200, 1200]).map(Math.round); // [1246, 1215, 1185, 1154]\n/*\nFor teams, each rating can adjusted based on own team's average rating vs.\naverage rating of opposing team, with the score being added to their\nown individual rating by supplying it as the third argument.\n*/","id":"elo","tags":["math","array","advanced"],"description":"Computes the new ratings between two or more opponents using the [Elo rating system](https://en.wikipedia.org/wiki/Elo_rating_system). It takes an array\nof pre-ratings and returns an array containing post-ratings.\nThe array should be ordered from best performer to worst performer (winner -> loser).\nUse the exponent `**` operator and math operators to compute the expected score (chance of winning).\nof each opponent and compute the new rating for each.\nLoop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion. \nOmit the second argument to use the default `kFactor` of 32."},{"code":"const equals = (a, b) => {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;\n if (a === null || a === undefined || b === null || b === undefined) return false;\n if (a.prototype !== b.prototype) return false;\n let keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n return keys.every(k => equals(a[k], b[k]));\n};","example":"equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true","id":"equals","tags":["object","array","type","advanced"],"description":"Performs a deep comparison between two values to determine if they are equivalent.\nCheck 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).\nCheck if only one value is `null` or `undefined` or if their prototypes differ.\nIf 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."},{"code":"const escapeHTML = str =>\n str.replace(\n /[&<>'\"]/g,\n tag =>\n ({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n \"'\": '&#39;',\n '\"': '&quot;'\n }[tag] || tag)\n );","example":"escapeHTML('<a href=\"#\">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'","id":"escapeHTML","tags":["string","browser","regexp","intermediate"],"description":"Escapes a string for use in HTML.\nUse `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)."},{"code":"c