Adapter
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.
const call = (key, ...args) => context => context[key](...args); + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Adapter
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.
const call = (key, ...args) => context => context[key](...args);Promise.resolve([1, 2, 3]) .then(call('map', x => 2 * x)) .then(console.log); //[ 2, 4, 6 ] @@ -161,11 +161,18 @@ Object.assiginitialize2DArray
Initializes a 2D array of given width and height and value.
Use
Array.map()to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default tonull.const initialize2DArray = (w, h, val = null) => Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));initialize2DArray(2, 2, 0); // [[0,0], [0,0]] -initializeArrayWithRange
Initializes an array containing the numbers in the specified range where
startandendare inclusive with there common differencestep.Use
Array.from(Math.ceil((end+1-start)/step))to create an array of the desired length(the amounts of elements is equal to(end-start)/stepor(end+1-start)/stepfor inclusive end),Array.map()to fill with the desired values in a range. You can omitstartto use a default value of0. You can omitstepto use a default value of1.const initializeArrayWithRange = (end, start = 0, step = 1) => +initializeArrayWithRange
Initializes an array containing the numbers in the specified range where
startandendare inclusive with their common differencestep.Use
Array.from(Math.ceil((end+1-start)/step))to create an array of the desired length(the amounts of elements is equal to(end-start)/stepor(end+1-start)/stepfor inclusive end),Array.map()to fill with the desired values in a range. You can omitstartto use a default value of0. You can omitstepto use a default value of1.const initializeArrayWithRange = (end, start = 0, step = 1) => Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start);initializeArrayWithRange(5); // [0,1,2,3,4,5] initializeArrayWithRange(7, 3); // [3,4,5,6,7] initializeArrayWithRange(9, 0, 2); // [0,2,4,6,8] +initializeArrayWithRangeRight
Initializes an array containing the numbers in the specified range (in reverse) where
startandendare inclusive with their common differencestep.Use
Array.from(Math.ceil((end+1-start)/step))to create an array of the desired length(the amounts of elements is equal to(end-start)/stepor(end+1-start)/stepfor inclusive end),Array.map()to fill with the desired values in a range. You can omitstartto use a default value of0. You can omitstepto use a default value of1.const initializeArrayWithRangeRight = (end, start = 0, step = 1) => + Array.from({ length: Math.ceil((end + 1 - start) / step) }).map( + (v, i, arr) => (arr.length - i - 1) * step + start + ); +initializeArrayWithRangeRight(5); // [5,4,3,2,1,0] +initializeArrayWithRangeRight(7, 3); // [7,6,5,4,3] +initializeArrayWithRangeRight(9, 0, 2); // [8,6,4,2,0]initializeArrayWithValues
Initializes and fills an array with the specified values.
Use
Array(n)to create an array of the desired length,fill(v)to fill it with the desired values. You can omitvalto use a default value of0.const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);initializeArrayWithValues(5, 2); // [2,2,2,2,2]intersection
Returns a list of elements that exist in both arrays.
Create a
Setfromb, then useArray.filter()onato only keep values contained inb.const intersection = (a, b) => { @@ -448,6 +455,26 @@ hub.offif (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); };httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com +observeMutationsadvanced
Returns a new MutationObserver and runs the provided callback for each mutation on the specified element.
Use a
MutationObserverto observe mutations on the given element. UseArray.forEach()to run the callback for each mutation that is observed. Omit the third argument,options, to use the default options (alltrue).const observeMutations = (element, callback, options) => { + const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); + observer.observe( + element, + Object.assign( + { + childList: true, + attributes: true, + attributeOldValue: true, + characterData: true, + characterDataOldValue: true, + subtree: true + }, + options + ) + ); + return observer; +}; +const obs = observeMutations(document, console.log); // Logs all mutations that happen on the page +obs.disconnect(); // Disconnects the observer and stops logging mutations on the pageoff
Removes an event listener from an element.
Use
EventTarget.removeEventListener()to remove an event listener from an element. Omit the fourth argumentoptsto usefalseor specify it based on the options used when the event listener was added.const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);const fn = () => console.log('!'); document.body.addEventListener('click', fn); @@ -1146,6 +1173,8 @@ Foo.prototypeShow examplesgetType(new Set([1, 2, 3])); // 'set'isArray
Checks if the given argument is an array.
Use
Array.isArray()to check if a value is classified as an array.const isArray = val => Array.isArray(val);isArray([1]); // true +isArrayBuffer
Checks if value is classified as a ArrayBuffer object.
Use the
instanceofoperator to check if the provided value is aArrayBufferobject.const isArrayBuffer = val => val instanceof ArrayBuffer; +isArrayBuffer(new ArrayBuffer()); // trueisArrayLike
Checks if the provided argument is array-like (i.e. is iterable).
Use the spread operator (
...) to check if the provided argument is iterable inside atry... catchblock and the comma operator (,) to return the appropriate value.const isArrayLike = val => { try { return [...val], true; @@ -1162,6 +1191,11 @@ Foo.prototype📋 Copy to clipboardisFunction
Checks if the given argument is a function.
Use
typeofto check if a value is classified as a function primitive.const isFunction = val => typeof val === 'function';isFunction('x'); // false isFunction(x => x); // true +isMap
Checks if value is classified as a Map object.
Use the
instanceofoperator to check if the provided value is aMapobject.const isMap = val => val instanceof Map; +isMap(new Map()); // true +isNil
Returns
trueif the specified value isnullorundefined,falseotherwise.Use the strict equality operator to check if the value and of
valare equal tonullorundefined.const isNil = val => val === undefined || val === null; +isNil(null); // true +isNil(undefined); // trueisNull
Returns
trueif the specified value isnull,falseotherwise.Use the strict equality operator to check if the value and of
valare equal tonull.const isNull = val => val === null;isNull(null); // trueisNumber
Checks if the given argument is a number.
Use
typeofto check if a value is classified as a number primitive.const isNumber = val => typeof val === 'number'; @@ -1192,10 +1226,18 @@ Foo.prototype// true isPromiseLike(null); // false isPromiseLike({}); // false +isRegExp
Checks if value is classified as a RegExp object.
Use the
instanceofoperator to check if the provided value is aRegExpobject.const isRegExp = val => val instanceof RegExp; +isRegExp(/./g); // true +isSet
Checks if value is classified as a Set object.
Use the
instanceofoperator to check if the provided value is aSetobject.const isSet = val => val instanceof Set; +isSet(new Set()); // trueisString
Checks if the given argument is a string.
Use
typeofto check if a value is classified as a string primitive.const isString = val => typeof val === 'string';isString('10'); // trueisSymbol
Checks if the given argument is a symbol.
Use
typeofto check if a value is classified as a symbol primitive.const isSymbol = val => typeof val === 'symbol';isSymbol(Symbol('x')); // true +isTypedArray
Checks if value is classified as a TypedArray object.
Use the
instanceofoperator to check if the provided value is aTypedArrayobject.const isTypedArray = val => val instanceof TypedArray; +isTypedArray(new TypedArray()); // true +isUndefined
Returns
trueif the specified value isundefined,falseotherwise.Use the strict equality operator to check if the value and of
valare equal toundefined.const isUndefined = val => val === undefined; +isUndefined(undefined); // trueisValidJSON
Checks if the provided argument is a valid JSON.
Use
JSON.parse()and atry... catchblock to check if the provided argument is a valid JSON.const isValidJSON = obj => { try { JSON.parse(obj); @@ -1207,6 +1249,10 @@ Foo.prototypeShow examplesisValidJSON('{"name":"Adam","age":20}'); // true isValidJSON('{"name":"Adam",age:"20"}'); // false isValidJSON(null); // true +isWeakMap
Checks if value is classified as a WeakMap object.
Use the
instanceofoperator to check if the provided value is aWeakMapobject.const isWeakMap = val => val instanceof WeakMap; +isWeakMap(new WeakMap()); // true +isWeakSet
Checks if value is classified as a WeakSet object.
Use the
instanceofoperator to check if the provided value is aWeakSetobject.const isWeakSet = val => val instanceof WeakSet; +isWeakSet(new WeakSet()); // trueUtility
cloneRegExp
Clones a regular expression.
Use
new RegExp(),RegExp.sourceandRegExp.flagsto clone the given regular expression.const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);const regExp = /lorem ipsum/gi; const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi diff --git a/scripts/build.js b/scripts/build.js index 169103309..2eba5bc0e 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -26,7 +26,7 @@ if(isTravisCI() && (process.env['TRAVIS_EVENT_TYPE'] === 'cron' || process.env[' .readdirSync(SNIPPETS_ARCHIVE_PATH) .sort((a, b) => a.toLowerCase() - b.toLowerCase()); // Store the data read from each snippet in the appropriate object - for (const name of snippetFilenames) { + for (const name of snippetFilenames.filter(s => s !== 'README.md')) { snippets[name] = fs.readFileSync(path.join(SNIPPETS_ARCHIVE_PATH, name), 'utf8'); } } catch (err) { @@ -45,7 +45,7 @@ These snippets, while useful and interesting, didn\'t quite make it into the rep ` for(const snippet of Object.entries(snippets)) - output += `* [\`${snippet[0]}\`](#${snippet[0].toLowerCase()})\n`; + output += `* [\`${snippet[0].slice(0,-3)}\`](#${snippet[0].toLowerCase().slice(0,-3)})\n`; output += '\n---\n'; for(const snippet of Object.entries(snippets)){ let data = snippet[1]; diff --git a/snippets/initializeArrayWithRange.md b/snippets/initializeArrayWithRange.md index 228c6fcaf..f5f9f435a9 100644 --- a/snippets/initializeArrayWithRange.md +++ b/snippets/initializeArrayWithRange.md @@ -1,6 +1,6 @@ ### initializeArrayWithRange -Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with there common difference `step`. +Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`. Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range. You can omit `start` to use a default value of `0`. diff --git a/snippets/initializeArrayWithRangeRight.md b/snippets/initializeArrayWithRangeRight.md new file mode 100644 index 000000000..608352c4d --- /dev/null +++ b/snippets/initializeArrayWithRangeRight.md @@ -0,0 +1,20 @@ +### initializeArrayWithRangeRight + +Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`. + +Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range. +You can omit `start` to use a default value of `0`. +You can omit `step` to use a default value of `1`. + +```js +const initializeArrayWithRangeRight = (end, start = 0, step = 1) => + Array.from({ length: Math.ceil((end + 1 - start) / step) }).map( + (v, i, arr) => (arr.length - i - 1) * step + start + ); +``` + +```js +initializeArrayWithRangeRight(5); // [5,4,3,2,1,0] +initializeArrayWithRangeRight(7, 3); // [7,6,5,4,3] +initializeArrayWithRangeRight(9, 0, 2); // [8,6,4,2,0] +``` diff --git a/snippets/isArrayBuffer.md b/snippets/isArrayBuffer.md new file mode 100644 index 000000000..7c28d4398 --- /dev/null +++ b/snippets/isArrayBuffer.md @@ -0,0 +1,13 @@ +### isArrayBuffer + +Checks if value is classified as a ArrayBuffer object. + +Use the `instanceof`operator to check if the provided value is a `ArrayBuffer` object. + +```js +const isArrayBuffer = val => val instanceof ArrayBuffer; +``` + +```js +isArrayBuffer(new ArrayBuffer()); // true +``` diff --git a/snippets/isMap.md b/snippets/isMap.md new file mode 100644 index 000000000..b3a202c5d --- /dev/null +++ b/snippets/isMap.md @@ -0,0 +1,13 @@ +### isMap + +Checks if value is classified as a Map object. + +Use the `instanceof`operator to check if the provided value is a `Map` object. + +```js +const isMap = val => val instanceof Map; +``` + +```js +isMap(new Map()); // true +``` diff --git a/snippets/isNil.md b/snippets/isNil.md new file mode 100644 index 000000000..82618c36f --- /dev/null +++ b/snippets/isNil.md @@ -0,0 +1,14 @@ +### isNil + +Returns `true` if the specified value is `null` or `undefined`, `false` otherwise. + +Use the strict equality operator to check if the value and of `val` are equal to `null` or `undefined`. + +```js +const isNil = val => val === undefined || val === null; +``` + +```js +isNil(null); // true +isNil(undefined); // true +``` diff --git a/snippets/isRegExp.md b/snippets/isRegExp.md new file mode 100644 index 000000000..db57bf587 --- /dev/null +++ b/snippets/isRegExp.md @@ -0,0 +1,13 @@ +### isRegExp + +Checks if value is classified as a RegExp object. + +Use the `instanceof`operator to check if the provided value is a `RegExp` object. + +```js +const isRegExp = val => val instanceof RegExp; +``` + +```js +isRegExp(/./g); // true +``` diff --git a/snippets/isSet.md b/snippets/isSet.md new file mode 100644 index 000000000..bddf3fcbb --- /dev/null +++ b/snippets/isSet.md @@ -0,0 +1,13 @@ +### isSet + +Checks if value is classified as a Set object. + +Use the `instanceof`operator to check if the provided value is a `Set` object. + +```js +const isSet = val => val instanceof Set; +``` + +```js +isSet(new Set()); // true +``` diff --git a/snippets/isTypedArray.md b/snippets/isTypedArray.md new file mode 100644 index 000000000..7b7416bf9 --- /dev/null +++ b/snippets/isTypedArray.md @@ -0,0 +1,13 @@ +### isTypedArray + +Checks if value is classified as a TypedArray object. + +Use the `instanceof`operator to check if the provided value is a `TypedArray` object. + +```js +const isTypedArray = val => val instanceof TypedArray; +``` + +```js +isTypedArray(new TypedArray()); // true +``` diff --git a/snippets/isUndefined.md b/snippets/isUndefined.md new file mode 100644 index 000000000..265b80e57 --- /dev/null +++ b/snippets/isUndefined.md @@ -0,0 +1,13 @@ +### isUndefined + +Returns `true` if the specified value is `undefined`, `false` otherwise. + +Use the strict equality operator to check if the value and of `val` are equal to `undefined`. + +```js +const isUndefined = val => val === undefined; +``` + +```js +isUndefined(undefined); // true +``` diff --git a/snippets/isWeakMap.md b/snippets/isWeakMap.md new file mode 100644 index 000000000..432f17f7e --- /dev/null +++ b/snippets/isWeakMap.md @@ -0,0 +1,13 @@ +### isWeakMap + +Checks if value is classified as a WeakMap object. + +Use the `instanceof`operator to check if the provided value is a `WeakMap` object. + +```js +const isWeakMap = val => val instanceof WeakMap; +``` + +```js +isWeakMap(new WeakMap()); // true +``` diff --git a/snippets/isWeakSet.md b/snippets/isWeakSet.md new file mode 100644 index 000000000..a72a1f0ac --- /dev/null +++ b/snippets/isWeakSet.md @@ -0,0 +1,13 @@ +### isWeakSet + +Checks if value is classified as a WeakSet object. + +Use the `instanceof`operator to check if the provided value is a `WeakSet` object. + +```js +const isWeakSet = val => val instanceof WeakSet; +``` + +```js +isWeakSet(new WeakSet()); // true +``` diff --git a/snippets/observeMutations.md b/snippets/observeMutations.md new file mode 100644 index 000000000..9ccc56f43 --- /dev/null +++ b/snippets/observeMutations.md @@ -0,0 +1,33 @@ +### observeMutations + +Returns a new MutationObserver and runs the provided callback for each mutation on the specified element. + +Use a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to observe mutations on the given element. +Use `Array.forEach()` to run the callback for each mutation that is observed. +Omit the third argument, `options`, to use the default [options](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationObserverInit) (all `true`). + +```js +const observeMutations = (element, callback, options) => { + const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); + observer.observe( + element, + Object.assign( + { + childList: true, + attributes: true, + attributeOldValue: true, + characterData: true, + characterDataOldValue: true, + subtree: true + }, + options + ) + ); + return observer; +}; +``` + +```js +const obs = observeMutations(document, console.log); // Logs all mutations that happen on the page +obs.disconnect(); // Disconnects the observer and stops logging mutations on the page +``` diff --git a/snippets_archive/README.md b/snippets_archive/README.md index 8e92cc46b..bd7001585 100644 --- a/snippets_archive/README.md +++ b/snippets_archive/README.md @@ -6,79 +6,24 @@ These snippets, while useful and interesting, didn't quite make it into the repo ## Table of Contents -* [`JSONToDate.md`](#jsontodate.md) -* [`speechSynthesis.md`](#speechsynthesis.md) -* [`binarySearch.md`](#binarysearch.md) -* [`collatz.md`](#collatz.md) -* [`countVowels.md`](#countvowels.md) -* [`factors.md`](#factors.md) -* [`fibonacciCountUntilNum.md`](#fibonaccicountuntilnum.md) -* [`fibonacciUntilNum.md`](#fibonacciuntilnum.md) -* [`README.md`](#readme.md) -* [`httpDelete.md`](#httpdelete.md) -* [`httpPut.md`](#httpput.md) -* [`isArmstrongNumber.md`](#isarmstrongnumber.md) -* [`quickSort.md`](#quicksort.md) -* [`removeVowels.md`](#removevowels.md) -* [`solveRPN.md`](#solverpn.md) -* [`howManyTimes.md`](#howmanytimes.md) +* [`binarySearch`](#binarysearch) +* [`speechSynthesis`](#speechsynthesis) +* [`countVowels`](#countvowels) +* [`factors`](#factors) +* [`fibonacciCountUntilNum`](#fibonaccicountuntilnum) +* [`fibonacciUntilNum`](#fibonacciuntilnum) +* [`howManyTimes`](#howmanytimes) +* [`httpDelete`](#httpdelete) +* [`collatz`](#collatz) +* [`isArmstrongNumber`](#isarmstrongnumber) +* [`JSONToDate`](#jsontodate) +* [`quickSort`](#quicksort) +* [`removeVowels`](#removevowels) +* [`solveRPN`](#solverpn) +* [`httpPut`](#httpput) --- -### JSONToDate - -Converts a JSON object to a date. - -Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). - -```js -const JSONToDate = arr => { - const dt = new Date(parseInt(arr.toString().substr(6))); - return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; -}; -``` - --- -Examples
- -```js -JSONToDate(/Date(1489525200000)/); // "14/3/2017" -``` - -
[⬆ Back to top](#table-of-contents) - - -### speechSynthesis - -Performs speech synthesis (experimental). - -Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech. -Use `window.speechSynthesis.speak()` to play the message. - -Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance). - -```js -const speechSynthesis = message => { - const msg = new SpeechSynthesisUtterance(message); - msg.voice = window.speechSynthesis.getVoices()[0]; - window.speechSynthesis.speak(msg); -}; -``` - --- -Examples
- -```js -speechSynthesis('Hello, World'); // // plays the message -``` - -
[⬆ Back to top](#table-of-contents) - - ### binarySearch Use recursion. Similar to `Array.indexOf()` that finds the index of a value within an array. @@ -112,21 +57,28 @@ binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1
[⬆ Back to top](#table-of-contents) -### collatz +### speechSynthesis -Applies the Collatz algorithm. +Performs speech synthesis (experimental). -If `n` is even, return `n/2`. Otherwise, return `3n+1`. +Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech. +Use `window.speechSynthesis.speak()` to play the message. + +Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance). ```js -const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1); +const speechSynthesis = message => { + const msg = new SpeechSynthesisUtterance(message); + msg.voice = window.speechSynthesis.getVoices()[0]; + window.speechSynthesis.speak(msg); +}; ```@@ -261,698 +213,6 @@ fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]Examples
```js -collatz(8); // 4 +speechSynthesis('Hello, World'); // // plays the message ```
[⬆ Back to top](#table-of-contents) - - -# Snippets Archive - -These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are. - -## Table of Contents - -* [`JSONToDate.md`](#jsontodate.md) -* [`speechSynthesis.md`](#speechsynthesis.md) -* [`binarySearch.md`](#binarysearch.md) -* [`collatz.md`](#collatz.md) -* [`countVowels.md`](#countvowels.md) -* [`factors.md`](#factors.md) -* [`fibonacciCountUntilNum.md`](#fibonaccicountuntilnum.md) -* [`README.md`](#readme.md) -* [`howManyTimes.md`](#howmanytimes.md) -* [`isArmstrongNumber.md`](#isarmstrongnumber.md) -* [`quickSort.md`](#quicksort.md) -* [`removeVowels.md`](#removevowels.md) -* [`solveRPN.md`](#solverpn.md) -* [`fibonacciUntilNum.md`](#fibonacciuntilnum.md) - ---- - -### JSONToDate - -Converts a JSON object to a date. - -Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). - -```js -const JSONToDate = arr => { - const dt = new Date(parseInt(arr.toString().substr(6))); - return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; -}; -``` - --- -Examples
- -```js -JSONToDate(/Date(1489525200000)/); // "14/3/2017" -``` - -
[⬆ Back to top](#table-of-contents) - - -### speechSynthesis - -Performs speech synthesis (experimental). - -Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech. -Use `window.speechSynthesis.speak()` to play the message. - -Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance). - -```js -const speechSynthesis = message => { - const msg = new SpeechSynthesisUtterance(message); - msg.voice = window.speechSynthesis.getVoices()[0]; - window.speechSynthesis.speak(msg); -}; -``` - --- -Examples
- -```js -speechSynthesis('Hello, World'); // // plays the message -``` - -
[⬆ Back to top](#table-of-contents) - - -### binarySearch - -Use recursion. Similar to `Array.indexOf()` that finds the index of a value within an array. -The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.indexOf()`. - -Search a sorted array by repeatedly dividing the search interval in half. -Begin with an interval covering the whole array. -If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. -Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`. - -```js -const binarySearch = (arr, val, start = 0, end = arr.length - 1) => { - if (start > end) return -1; - const mid = Math.floor((start + end) / 2); - if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1); - if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end); - return mid; -} -``` - --- -Examples
- -```js -binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2 -binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1 -``` - -
[⬆ Back to top](#table-of-contents) - - -### collatz - -Applies the Collatz algorithm. - -If `n` is even, return `n/2`. Otherwise, return `3n+1`. - -```js -const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1); -``` - --- -Examples
- -```js -collatz(8); // 4 -``` - -
[⬆ Back to top](#table-of-contents) - - -### countVowels - -Retuns `number` of vowels in provided string. - -Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`. - -```js -const countVowels = str => (str.match(/[aeiou]/gi) || []).length; -``` - --- -Examples
- -```js -countVowels('foobar'); // 3 -countVowels('gym'); // 0 -``` - -
[⬆ Back to top](#table-of-contents) - - -### factors - -Returns the array of factors of the given `num`. -If the second argument is set to `true` returns only the prime factors of `num`. -If `num` is `1` or `0` returns an empty array. -If `num` is less than `0` returns all the factors of `-int` together with their additive inverses. - -Use `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`. -If given `num` is negative, use `Array.reduce()` to add the additive inverses to the array. -Return all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`. -Omit the second argument, `primes`, to return prime and non-prime factors by default. - -**Note**:- _Negative numbers are not considered prime._ - -```js -const factors = (num, primes = false) => { - const isPrime = num => { - const boundary = Math.floor(Math.sqrt(num)); - for (var i = 2; i <= boundary; i++) if (num % i === 0) return false; - return num >= 2; - }; - const isNeg = num < 0; - num = isNeg ? -num : num; - let array = Array.from({ length: num - 1 }) - .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false)) - .filter(val => val); - if (isNeg) - array = array.reduce((acc, val) => { - acc.push(val); - acc.push(-val); - return acc; - }, []); - return primes ? array.filter(isPrime) : array; -}; -``` - --- -Examples
- -```js -factors(12); // [2,3,4,6,12] -factors(12, true); // [2,3] -factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12] -factors(-12, true); // [2,3] -``` - -
[⬆ Back to top](#table-of-contents) - - -### fibonacciCountUntilNum - -Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive). - -Use a mathematical formula to calculate the number of fibonacci numbers until `num`. - -```js -const fibonacciCountUntilNum = num => - Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); -``` - --- -Examples
- -```js -fibonacciCountUntilNum(10); // 7 -``` - -
[⬆ Back to top](#table-of-contents) - - - - -# Snippets Archive - -These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are. - -## Table of Contents - -* [`JSONToDate.md`](#jsontodate.md) -* [`speechSynthesis.md`](#speechsynthesis.md) -* [`binarySearch.md`](#binarysearch.md) -* [`collatz.md`](#collatz.md) -* [`countVowels.md`](#countvowels.md) -* [`factors.md`](#factors.md) -* [`fibonacciCountUntilNum.md`](#fibonaccicountuntilnum.md) -* [`README.md`](#readme.md) -* [`howManyTimes.md`](#howmanytimes.md) -* [`isArmstrongNumber.md`](#isarmstrongnumber.md) -* [`quickSort.md`](#quicksort.md) -* [`removeVowels.md`](#removevowels.md) -* [`solveRPN.md`](#solverpn.md) -* [`fibonacciUntilNum.md`](#fibonacciuntilnum.md) - ---- - -### JSONToDate - -Converts a JSON object to a date. - -Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). - -```js -const JSONToDate = arr => { - const dt = new Date(parseInt(arr.toString().substr(6))); - return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; -}; -``` - --- -Examples
- -```js -JSONToDate(/Date(1489525200000)/); // "14/3/2017" -``` - -
[⬆ Back to top](#table-of-contents) - - -### speechSynthesis - -Performs speech synthesis (experimental). - -Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech. -Use `window.speechSynthesis.speak()` to play the message. - -Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance). - -```js -const speechSynthesis = message => { - const msg = new SpeechSynthesisUtterance(message); - msg.voice = window.speechSynthesis.getVoices()[0]; - window.speechSynthesis.speak(msg); -}; -``` - --- -Examples
- -```js -speechSynthesis('Hello, World'); // // plays the message -``` - -
[⬆ Back to top](#table-of-contents) - - -### binarySearch - -Use recursion. Similar to `Array.indexOf()` that finds the index of a value within an array. -The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.indexOf()`. - -Search a sorted array by repeatedly dividing the search interval in half. -Begin with an interval covering the whole array. -If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. -Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`. - -```js -const binarySearch = (arr, val, start = 0, end = arr.length - 1) => { - if (start > end) return -1; - const mid = Math.floor((start + end) / 2); - if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1); - if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end); - return mid; -} -``` - --- -Examples
- -```js -binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2 -binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1 -``` - -
[⬆ Back to top](#table-of-contents) - - -### collatz - -Applies the Collatz algorithm. - -If `n` is even, return `n/2`. Otherwise, return `3n+1`. - -```js -const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1); -``` - --- -Examples
- -```js -collatz(8); // 4 -``` - -
[⬆ Back to top](#table-of-contents) - - -### countVowels - -Retuns `number` of vowels in provided string. - -Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`. - -```js -const countVowels = str => (str.match(/[aeiou]/gi) || []).length; -``` - --- -Examples
- -```js -countVowels('foobar'); // 3 -countVowels('gym'); // 0 -``` - -
[⬆ Back to top](#table-of-contents) - - -### factors - -Returns the array of factors of the given `num`. -If the second argument is set to `true` returns only the prime factors of `num`. -If `num` is `1` or `0` returns an empty array. -If `num` is less than `0` returns all the factors of `-int` together with their additive inverses. - -Use `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`. -If given `num` is negative, use `Array.reduce()` to add the additive inverses to the array. -Return all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`. -Omit the second argument, `primes`, to return prime and non-prime factors by default. - -**Note**:- _Negative numbers are not considered prime._ - -```js -const factors = (num, primes = false) => { - const isPrime = num => { - const boundary = Math.floor(Math.sqrt(num)); - for (var i = 2; i <= boundary; i++) if (num % i === 0) return false; - return num >= 2; - }; - const isNeg = num < 0; - num = isNeg ? -num : num; - let array = Array.from({ length: num - 1 }) - .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false)) - .filter(val => val); - if (isNeg) - array = array.reduce((acc, val) => { - acc.push(val); - acc.push(-val); - return acc; - }, []); - return primes ? array.filter(isPrime) : array; -}; -``` - --- -Examples
- -```js -factors(12); // [2,3,4,6,12] -factors(12, true); // [2,3] -factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12] -factors(-12, true); // [2,3] -``` - -
[⬆ Back to top](#table-of-contents) - - -### fibonacciCountUntilNum - -Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive). - -Use a mathematical formula to calculate the number of fibonacci numbers until `num`. - -```js -const fibonacciCountUntilNum = num => - Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); -``` - --- -Examples
- -```js -fibonacciCountUntilNum(10); // 7 -``` - -
[⬆ Back to top](#table-of-contents) - - - - -# 30 seconds of code - -These snippets , while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are. - -## Table of Contents - -* [`JSONToDate.md`](#jsontodate.md -* [`speechSynthesis.md`](#speechsynthesis.md -* [`collatz.md`](#collatz.md -* [`countVowels.md`](#countvowels.md -* [`factors.md`](#factors.md -* [`fibonacciCountUntilNum.md`](#fibonaccicountuntilnum.md -* [`binarySearch.md`](#binarysearch.md -* [`howManyTimes.md`](#howmanytimes.md -* [`isArmstrongNumber.md`](#isarmstrongnumber.md -* [`quickSort.md`](#quicksort.md -* [`removeVowels.md`](#removevowels.md -* [`solveRPN.md`](#solverpn.md -* [`fibonacciUntilNum.md`](#fibonacciuntilnum.md - ---- - -### JSONToDate - -Converts a JSON object to a date. - -Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). - -```js -const JSONToDate = arr => { - const dt = new Date(parseInt(arr.toString().substr(6))); - return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; -}; -``` - --- -Examples
- -```js -JSONToDate(/Date(1489525200000)/); // "14/3/2017" -``` - -
[⬆ Back to top](#table-of-contents) - - -### speechSynthesis - -Performs speech synthesis (experimental). - -Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech. -Use `window.speechSynthesis.speak()` to play the message. - -Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance). - -```js -const speechSynthesis = message => { - const msg = new SpeechSynthesisUtterance(message); - msg.voice = window.speechSynthesis.getVoices()[0]; - window.speechSynthesis.speak(msg); -}; -``` - --- -Examples
- -```js -speechSynthesis('Hello, World'); // // plays the message -``` - -
[⬆ Back to top](#table-of-contents) - - -### collatz - -Applies the Collatz algorithm. - -If `n` is even, return `n/2`. Otherwise, return `3n+1`. - -```js -const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1); -``` - --- -Examples
- -```js -collatz(8); // 4 -``` - -
[⬆ Back to top](#table-of-contents) - - -### countVowels - -Retuns `number` of vowels in provided string. - -Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`. - -```js -const countVowels = str => (str.match(/[aeiou]/gi) || []).length; -``` - --- -Examples
- -```js -countVowels('foobar'); // 3 -countVowels('gym'); // 0 -``` - -
[⬆ Back to top](#table-of-contents) - - -### factors - -Returns the array of factors of the given `num`. -If the second argument is set to `true` returns only the prime factors of `num`. -If `num` is `1` or `0` returns an empty array. -If `num` is less than `0` returns all the factors of `-int` together with their additive inverses. - -Use `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`. -If given `num` is negative, use `Array.reduce()` to add the additive inverses to the array. -Return all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`. -Omit the second argument, `primes`, to return prime and non-prime factors by default. - -**Note**:- _Negative numbers are not considered prime._ - -```js -const factors = (num, primes = false) => { - const isPrime = num => { - const boundary = Math.floor(Math.sqrt(num)); - for (var i = 2; i <= boundary; i++) if (num % i === 0) return false; - return num >= 2; - }; - const isNeg = num < 0; - num = isNeg ? -num : num; - let array = Array.from({ length: num - 1 }) - .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false)) - .filter(val => val); - if (isNeg) - array = array.reduce((acc, val) => { - acc.push(val); - acc.push(-val); - return acc; - }, []); - return primes ? array.filter(isPrime) : array; -}; -``` - --- -Examples
- -```js -factors(12); // [2,3,4,6,12] -factors(12, true); // [2,3] -factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12] -factors(-12, true); // [2,3] -``` - -
[⬆ Back to top](#table-of-contents) - - -### fibonacciCountUntilNum - -Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive). - -Use a mathematical formula to calculate the number of fibonacci numbers until `num`. - -```js -const fibonacciCountUntilNum = num => - Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); -``` - --- -Examples
- -```js -fibonacciCountUntilNum(10); // 7 -``` - -
[⬆ Back to top](#table-of-contents) - - -### binarySearch - -Use recursion. Similar to `Array.indexOf()` that finds the index of a value within an array. -The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.indexOf()`. - -Search a sorted array by repeatedly dividing the search interval in half. -Begin with an interval covering the whole array. -If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. -Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`. - -```js -const binarySearch = (arr, val, start = 0, end = arr.length - 1) => { - if (start > end) return -1; - const mid = Math.floor((start + end) / 2); - if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1); - if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end); - return mid; -} -``` - --- -Examples
- -```js -binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2 -binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1 -``` - -
[⬆ Back to top](#table-of-contents) - - ### howManyTimes Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer. @@ -991,604 +251,6 @@ howManyTimes(100, -1); // Infinity
[⬆ Back to top](#table-of-contents) -### isArmstrongNumber - -Checks if the given number is an Armstrong number or not. - -Convert the given number into an array of digits. Use the exponent operator (`**`) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`. - -```js -const isArmstrongNumber = digits => - (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)( - (digits + '').split('') - ); -``` - --- -Examples
- -```js -isArmstrongNumber(1634); // true -isArmstrongNumber(56); // false -``` - -
[⬆ Back to top](#table-of-contents) - - -### quickSort - -QuickSort an Array (ascending sort by default). - -Use recursion. -Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. -If the parameter `desc` is truthy, return array sorts in descending order. - -```js -const quickSort = ([n, ...nums], desc) => - isNaN(n) - ? [] - : [ - ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc), - n, - ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc) - ]; -``` - --- -Examples
- -```js -quickSort([4, 1, 3, 2]); // [1,2,3,4] -quickSort([4, 1, 3, 2], true); // [4,3,2,1] -``` - -
[⬆ Back to top](#table-of-contents) - - -### removeVowels - -Returns all the vowels in a `str` replaced by `repl`. - -Use `String.replace()` with a regexp to replace all vowels in `str`. -Omot `repl` to use a default value of `''`. - -```js -const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl); -``` - --- -Examples
- -```js -removeVowels("foobAr"); // "fbr" -removeVowels("foobAr","*"); // "f**b*r" -``` - -
[⬆ Back to top](#table-of-contents) - - -### solveRPN - -Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation). -Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators. - -Use a dictionary, `OPERATORS` to specify each operator's matching mathematical operation. -Use `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens. -Use `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression. -Numeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations. - -```js -const solveRPN = rpn => { - const OPERATORS = { - '*': (a, b) => a * b, - '+': (a, b) => a + b, - '-': (a, b) => a - b, - '/': (a, b) => a / b, - '**': (a, b) => a ** b - }; - const [stack, solve] = [ - [], - rpn - .replace(/\^/g, '**') - .split(/\s+/g) - .filter(el => !/\s+/.test(el) && el !== '') - ]; - solve.forEach(symbol => { - if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) { - stack.push(symbol); - } else if (Object.keys(OPERATORS).includes(symbol)) { - const [a, b] = [stack.pop(), stack.pop()]; - stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a))); - } else { - throw `${symbol} is not a recognized symbol`; - } - }); - if (stack.length === 1) return stack.pop(); - else throw `${rpn} is not a proper RPN. Please check it and try again`; -}; -``` - --- -Examples
- -```js -solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5 -solveRPN('2 3 ^'); // 8 -``` - -
[⬆ Back to top](#table-of-contents) - - -### fibonacciUntilNum - -Generates an array, containing the Fibonacci sequence, up until the nth term. - -Create an empty array of the specific length, initializing the first two values (`0` and `1`). -Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two. -Uses a mathematical formula to calculate the length of the array required. - -```js -const fibonacciUntilNum = num => { - let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); - return Array.from({ length: n }).reduce( - (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), - [] - ); -}; -``` - --- -Examples
- --- -Examples
- -```js -fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ] -``` - -
[⬆ Back to top](#table-of-contents) - - -
[⬆ Back to top](#table-of-contents) - - -### howManyTimes - -Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer. -Works for both negative and positive integers. - -If `divisor` is `-1` or `1` return `Infinity`. -If `divisor` is `-0` or `0` return `0`. -Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer. -Return the number of times the loop was executed, `i`. - -```js -const howManyTimes = (num, divisor) => { - if (divisor === 1 || divisor === -1) return Infinity; - if (divisor === 0) return 0; - let i = 0; - while (Number.isInteger(num / divisor)) { - i++; - num = num / divisor; - } - return i; -}; -``` - --- -Examples
- -```js -howManyTimes(100, 2); // 2 -howManyTimes(100, 2.5); // 2 -howManyTimes(100, 0); // 0 -howManyTimes(100, -1); // Infinity -``` - -
[⬆ Back to top](#table-of-contents) - - -### isArmstrongNumber - -Checks if the given number is an Armstrong number or not. - -Convert the given number into an array of digits. Use the exponent operator (`**`) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`. - -```js -const isArmstrongNumber = digits => - (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)( - (digits + '').split('') - ); -``` - --- -Examples
- -```js -isArmstrongNumber(1634); // true -isArmstrongNumber(56); // false -``` - -
[⬆ Back to top](#table-of-contents) - - -### quickSort - -QuickSort an Array (ascending sort by default). - -Use recursion. -Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. -If the parameter `desc` is truthy, return array sorts in descending order. - -```js -const quickSort = ([n, ...nums], desc) => - isNaN(n) - ? [] - : [ - ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc), - n, - ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc) - ]; -``` - --- -Examples
- -```js -quickSort([4, 1, 3, 2]); // [1,2,3,4] -quickSort([4, 1, 3, 2], true); // [4,3,2,1] -``` - -
[⬆ Back to top](#table-of-contents) - - -### removeVowels - -Returns all the vowels in a `str` replaced by `repl`. - -Use `String.replace()` with a regexp to replace all vowels in `str`. -Omot `repl` to use a default value of `''`. - -```js -const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl); -``` - --- -Examples
- -```js -removeVowels("foobAr"); // "fbr" -removeVowels("foobAr","*"); // "f**b*r" -``` - -
[⬆ Back to top](#table-of-contents) - - -### solveRPN - -Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation). -Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators. - -Use a dictionary, `OPERATORS` to specify each operator's matching mathematical operation. -Use `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens. -Use `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression. -Numeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations. - -```js -const solveRPN = rpn => { - const OPERATORS = { - '*': (a, b) => a * b, - '+': (a, b) => a + b, - '-': (a, b) => a - b, - '/': (a, b) => a / b, - '**': (a, b) => a ** b - }; - const [stack, solve] = [ - [], - rpn - .replace(/\^/g, '**') - .split(/\s+/g) - .filter(el => !/\s+/.test(el) && el !== '') - ]; - solve.forEach(symbol => { - if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) { - stack.push(symbol); - } else if (Object.keys(OPERATORS).includes(symbol)) { - const [a, b] = [stack.pop(), stack.pop()]; - stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a))); - } else { - throw `${symbol} is not a recognized symbol`; - } - }); - if (stack.length === 1) return stack.pop(); - else throw `${rpn} is not a proper RPN. Please check it and try again`; -}; -``` - --- -Examples
- -```js -solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5 -solveRPN('2 3 ^'); // 8 -``` - -
[⬆ Back to top](#table-of-contents) - - -### fibonacciUntilNum - -Generates an array, containing the Fibonacci sequence, up until the nth term. - -Create an empty array of the specific length, initializing the first two values (`0` and `1`). -Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two. -Uses a mathematical formula to calculate the length of the array required. - -```js -const fibonacciUntilNum = num => { - let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); - return Array.from({ length: n }).reduce( - (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), - [] - ); -}; -``` - --- -Examples
- --- -Examples
- -```js -fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ] -``` - -
[⬆ Back to top](#table-of-contents) - - -
[⬆ Back to top](#table-of-contents) - - -### howManyTimes - -Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer. -Works for both negative and positive integers. - -If `divisor` is `-1` or `1` return `Infinity`. -If `divisor` is `-0` or `0` return `0`. -Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer. -Return the number of times the loop was executed, `i`. - -```js -const howManyTimes = (num, divisor) => { - if (divisor === 1 || divisor === -1) return Infinity; - if (divisor === 0) return 0; - let i = 0; - while (Number.isInteger(num / divisor)) { - i++; - num = num / divisor; - } - return i; -}; -``` - --- -Examples
- -```js -howManyTimes(100, 2); // 2 -howManyTimes(100, 2.5); // 2 -howManyTimes(100, 0); // 0 -howManyTimes(100, -1); // Infinity -``` - -
[⬆ Back to top](#table-of-contents) - - -### isArmstrongNumber - -Checks if the given number is an Armstrong number or not. - -Convert the given number into an array of digits. Use the exponent operator (`**`) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`. - -```js -const isArmstrongNumber = digits => - (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)( - (digits + '').split('') - ); -``` - --- -Examples
- -```js -isArmstrongNumber(1634); // true -isArmstrongNumber(56); // false -``` - -
[⬆ Back to top](#table-of-contents) - - -### quickSort - -QuickSort an Array (ascending sort by default). - -Use recursion. -Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. -If the parameter `desc` is truthy, return array sorts in descending order. - -```js -const quickSort = ([n, ...nums], desc) => - isNaN(n) - ? [] - : [ - ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc), - n, - ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc) - ]; -``` - --- -Examples
- -```js -quickSort([4, 1, 3, 2]); // [1,2,3,4] -quickSort([4, 1, 3, 2], true); // [4,3,2,1] -``` - -
[⬆ Back to top](#table-of-contents) - - -### removeVowels - -Returns all the vowels in a `str` replaced by `repl`. - -Use `String.replace()` with a regexp to replace all vowels in `str`. -Omot `repl` to use a default value of `''`. - -```js -const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl); -``` - --- -Examples
- -```js -removeVowels("foobAr"); // "fbr" -removeVowels("foobAr","*"); // "f**b*r" -``` - -
[⬆ Back to top](#table-of-contents) - - -### solveRPN - -Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation). -Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators. - -Use a dictionary, `OPERATORS` to specify each operator's matching mathematical operation. -Use `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens. -Use `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression. -Numeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations. - -```js -const solveRPN = rpn => { - const OPERATORS = { - '*': (a, b) => a * b, - '+': (a, b) => a + b, - '-': (a, b) => a - b, - '/': (a, b) => a / b, - '**': (a, b) => a ** b - }; - const [stack, solve] = [ - [], - rpn - .replace(/\^/g, '**') - .split(/\s+/g) - .filter(el => !/\s+/.test(el) && el !== '') - ]; - solve.forEach(symbol => { - if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) { - stack.push(symbol); - } else if (Object.keys(OPERATORS).includes(symbol)) { - const [a, b] = [stack.pop(), stack.pop()]; - stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a))); - } else { - throw `${symbol} is not a recognized symbol`; - } - }); - if (stack.length === 1) return stack.pop(); - else throw `${rpn} is not a proper RPN. Please check it and try again`; -}; -``` - --- -Examples
- -```js -solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5 -solveRPN('2 3 ^'); // 8 -``` - -
[⬆ Back to top](#table-of-contents) - - -### fibonacciUntilNum - -Generates an array, containing the Fibonacci sequence, up until the nth term. - -Create an empty array of the specific length, initializing the first two values (`0` and `1`). -Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two. -Uses a mathematical formula to calculate the length of the array required. - -```js -const fibonacciUntilNum = num => { - let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); - return Array.from({ length: n }).reduce( - (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), - [] - ); -}; -``` - --- -Examples
- --- -Examples
- -```js -fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ] -``` - -
[⬆ Back to top](#table-of-contents) - - -
[⬆ Back to top](#table-of-contents) - - ### httpDelete Makes a `DELETE` request to the passed URL. @@ -1622,6 +284,189 @@ httpDelete('https://website.com/users/123', request => {
[⬆ Back to top](#table-of-contents) +### collatz + +Applies the Collatz algorithm. + +If `n` is even, return `n/2`. Otherwise, return `3n+1`. + +```js +const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1); +``` + +++ +Examples
+ +```js +collatz(8); // 4 +``` + +
[⬆ Back to top](#table-of-contents) + + +### isArmstrongNumber + +Checks if the given number is an Armstrong number or not. + +Convert the given number into an array of digits. Use the exponent operator (`**`) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`. + +```js +const isArmstrongNumber = digits => + (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)( + (digits + '').split('') + ); +``` + +++ +Examples
+ +```js +isArmstrongNumber(1634); // true +isArmstrongNumber(56); // false +``` + +
[⬆ Back to top](#table-of-contents) + + +### JSONToDate + +Converts a JSON object to a date. + +Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). + +```js +const JSONToDate = arr => { + const dt = new Date(parseInt(arr.toString().substr(6))); + return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; +}; +``` + +++ +Examples
+ +```js +JSONToDate(/Date(1489525200000)/); // "14/3/2017" +``` + +
[⬆ Back to top](#table-of-contents) + + +### quickSort + +QuickSort an Array (ascending sort by default). + +Use recursion. +Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. +If the parameter `desc` is truthy, return array sorts in descending order. + +```js +const quickSort = ([n, ...nums], desc) => + isNaN(n) + ? [] + : [ + ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc), + n, + ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc) + ]; +``` + +++ +Examples
+ +```js +quickSort([4, 1, 3, 2]); // [1,2,3,4] +quickSort([4, 1, 3, 2], true); // [4,3,2,1] +``` + +
[⬆ Back to top](#table-of-contents) + + +### removeVowels + +Returns all the vowels in a `str` replaced by `repl`. + +Use `String.replace()` with a regexp to replace all vowels in `str`. +Omot `repl` to use a default value of `''`. + +```js +const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl); +``` + +++ +Examples
+ +```js +removeVowels("foobAr"); // "fbr" +removeVowels("foobAr","*"); // "f**b*r" +``` + +
[⬆ Back to top](#table-of-contents) + + +### solveRPN + +Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation). +Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators. + +Use a dictionary, `OPERATORS` to specify each operator's matching mathematical operation. +Use `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens. +Use `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression. +Numeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations. + +```js +const solveRPN = rpn => { + const OPERATORS = { + '*': (a, b) => a * b, + '+': (a, b) => a + b, + '-': (a, b) => a - b, + '/': (a, b) => a / b, + '**': (a, b) => a ** b + }; + const [stack, solve] = [ + [], + rpn + .replace(/\^/g, '**') + .split(/\s+/g) + .filter(el => !/\s+/.test(el) && el !== '') + ]; + solve.forEach(symbol => { + if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) { + stack.push(symbol); + } else if (Object.keys(OPERATORS).includes(symbol)) { + const [a, b] = [stack.pop(), stack.pop()]; + stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a))); + } else { + throw `${symbol} is not a recognized symbol`; + } + }); + if (stack.length === 1) return stack.pop(); + else throw `${rpn} is not a proper RPN. Please check it and try again`; +}; +``` + +++ +Examples
+ +```js +solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5 +solveRPN('2 3 ^'); // 8 +``` + +
[⬆ Back to top](#table-of-contents) + + ### httpPut Makes a `PUT` request to the passed URL. @@ -1658,177 +503,3 @@ httpPut('https://website.com/users/123', data, request => {
[⬆ Back to top](#table-of-contents) - -### isArmstrongNumber - -Checks if the given number is an Armstrong number or not. - -Convert the given number into an array of digits. Use the exponent operator (`**`) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`. - -```js -const isArmstrongNumber = digits => - (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)( - (digits + '').split('') - ); -``` - --- -Examples
- -```js -isArmstrongNumber(1634); // true -isArmstrongNumber(56); // false -``` - -
[⬆ Back to top](#table-of-contents) - - -### quickSort - -QuickSort an Array (ascending sort by default). - -Use recursion. -Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. -If the parameter `desc` is truthy, return array sorts in descending order. - -```js -const quickSort = ([n, ...nums], desc) => - isNaN(n) - ? [] - : [ - ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc), - n, - ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc) - ]; -``` - --- -Examples
- -```js -quickSort([4, 1, 3, 2]); // [1,2,3,4] -quickSort([4, 1, 3, 2], true); // [4,3,2,1] -``` - -
[⬆ Back to top](#table-of-contents) - - -### removeVowels - -Returns all the vowels in a `str` replaced by `repl`. - -Use `String.replace()` with a regexp to replace all vowels in `str`. -Omot `repl` to use a default value of `''`. - -```js -const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl); -``` - --- -Examples
- -```js -removeVowels("foobAr"); // "fbr" -removeVowels("foobAr","*"); // "f**b*r" -``` - -
[⬆ Back to top](#table-of-contents) - - -### solveRPN - -Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation). -Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators. - -Use a dictionary, `OPERATORS` to specify each operator's matching mathematical operation. -Use `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens. -Use `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression. -Numeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations. - -```js -const solveRPN = rpn => { - const OPERATORS = { - '*': (a, b) => a * b, - '+': (a, b) => a + b, - '-': (a, b) => a - b, - '/': (a, b) => a / b, - '**': (a, b) => a ** b - }; - const [stack, solve] = [ - [], - rpn - .replace(/\^/g, '**') - .split(/\s+/g) - .filter(el => !/\s+/.test(el) && el !== '') - ]; - solve.forEach(symbol => { - if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) { - stack.push(symbol); - } else if (Object.keys(OPERATORS).includes(symbol)) { - const [a, b] = [stack.pop(), stack.pop()]; - stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a))); - } else { - throw `${symbol} is not a recognized symbol`; - } - }); - if (stack.length === 1) return stack.pop(); - else throw `${rpn} is not a proper RPN. Please check it and try again`; -}; -``` - --- -Examples
- -```js -solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5 -solveRPN('2 3 ^'); // 8 -``` - -
[⬆ Back to top](#table-of-contents) - - -### howManyTimes - -Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer. -Works for both negative and positive integers. - -If `divisor` is `-1` or `1` return `Infinity`. -If `divisor` is `-0` or `0` return `0`. -Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer. -Return the number of times the loop was executed, `i`. - -```js -const howManyTimes = (num, divisor) => { - if (divisor === 1 || divisor === -1) return Infinity; - if (divisor === 0) return 0; - let i = 0; - while (Number.isInteger(num / divisor)) { - i++; - num = num / divisor; - } - return i; -}; -``` - --- -Examples
- -```js -howManyTimes(100, 2); // 2 -howManyTimes(100, 2.5); // 2 -howManyTimes(100, 0); // 0 -howManyTimes(100, -1); // Infinity -``` - -
[⬆ Back to top](#table-of-contents) - diff --git a/tag_database b/tag_database index 08f5b3fae..84a3b4dfa 100644 --- a/tag_database +++ b/tag_database @@ -75,30 +75,40 @@ indexOfAll:array initial:array initialize2DArray:array initializeArrayWithRange:array,math +initializeArrayWithRangeRight:array,math initializeArrayWithValues:array,math inRange:math intersection:array,math invertKeyValues:object isAbsoluteURL:string,utility,browser,url isArray:type,array +isArrayBuffer:type isArrayLike:type,array isBoolean:type isDivisible:math isEven:math isFunction:type,function isLowerCase:string,utility +isMap:type +isNil:type isNull:type isNumber:type,math isObject:type,object isPrime:math isPrimitive:type,function,array,string isPromiseLike:type,function,promise +isRegExp:type,regexp +isSet:type isSorted:array isString:type,string isSymbol:type isTravisCI:node +isTypedArray:type +isUndefined:type isUpperCase:string,utility isValidJSON:type,json +isWeakMap:type +isWeakSet:type join:array JSONToFile:node,json last:array @@ -121,6 +131,7 @@ negate:function nthElement:array objectFromPairs:object,array objectToPairs:object,array +observeMutations:browser,event,advanced off:browser,event on:browser,event once:function diff --git a/test/observeMutations/observeMutations.js b/test/observeMutations/observeMutations.js new file mode 100644 index 000000000..15a462fac --- /dev/null +++ b/test/observeMutations/observeMutations.js @@ -0,0 +1,18 @@ +module.exports = observeMutations = (element, callback, options) => { +const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); +observer.observe( +element, +Object.assign( +{ +childList: true, +attributes: true, +attributeOldValue: true, +characterData: true, +characterDataOldValue: true, +subtree: true +}, +options +) +); +return observer; +}; \ No newline at end of file diff --git a/test/observeMutations/observeMutations.test.js b/test/observeMutations/observeMutations.test.js new file mode 100644 index 000000000..eca8ff0d4 --- /dev/null +++ b/test/observeMutations/observeMutations.test.js @@ -0,0 +1,13 @@ +const test = require('tape'); +const observeMutations = require('./observeMutations.js'); + +test('Testing observeMutations', (t) => { + //For more information on all the methods supported by tape + //Please go to https://github.com/substack/tape + t.true(typeof observeMutations === 'function', 'observeMutations is a Function'); + //t.deepEqual(observeMutations(args..), 'Expected'); + //t.equal(observeMutations(args..), 'Expected'); + //t.false(observeMutations(args..), 'Expected'); + //t.throws(observeMutations(args..), 'Expected'); + t.end(); +}); \ No newline at end of file diff --git a/test/testlog b/test/testlog index d2f4be138..958ea9de0 100644 --- a/test/testlog +++ b/test/testlog @@ -721,6 +721,10 @@ Test log for: Tue Jan 16 2018 15:31:32 GMT+0200 (GTB Standard Time) √ objectToPairs is a Function √ Creates an array of key-value pair arrays from an object. + Testing observeMutations + + ✔ observeMutations is a Function + Testing off √ off is a Function @@ -1153,3 +1157,4 @@ Test log for: Tue Jan 16 2018 15:31:32 GMT+0200 (GTB Standard Time) duration: 345ms +