├── .gitattributes ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── languageFix.js ├── logo.png ├── snippet-template.md └── snippets ├── CSVToArray.md ├── CSVToJSON.md ├── HSBToRGB.md ├── HSLToRGB.md ├── JSONToFile.md ├── JSONtoCSV.md ├── RGBToHSB.md ├── RGBToHSL.md ├── RGBToHex.md ├── URLJoin.md ├── UUIDGeneratorBrowser.md ├── UUIDGeneratorNode.md ├── accumulate.md ├── addClass.md ├── addDaysToDate.md ├── addEventListenerAll.md ├── addMinutesToDate.md ├── addMultipleEvents.md ├── addStyles.md ├── addWeekDays.md ├── all.md ├── allEqual.md ├── allEqualBy.md ├── allUnique.md ├── allUniqueBy.md ├── and.md ├── any.md ├── aperture.md ├── approximatelyEqual.md ├── arithmeticProgression.md ├── arrayToCSV.md ├── arrayToHTMLList.md ├── ary.md ├── assertValidKeys.md ├── atob.md ├── attempt.md ├── average.md ├── averageBy.md ├── bifurcate.md ├── bifurcateBy.md ├── binary.md ├── binarySearch.md ├── bind.md ├── bindAll.md ├── bindKey.md ├── binomialCoefficient.md ├── both.md ├── bottomVisible.md ├── btoa.md ├── bubbleSort.md ├── bucketSort.md ├── byteSize.md ├── caesarCipher.md ├── call.md ├── capitalize.md ├── capitalizeEveryWord.md ├── cartesianProduct.md ├── castArray.md ├── celsiusToFahrenheit.md ├── chainAsync.md ├── changeLightness.md ├── checkProp.md ├── chunk.md ├── chunkIntoN.md ├── chunkify.md ├── clampNumber.md ├── cloneRegExp.md ├── coalesce.md ├── coalesceFactory.md ├── collectInto.md ├── colorize.md ├── combine.md ├── compact.md ├── compactObject.md ├── compactWhitespace.md ├── complement.md ├── compose.md ├── composeRight.md ├── containsWhitespace.md ├── converge.md ├── copySign.md ├── copyToClipboard.md ├── countBy.md ├── countOccurrences.md ├── countSubstrings.md ├── countWeekDaysBetween.md ├── counter.md ├── createDirIfNotExists.md ├── createElement.md ├── createEventHub.md ├── currentURL.md ├── curry.md ├── cycleGenerator.md ├── dateRangeGenerator.md ├── dayName.md ├── dayOfYear.md ├── daysAgo.md ├── daysFromNow.md ├── daysInMonth.md ├── debounce.md ├── debouncePromise.md ├── decapitalize.md ├── deepClone.md ├── deepFlatten.md ├── deepFreeze.md ├── deepGet.md ├── deepMapKeys.md ├── deepMerge.md ├── defaults.md ├── defer.md ├── degreesToRads.md ├── delay.md ├── detectDeviceType.md ├── detectLanguage.md ├── difference.md ├── differenceBy.md ├── differenceWith.md ├── dig.md ├── digitize.md ├── distance.md ├── divmod.md ├── drop.md ├── dropRight.md ├── dropRightWhile.md ├── dropWhile.md ├── either.md ├── elementContains.md ├── elementIsFocused.md ├── elementIsVisibleInViewport.md ├── equals.md ├── escapeHTML.md ├── escapeRegExp.md ├── euclideanDistance.md ├── everyNth.md ├── expandTabs.md ├── extendHex.md ├── factorial.md ├── fahrenheitToCelsius.md ├── fibonacci.md ├── filterNonUnique.md ├── filterNonUniqueBy.md ├── filterUnique.md ├── filterUniqueBy.md ├── findClosestAnchor.md ├── findClosestMatchingNode.md ├── findFirstN.md ├── findKey.md ├── findKeys.md ├── findLast.md ├── findLastIndex.md ├── findLastKey.md ├── findLastN.md ├── flatten.md ├── flattenObject.md ├── flip.md ├── forEachRight.md ├── forOwn.md ├── forOwnRight.md ├── formToObject.md ├── formatDuration.md ├── formatNumber.md ├── formatSeconds.md ├── frequencies.md ├── fromCamelCase.md ├── fromTimestamp.md ├── frozenSet.md ├── fullscreen.md ├── functionName.md ├── functions.md ├── gcd.md ├── generateItems.md ├── generatorToArray.md ├── geometricProgression.md ├── get.md ├── getAncestors.md ├── getBaseURL.md ├── getColonTimeFromDate.md ├── getDaysDiffBetweenDates.md ├── getElementsBiggerThanViewport.md ├── getHoursDiffBetweenDates.md ├── getImages.md ├── getMeridiemSuffixOfInteger.md ├── getMinutesDiffBetweenDates.md ├── getMonthsDiffBetweenDates.md ├── getParentsUntil.md ├── getProtocol.md ├── getScrollPosition.md ├── getSecondsDiffBetweenDates.md ├── getSelectedText.md ├── getSiblings.md ├── getStyle.md ├── getTimestamp.md ├── getType.md ├── getURLParameters.md ├── getVerticalOffset.md ├── groupBy.md ├── hammingDistance.md ├── hasClass.md ├── hasDuplicates.md ├── hasFlags.md ├── hasKey.md ├── hasMany.md ├── hasOne.md ├── hashBrowser.md ├── hashNode.md ├── haveSameContents.md ├── head.md ├── heapsort.md ├── hexToRGB.md ├── hide.md ├── httpDelete.md ├── httpGet.md ├── httpPost.md ├── httpPut.md ├── httpsRedirect.md ├── hz.md ├── inRange.md ├── includesAll.md ├── includesAny.md ├── indentString.md ├── indexBy.md ├── indexOfAll.md ├── indexOfSubstrings.md ├── indexOn.md ├── initial.md ├── initialize2DArray.md ├── initializeArrayWithRange.md ├── initializeArrayWithRangeRight.md ├── initializeArrayWithValues.md ├── initializeNDArray.md ├── injectCSS.md ├── insertAfter.md ├── insertAt.md ├── insertBefore.md ├── insertionSort.md ├── intersection.md ├── intersectionBy.md ├── intersectionWith.md ├── invertKeyValues.md ├── is.md ├── isAbsoluteURL.md ├── isAfterDate.md ├── isAlpha.md ├── isAlphaNumeric.md ├── isAnagram.md ├── isArrayLike.md ├── isAsyncFunction.md ├── isBeforeDate.md ├── isBetweenDates.md ├── isBoolean.md ├── isBrowser.md ├── isBrowserTabFocused.md ├── isContainedIn.md ├── isDateValid.md ├── isDeepFrozen.md ├── isDisjoint.md ├── isDivisible.md ├── isDuplexStream.md ├── isEmpty.md ├── isEven.md ├── isFunction.md ├── isGeneratorFunction.md ├── isISOString.md ├── isLeapYear.md ├── isLocalStorageEnabled.md ├── isLowerCase.md ├── isNegativeZero.md ├── isNil.md ├── isNode.md ├── isNull.md ├── isNumber.md ├── isObject.md ├── isObjectLike.md ├── isOdd.md ├── isPlainObject.md ├── isPowerOfTen.md ├── isPowerOfTwo.md ├── isPrime.md ├── isPrimitive.md ├── isPromiseLike.md ├── isReadableStream.md ├── isSameDate.md ├── isSameOrigin.md ├── isSessionStorageEnabled.md ├── isSorted.md ├── isStream.md ├── isString.md ├── isSymbol.md ├── isTravisCI.md ├── isUndefined.md ├── isUpperCase.md ├── isValidJSON.md ├── isWeekday.md ├── isWeekend.md ├── isWritableStream.md ├── join.md ├── juxt.md ├── kMeans.md ├── kNearestNeighbors.md ├── kmToMiles.md ├── last.md ├── lastDateOfMonth.md ├── lcm.md ├── levenshteinDistance.md ├── linearSearch.md ├── listenOnce.md ├── logBase.md ├── longestItem.md ├── lowercaseKeys.md ├── luhnCheck.md ├── mapConsecutive.md ├── mapKeys.md ├── mapNumRange.md ├── mapObject.md ├── mapString.md ├── mapValues.md ├── mask.md ├── matches.md ├── matchesWith.md ├── maxBy.md ├── maxDate.md ├── maxN.md ├── median.md ├── memoize.md ├── merge.md ├── mergeSort.md ├── mergeSortedArrays.md ├── midpoint.md ├── milesToKm.md ├── minBy.md ├── minDate.md ├── minN.md ├── mostFrequent.md ├── mostPerformant.md ├── negate.md ├── nest.md ├── nodeListToArray.md ├── none.md ├── nor.md ├── normalizeLineEndings.md ├── not.md ├── nthArg.md ├── nthElement.md ├── nthRoot.md ├── objectFromPairs.md ├── objectToEntries.md ├── objectToPairs.md ├── objectToQueryString.md ├── observeMutations.md ├── off.md ├── offset.md ├── omit.md ├── omitBy.md ├── on.md ├── onClickOutside.md ├── onScrollStop.md ├── onUserInputChange.md ├── once.md ├── or.md ├── orderBy.md ├── orderWith.md ├── over.md ├── overArgs.md ├── pad.md ├── padNumber.md ├── palindrome.md ├── parseCookie.md ├── partial.md ├── partialRight.md ├── partition.md ├── partitionBy.md ├── percentile.md ├── permutations.md ├── pick.md ├── pickBy.md ├── pipeAsyncFunctions.md ├── pipeFunctions.md ├── pluck.md ├── pluralize.md ├── powerset.md ├── prefersDarkColorScheme.md ├── prefersLightColorScheme.md ├── prefix.md ├── prettyBytes.md ├── primeFactors.md ├── primes.md ├── prod.md ├── promisify.md ├── pull.md ├── pullAtIndex.md ├── pullAtValue.md ├── pullBy.md ├── quarterOfYear.md ├── queryStringToObject.md ├── quickSort.md ├── radsToDegrees.md ├── randomAlphaNumeric.md ├── randomBoolean.md ├── randomHexColorCode.md ├── randomIntArrayInRange.md ├── randomIntegerInRange.md ├── randomNumberInRange.md ├── rangeGenerator.md ├── readFileLines.md ├── rearg.md ├── recordAnimationFrames.md ├── redirect.md ├── reduceSuccessive.md ├── reduceWhich.md ├── reducedFilter.md ├── reject.md ├── remove.md ├── removeAccents.md ├── removeClass.md ├── removeElement.md ├── removeEventListenerAll.md ├── removeNonASCII.md ├── removeWhitespace.md ├── renameKeys.md ├── renderElement.md ├── repeatGenerator.md ├── replaceLast.md ├── requireUncached.md ├── reverseNumber.md ├── reverseString.md ├── round.md ├── runAsync.md ├── runPromisesInSeries.md ├── sample.md ├── sampleSize.md ├── scrollToTop.md ├── sdbm.md ├── selectionSort.md ├── serializeCookie.md ├── serializeForm.md ├── setStyle.md ├── shallowClone.md ├── shank.md ├── show.md ├── shuffle.md ├── similarity.md ├── size.md ├── sleep.md ├── slugify.md ├── smoothScroll.md ├── sortCharactersInString.md ├── sortedIndex.md ├── sortedIndexBy.md ├── sortedLastIndex.md ├── sortedLastIndexBy.md ├── splitLines.md ├── spreadOver.md ├── stableSort.md ├── standardDeviation.md ├── stringPermutations.md ├── stringifyCircularJSON.md ├── stripHTMLTags.md ├── subSet.md ├── sum.md ├── sumBy.md ├── sumN.md ├── sumPower.md ├── superSet.md ├── supportsTouchEvents.md ├── swapCase.md ├── symbolizeKeys.md ├── symmetricDifference.md ├── symmetricDifferenceBy.md ├── symmetricDifferenceWith.md ├── tail.md ├── take.md ├── takeRight.md ├── takeRightUntil.md ├── takeRightWhile.md ├── takeUntil.md ├── takeWhile.md ├── throttle.md ├── timeTaken.md ├── times.md ├── toCamelCase.md ├── toCharArray.md ├── toCurrency.md ├── toDecimalMark.md ├── toHSLArray.md ├── toHSLObject.md ├── toHash.md ├── toISOStringWithTimezone.md ├── toKebabCase.md ├── toOrdinalSuffix.md ├── toPairs.md ├── toPascalCase.md ├── toRGBArray.md ├── toRGBObject.md ├── toRomanNumeral.md ├── toSafeInteger.md ├── toSnakeCase.md ├── toTitleCase.md ├── toggleClass.md ├── tomorrow.md ├── transform.md ├── triggerEvent.md ├── truncateString.md ├── truncateStringAtWhitespace.md ├── truthCheckCollection.md ├── unary.md ├── uncurry.md ├── unescapeHTML.md ├── unflattenObject.md ├── unfold.md ├── union.md ├── unionBy.md ├── unionWith.md ├── uniqueElements.md ├── uniqueElementsBy.md ├── uniqueElementsByRight.md ├── uniqueSymmetricDifference.md ├── untildify.md ├── unzip.md ├── unzipWith.md ├── validateNumber.md ├── vectorAngle.md ├── vectorDistance.md ├── walkThrough.md ├── weekOfYear.md ├── weightedAverage.md ├── weightedSample.md ├── when.md ├── without.md ├── wordWrap.md ├── words.md ├── xProd.md ├── xor.md ├── yesNo.md ├── yesterday.md ├── zip.md ├── zipObject.md └── zipWith.md /.gitattributes: -------------------------------------------------------------------------------- 1 | src/docs/* linguist-documentation 2 | scripts/* linguist-documentation 3 | gatsby-browser.js linguist-documentation 4 | gatsby-config.js linguist-documentation 5 | gatsby-node.js linguist-documentation 6 | gatsby-ssr.js linguist-documentation 7 | .travis/* linguist-documentation 8 | -------------------------------------------------------------------------------- /languageFix.js: -------------------------------------------------------------------------------- 1 | console.log('This file is here only to tag the repository language. Do not delete, please!'); 2 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mr-dev-dragon/30-seconds-of-code/a7eba421425340c00eb695655ed6b826a37d6fa5/logo.png -------------------------------------------------------------------------------- /snippet-template.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: functionName 3 | tags: array,intermediate 4 | firstSeen: 2021-06-13T05:00:00-04:00 5 | --- 6 | 7 | Explain briefly what the snippet does. 8 | 9 | - Explain briefly how the snippet works. 10 | - Use bullet points for your snippet's explanation. 11 | - Try to explain everything briefly but clearly. 12 | 13 | ```js 14 | const functionName = arguments => 15 | {functionBody} 16 | ``` 17 | 18 | ```js 19 | functionName('sampleInput'); // 'sampleOutput' 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/JSONToFile.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: JSONToFile 3 | tags: node,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Writes a JSON object to a file. 9 | 10 | - Use `fs.writeFileSync()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file. 11 | 12 | ```js 13 | const fs = require('fs'); 14 | 15 | const JSONToFile = (obj, filename) => 16 | fs.writeFileSync(`${filename}.json`, JSON.stringify(obj, null, 2)); 17 | ``` 18 | 19 | ```js 20 | JSONToFile({ test: 'is passed' }, 'testJsonFile'); 21 | // writes the object to 'testJsonFile.json' 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/RGBToHex.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: RGBToHex 3 | tags: string,math,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-11-03T22:11:18+02:00 6 | --- 7 | 8 | Converts the values of RGB components to a hexadecimal color code. 9 | 10 | - Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `Number.prototype.toString(16)`. 11 | - Use `String.prototype.padStart(6, '0')` to get a 6-digit hexadecimal value. 12 | 13 | ```js 14 | const RGBToHex = (r, g, b) => 15 | ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); 16 | ``` 17 | 18 | ```js 19 | RGBToHex(255, 165, 1); // 'ffa501' 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/UUIDGeneratorBrowser.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: UUIDGeneratorBrowser 3 | tags: browser,random,intermediate 4 | firstSeen: 2017-12-29T09:47:10+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Generates a UUID in a browser. 9 | 10 | - Use `Crypto.getRandomValues()` to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4. 11 | - Use `Number.prototype.toString(16)` to convert it to a proper UUID. 12 | 13 | ```js 14 | const UUIDGeneratorBrowser = () => 15 | ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => 16 | ( 17 | c ^ 18 | (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4))) 19 | ).toString(16) 20 | ); 21 | ``` 22 | 23 | ```js 24 | UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d' 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/UUIDGeneratorNode.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: UUIDGeneratorNode 3 | tags: node,random,intermediate 4 | firstSeen: 2017-12-29T09:47:10+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Generates a UUID in Node.JS. 9 | 10 | - Use `crypto.randomBytes()` to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4. 11 | - Use `Number.prototype.toString(16)` to convert it to a proper UUID. 12 | 13 | ```js 14 | const crypto = require('crypto'); 15 | 16 | const UUIDGeneratorNode = () => 17 | ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => 18 | (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) 19 | ); 20 | ``` 21 | 22 | ```js 23 | UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc' 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/accumulate.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: accumulate 3 | tags: math,array,intermediate 4 | firstSeen: 2020-05-04T12:20:46+03:00 5 | lastUpdated: 2020-11-03T21:46:13+02:00 6 | --- 7 | 8 | Creates an array of partial sums. 9 | 10 | - Use `Array.prototype.reduce()`, initialized with an empty array accumulator to iterate over `nums`. 11 | - Use `Array.prototype.slice(-1)`, the spread operator (`...`) and the unary `+` operator to add each value to the accumulator array containing the previous sums. 12 | 13 | ```js 14 | const accumulate = (...nums) => 15 | nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)], []); 16 | ``` 17 | 18 | ```js 19 | accumulate(1, 2, 3, 4); // [1, 3, 6, 10] 20 | accumulate(...[1, 2, 3, 4]); // [1, 3, 6, 10] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/addClass.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: addClass 3 | tags: browser,beginner 4 | firstSeen: 2020-12-30T19:21:15+02:00 5 | lastUpdated: 2020-12-30T19:21:15+02:00 6 | --- 7 | 8 | Adds a class to an HTML element. 9 | 10 | - Use `Element.classList` and `DOMTokenList.add()` to add the specified class to the element. 11 | 12 | ```js 13 | const addClass = (el, className) => el.classList.add(className); 14 | ``` 15 | 16 | ```js 17 | addClass(document.querySelector('p'), 'special'); 18 | // The paragraph will now have the 'special' class 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/addMultipleEvents.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: addMultipleListeners 3 | tags: browser,event,intermediate 4 | firstSeen: 2020-10-08T00:40:30+03:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Adds multiple event listeners with the same handler to an element. 9 | 10 | - Use `Array.prototype.forEach()` and `EventTarget.addEventListener()` to add multiple event listeners with an assigned callback function to an element. 11 | 12 | ```js 13 | const addMultipleListeners = (el, types, listener, options, useCapture) => { 14 | types.forEach(type => 15 | el.addEventListener(type, listener, options, useCapture) 16 | ); 17 | }; 18 | ``` 19 | 20 | ```js 21 | addMultipleListeners( 22 | document.querySelector('.my-element'), 23 | ['click', 'mousedown'], 24 | () => { console.log('hello!') } 25 | ); 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/addStyles.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: addStyles 3 | tags: browser,beginner 4 | firstSeen: 2021-01-07T00:37:43+02:00 5 | lastUpdated: 2021-01-07T00:37:43+02:00 6 | --- 7 | 8 | Adds the provided styles to the given element. 9 | 10 | - Use `Object.assign()` and `ElementCSSInlineStyle.style` to merge the provided `styles` object into the style of the given element. 11 | 12 | ```js 13 | const addStyles = (el, styles) => Object.assign(el.style, styles); 14 | ``` 15 | 16 | ```js 17 | addStyles(document.getElementById('my-element'), { 18 | background: 'red', 19 | color: '#ffff00', 20 | fontSize: '3rem' 21 | }); 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/all.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: all 3 | tags: array,beginner 4 | firstSeen: 2018-02-14T11:46:15+02:00 5 | lastUpdated: 2020-10-18T20:24:28+03:00 6 | --- 7 | 8 | Checks if the provided predicate function returns `true` for all elements in a collection. 9 | 10 | - Use `Array.prototype.every()` to test if all elements in the collection return `true` based on `fn`. 11 | - Omit the second argument, `fn`, to use `Boolean` as a default. 12 | 13 | ```js 14 | const all = (arr, fn = Boolean) => arr.every(fn); 15 | ``` 16 | 17 | ```js 18 | all([4, 2, 3], x => x > 1); // true 19 | all([1, 2, 3]); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/allEqual.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: allEqual 3 | tags: array,beginner 4 | firstSeen: 2018-08-03T00:03:08+03:00 5 | lastUpdated: 2020-10-18T20:24:28+03:00 6 | --- 7 | 8 | Checks if all elements in an array are equal. 9 | 10 | - Use `Array.prototype.every()` to check if all the elements of the array are the same as the first one. 11 | - Elements in the array are compared using the strict comparison operator, which does not account for `NaN` self-inequality. 12 | 13 | ```js 14 | const allEqual = arr => arr.every(val => val === arr[0]); 15 | ``` 16 | 17 | ```js 18 | allEqual([1, 2, 3, 4, 5, 6]); // false 19 | allEqual([1, 1, 1, 1]); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/allUnique.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: allUnique 3 | tags: array,beginner 4 | firstSeen: 2020-10-19T19:47:26+03:00 5 | lastUpdated: 2021-01-08T00:23:44+02:00 6 | --- 7 | 8 | Checks if all elements in an array are unique. 9 | 10 | - Create a new `Set` from the mapped values to keep only unique occurrences. 11 | - Use `Array.prototype.length` and `Set.prototype.size` to compare the length of the unique values to the original array. 12 | 13 | ```js 14 | const allUnique = arr => arr.length === new Set(arr).size; 15 | ``` 16 | 17 | ```js 18 | allUnique([1, 2, 3, 4]); // true 19 | allUnique([1, 1, 2, 3]); // false 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/allUniqueBy.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: allUniqueBy 3 | tags: array,intermediate 4 | firstSeen: 2020-10-19T22:15:05+03:00 5 | lastUpdated: 2021-01-08T00:23:44+02:00 6 | --- 7 | 8 | Checks if all elements in an array are unique, based on the provided mapping function. 9 | 10 | - Use `Array.prototype.map()` to apply `fn` to all elements in `arr`. 11 | - Create a new `Set` from the mapped values to keep only unique occurrences. 12 | - Use `Array.prototype.length` and `Set.prototype.size` to compare the length of the unique mapped values to the original array. 13 | 14 | ```js 15 | const allUniqueBy = (arr, fn) => arr.length === new Set(arr.map(fn)).size; 16 | ``` 17 | 18 | ```js 19 | allUniqueBy([1.2, 2.4, 2.9], Math.round); // true 20 | allUniqueBy([1.2, 2.3, 2.4], Math.round); // false 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/and.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: and 3 | tags: math,logic,beginner 4 | unlisted: true 5 | firstSeen: 2020-05-13T11:35:31+03:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Checks if both arguments are `true`. 10 | 11 | - Use the logical and (`&&`) operator on the two given values. 12 | 13 | ```js 14 | const and = (a, b) => a && b; 15 | ``` 16 | 17 | ```js 18 | and(true, true); // true 19 | and(true, false); // false 20 | and(false, false); // false 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/any.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: any 3 | tags: array,beginner 4 | firstSeen: 2018-02-14T11:46:15+02:00 5 | lastUpdated: 2020-10-18T20:24:28+03:00 6 | --- 7 | 8 | Checks if the provided predicate function returns `true` for at least one element in a collection. 9 | 10 | - Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`. 11 | - Omit the second argument, `fn`, to use `Boolean` as a default. 12 | 13 | ```js 14 | const any = (arr, fn = Boolean) => arr.some(fn); 15 | ``` 16 | 17 | ```js 18 | any([0, 1, 2, 0], x => x >= 2); // true 19 | any([0, 0, 1, 0]); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/approximatelyEqual.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: approximatelyEqual 3 | tags: math,beginner 4 | firstSeen: 2018-02-14T12:47:13+02:00 5 | lastUpdated: 2020-11-01T20:50:57+02:00 6 | --- 7 | 8 | Checks if two numbers are approximately equal to each other. 9 | 10 | - Use `Math.abs()` to compare the absolute difference of the two values to `epsilon`. 11 | - Omit the third argument, `epsilon`, to use a default value of `0.001`. 12 | 13 | ```js 14 | const approximatelyEqual = (v1, v2, epsilon = 0.001) => 15 | Math.abs(v1 - v2) < epsilon; 16 | ``` 17 | 18 | ```js 19 | approximatelyEqual(Math.PI / 2.0, 1.5708); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/arithmeticProgression.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: arithmeticProgression 3 | tags: math,algorithm,beginner 4 | firstSeen: 2020-10-04T11:37:07+03:00 5 | lastUpdated: 2021-10-13T19:29:39+02:00 6 | --- 7 | 8 | Creates an array of numbers in the arithmetic progression, starting with the given positive integer and up to the specified limit. 9 | 10 | - Use `Array.from()` to create an array of the desired length, `lim/n`. Use a map function to fill it with the desired values in the given range. 11 | 12 | ```js 13 | const arithmeticProgression = (n, lim) => 14 | Array.from({ length: Math.ceil(lim / n) }, (_, i) => (i + 1) * n ); 15 | ``` 16 | 17 | ```js 18 | arithmeticProgression(5, 25); // [5, 10, 15, 20, 25] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/arrayToHTMLList.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: arrayToHTMLList 3 | tags: browser,array,intermediate 4 | firstSeen: 2020-10-08T00:02:45+03:00 5 | lastUpdated: 2020-10-20T11:46:23+03:00 6 | --- 7 | 8 | Converts the given array elements into `
  • ` tags and appends them to the list of the given id. 9 | 10 | - Use `Array.prototype.map()` and `Document.querySelector()` to create a list of html tags. 11 | 12 | ```js 13 | const arrayToHTMLList = (arr, listID) => 14 | document.querySelector(`#${listID}`).innerHTML += arr 15 | .map(item => `
  • ${item}
  • `) 16 | .join(''); 17 | ``` 18 | 19 | ```js 20 | arrayToHTMLList(['item 1', 'item 2'], 'myListID'); 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/ary.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: ary 3 | tags: function,advanced 4 | firstSeen: 2018-01-24T13:59:54+02:00 5 | lastUpdated: 2020-10-18T20:24:28+03:00 6 | --- 7 | 8 | Creates a function that accepts up to `n` arguments, ignoring any additional arguments. 9 | 10 | - Call the provided function, `fn`, with up to `n` arguments, using `Array.prototype.slice(0, n)` and the spread operator (`...`). 11 | 12 | ```js 13 | const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); 14 | ``` 15 | 16 | ```js 17 | const firstTwoMax = ary(Math.max, 2); 18 | [[2, 6, 'a'], [6, 4, 8], [10]].map(x => firstTwoMax(...x)); // [6, 6, 10] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/assertValidKeys.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: assertValidKeys 3 | tags: object,intermediate 4 | firstSeen: 2021-07-18T05:00:00-04:00 5 | --- 6 | 7 | Validates all keys in an object match the given `keys`. 8 | 9 | - Use `Object.keys()` to get the keys of the given object, `obj`. 10 | - Use `Array.prototype.every()` and `Array.prototype.includes()` to validate that each key in the object is specified in the `keys` array. 11 | 12 | ```js 13 | const assertValidKeys = (obj, keys) => 14 | Object.keys(obj).every(key => keys.includes(key)); 15 | ``` 16 | 17 | ```js 18 | assertValidKeys({ id: 10, name: 'apple' }, ['id', 'name']); // true 19 | assertValidKeys({ id: 10, name: 'apple' }, ['id', 'type']); // false 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/atob.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: atob 3 | tags: node,string,beginner 4 | firstSeen: 2018-01-17T21:43:21+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Decodes a string of data which has been encoded using base-64 encoding. 9 | 10 | - Create a `Buffer` for the given string with base-64 encoding and use `Buffer.toString('binary')` to return the decoded string. 11 | 12 | ```js 13 | const atob = str => Buffer.from(str, 'base64').toString('binary'); 14 | ``` 15 | 16 | ```js 17 | atob('Zm9vYmFy'); // 'foobar' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/average.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: average 3 | tags: math,array,beginner 4 | firstSeen: 2017-12-29T13:29:49+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Calculates the average of two or more numbers. 9 | 10 | - Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`. 11 | - Divide the resulting array by its length. 12 | 13 | ```js 14 | const average = (...nums) => 15 | nums.reduce((acc, val) => acc + val, 0) / nums.length; 16 | ``` 17 | 18 | ```js 19 | average(...[1, 2, 3]); // 2 20 | average(1, 2, 3); // 2 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/bifurcate.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: bifurcate 3 | tags: array,intermediate 4 | firstSeen: 2018-02-14T12:13:07+02:00 5 | lastUpdated: 2020-11-01T20:50:57+02:00 6 | --- 7 | 8 | Splits values into two groups, based on the result of the given `filter` array. 9 | 10 | - Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`. 11 | - If `filter` has a truthy value for any element, add it to the first group, otherwise add it to the second group. 12 | 13 | ```js 14 | const bifurcate = (arr, filter) => 15 | arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [ 16 | [], 17 | [], 18 | ]); 19 | ``` 20 | 21 | ```js 22 | bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); 23 | // [ ['beep', 'boop', 'bar'], ['foo'] ] 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/binary.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: binary 3 | tags: function,intermediate 4 | firstSeen: 2020-05-13T13:36:36+03:00 5 | lastUpdated: 2020-10-18T23:04:45+03:00 6 | --- 7 | 8 | Creates a function that accepts up to two arguments, ignoring any additional arguments. 9 | 10 | - Call the provided function, `fn`, with the first two arguments given. 11 | 12 | ```js 13 | const binary = fn => (a, b) => fn(a, b); 14 | ``` 15 | 16 | ```js 17 | ['2', '1', '0'].map(binary(Math.max)); // [2, 1, 2] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/both.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: both 3 | tags: function,logic,beginner 4 | unlisted: true 5 | firstSeen: 2020-05-13T11:35:36+03:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Checks if both of the given functions return `true` for a given set of arguments. 10 | 11 | - Use the logical and (`&&`) operator on the result of calling the two functions with the supplied `args`. 12 | 13 | ```js 14 | const both = (f, g) => (...args) => f(...args) && g(...args); 15 | ``` 16 | 17 | ```js 18 | const isEven = num => num % 2 === 0; 19 | const isPositive = num => num > 0; 20 | const isPositiveEven = both(isEven, isPositive); 21 | isPositiveEven(4); // true 22 | isPositiveEven(-2); // false 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/bottomVisible.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: bottomVisible 3 | tags: browser,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Checks if the bottom of the page is visible. 9 | 10 | - Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible. 11 | 12 | ```js 13 | const bottomVisible = () => 14 | document.documentElement.clientHeight + window.scrollY >= 15 | (document.documentElement.scrollHeight || 16 | document.documentElement.clientHeight); 17 | ``` 18 | 19 | ```js 20 | bottomVisible(); // true 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/btoa.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: btoa 3 | tags: node,string,beginner 4 | firstSeen: 2018-01-17T21:43:21+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | 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. 9 | 10 | - Create a `Buffer` for the given string with binary encoding and use `Buffer.toString('base64')` to return the encoded string. 11 | 12 | ```js 13 | const btoa = str => Buffer.from(str, 'binary').toString('base64'); 14 | ``` 15 | 16 | ```js 17 | btoa('foobar'); // 'Zm9vYmFy' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/byteSize.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: byteSize 3 | tags: string,beginner 4 | firstSeen: 2017-12-29T14:30:34+02:00 5 | lastUpdated: 2020-10-18T23:04:45+03:00 6 | --- 7 | 8 | Returns the length of a string in bytes. 9 | 10 | - Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob). 11 | - Use `Blob.size` to get the length of the string in bytes. 12 | 13 | ```js 14 | const byteSize = str => new Blob([str]).size; 15 | ``` 16 | 17 | ```js 18 | byteSize('😀'); // 4 19 | byteSize('Hello World'); // 11 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/call.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: call 3 | tags: function,advanced 4 | firstSeen: 2017-12-22T21:54:30+02:00 5 | lastUpdated: 2021-06-13T13:50:25+03:00 6 | --- 7 | 8 | Given a key and a set of arguments, call them when given a context. 9 | 10 | - Use a closure to call `key` with `args` for the given `context`. 11 | 12 | ```js 13 | const call = (key, ...args) => context => context[key](...args); 14 | ``` 15 | 16 | ```js 17 | Promise.resolve([1, 2, 3]) 18 | .then(call('map', x => 2 * x)) 19 | .then(console.log); // [ 2, 4, 6 ] 20 | const map = call.bind(null, 'map'); 21 | Promise.resolve([1, 2, 3]) 22 | .then(map(x => 2 * x)) 23 | .then(console.log); // [ 2, 4, 6 ] 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/capitalizeEveryWord.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: capitalizeEveryWord 3 | tags: string,regexp,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Capitalizes the first letter of every word in a string. 9 | 10 | - Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it. 11 | 12 | ```js 13 | const capitalizeEveryWord = str => 14 | str.replace(/\b[a-z]/g, char => char.toUpperCase()); 15 | ``` 16 | 17 | ```js 18 | capitalizeEveryWord('hello world!'); // 'Hello World!' 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/cartesianProduct.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: cartesianProduct 3 | tags: math,array,beginner 4 | firstSeen: 2020-12-28T20:23:47+02:00 5 | lastUpdated: 2020-12-29T12:31:43+02:00 6 | --- 7 | 8 | Calculates the cartesian product of two arrays. 9 | 10 | - Use `Array.prototype.reduce()`, `Array.prototype.map()` and the spread operator (`...`) to generate all possible element pairs from the two arrays. 11 | 12 | ```js 13 | const cartesianProduct = (a, b) => 14 | a.reduce((p, x) => [...p, ...b.map(y => [x, y])], []); 15 | ``` 16 | 17 | ```js 18 | cartesianProduct(['x', 'y'], [1, 2]); 19 | // [['x', 1], ['x', 2], ['y', 1], ['y', 2]] 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/castArray.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: castArray 3 | tags: type,array,beginner 4 | firstSeen: 2018-01-23T20:54:12+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Casts the provided value as an array if it's not one. 9 | 10 | - Use `Array.prototype.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly. 11 | 12 | ```js 13 | const castArray = val => (Array.isArray(val) ? val : [val]); 14 | ``` 15 | 16 | ```js 17 | castArray('foo'); // ['foo'] 18 | castArray([1]); // [1] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/celsiusToFahrenheit.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: celsiusToFahrenheit 3 | tags: math,beginner 4 | unlisted: true 5 | firstSeen: 2020-04-16T11:00:06+03:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Converts Celsius to Fahrenheit. 10 | 11 | - Follow the conversion formula `F = 1.8 * C + 32`. 12 | 13 | ```js 14 | const celsiusToFahrenheit = degrees => 1.8 * degrees + 32; 15 | ``` 16 | 17 | ```js 18 | celsiusToFahrenheit(33); // 91.4 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/chunk.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: chunk 3 | tags: array,intermediate 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-11-03T21:35:12+02:00 6 | --- 7 | 8 | Chunks an array into smaller arrays of a specified size. 9 | 10 | - Use `Array.from()` to create a new array, that fits the number of chunks that will be produced. 11 | - Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`. 12 | - If the original array can't be split evenly, the final chunk will contain the remaining elements. 13 | 14 | ```js 15 | const chunk = (arr, size) => 16 | Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => 17 | arr.slice(i * size, i * size + size) 18 | ); 19 | ``` 20 | 21 | ```js 22 | chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]] 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/clampNumber.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: clampNumber 3 | tags: math,beginner 4 | firstSeen: 2017-12-20T19:19:18+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Clamps `num` within the inclusive range specified by the boundary values `a` and `b`. 9 | 10 | - If `num` falls within the range, return `num`. 11 | - Otherwise, return the nearest number in the range. 12 | 13 | ```js 14 | const clampNumber = (num, a, b) => 15 | Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); 16 | ``` 17 | 18 | ```js 19 | clampNumber(2, 3, 5); // 3 20 | clampNumber(1, -1, -5); // -1 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/cloneRegExp.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: cloneRegExp 3 | tags: type,intermediate 4 | firstSeen: 2018-01-01T19:45:47+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Clones a regular expression. 9 | 10 | - Use `new RegExp()`, `RegExp.prototype.source` and `RegExp.prototype.flags` to clone the given regular expression. 11 | 12 | ```js 13 | const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); 14 | ``` 15 | 16 | ```js 17 | const regExp = /lorem ipsum/gi; 18 | const regExp2 = cloneRegExp(regExp); // regExp !== regExp2 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/coalesce.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: coalesce 3 | tags: type,beginner 4 | firstSeen: 2017-12-17T10:08:55+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Returns the first defined, non-null argument. 9 | 10 | - Use `Array.prototype.find()` and `Array.prototype.includes()` to find the first value that is not equal to `undefined` or `null`. 11 | 12 | ```js 13 | const coalesce = (...args) => args.find(v => ![undefined, null].includes(v)); 14 | ``` 15 | 16 | ```js 17 | coalesce(null, undefined, '', NaN, 'Waldo'); // '' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/coalesceFactory.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: coalesceFactory 3 | tags: function,type,intermediate 4 | firstSeen: 2017-12-18T12:15:36+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Customizes a coalesce function that returns the first argument which is true based on the given validator. 9 | 10 | - Use `Array.prototype.find()` to return the first argument that returns `true` from the provided argument validation function, `valid`. 11 | 12 | ```js 13 | const coalesceFactory = valid => (...args) => args.find(valid); 14 | ``` 15 | 16 | ```js 17 | const customCoalesce = coalesceFactory( 18 | v => ![null, undefined, '', NaN].includes(v) 19 | ); 20 | customCoalesce(undefined, null, NaN, '', 'Waldo'); // 'Waldo' 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/collectInto.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: collectInto 3 | tags: function,array,intermediate 4 | firstSeen: 2017-12-22T05:08:36+02:00 5 | lastUpdated: 2021-06-13T13:50:25+03:00 6 | --- 7 | 8 | Changes a function that accepts an array into a variadic function. 9 | 10 | - Given a function, return a closure that collects all inputs into an array-accepting function. 11 | 12 | ```js 13 | const collectInto = fn => (...args) => fn(args); 14 | ``` 15 | 16 | ```js 17 | const Pall = collectInto(Promise.all.bind(Promise)); 18 | let p1 = Promise.resolve(1); 19 | let p2 = Promise.resolve(2); 20 | let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3)); 21 | Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds) 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/compact.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: compact 3 | tags: array,beginner 4 | firstSeen: 2017-12-14T08:19:15+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Removes falsy values from an array. 9 | 10 | - Use `Array.prototype.filter()` to filter out falsy values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`). 11 | 12 | ```js 13 | const compact = arr => arr.filter(Boolean); 14 | ``` 15 | 16 | ```js 17 | compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); 18 | // [ 1, 2, 3, 'a', 's', 34 ] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/compactWhitespace.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: compactWhitespace 3 | tags: string,regexp,beginner 4 | firstSeen: 2018-12-12T19:11:33+02:00 5 | lastUpdated: 2020-10-18T23:04:45+03:00 6 | --- 7 | 8 | Compacts whitespaces in a string. 9 | 10 | - Use `String.prototype.replace()` with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space. 11 | 12 | ```js 13 | const compactWhitespace = str => str.replace(/\s{2,}/g, ' '); 14 | ``` 15 | 16 | ```js 17 | compactWhitespace('Lorem Ipsum'); // 'Lorem Ipsum' 18 | compactWhitespace('Lorem \n Ipsum'); // 'Lorem Ipsum' 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/complement.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: complement 3 | tags: function,logic,beginner 4 | firstSeen: 2020-05-13T11:28:33+03:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Returns a function that is the logical complement of the given function, `fn`. 9 | 10 | - Use the logical not (`!`) operator on the result of calling `fn` with any supplied `args`. 11 | 12 | ```js 13 | const complement = fn => (...args) => !fn(...args); 14 | ``` 15 | 16 | ```js 17 | const isEven = num => num % 2 === 0; 18 | const isOdd = complement(isEven); 19 | isOdd(2); // false 20 | isOdd(3); // true 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/compose.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: compose 3 | tags: function,intermediate 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Performs right-to-left function composition. 9 | 10 | - Use `Array.prototype.reduce()` to perform right-to-left function composition. 11 | - The last (rightmost) function can accept one or more arguments; the remaining functions must be unary. 12 | 13 | ```js 14 | const compose = (...fns) => 15 | fns.reduce((f, g) => (...args) => f(g(...args))); 16 | ``` 17 | 18 | ```js 19 | const add5 = x => x + 5; 20 | const multiply = (x, y) => x * y; 21 | const multiplyAndAdd5 = compose( 22 | add5, 23 | multiply 24 | ); 25 | multiplyAndAdd5(5, 2); // 15 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/composeRight.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: composeRight 3 | tags: function,intermediate 4 | firstSeen: 2018-01-23T22:12:56+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Performs left-to-right function composition. 9 | 10 | - Use `Array.prototype.reduce()` to perform left-to-right function composition. 11 | - The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. 12 | 13 | ```js 14 | const composeRight = (...fns) => 15 | fns.reduce((f, g) => (...args) => g(f(...args))); 16 | ``` 17 | 18 | ```js 19 | const add = (x, y) => x + y; 20 | const square = x => x * x; 21 | const addAndSquare = composeRight(add, square); 22 | addAndSquare(1, 2); // 9 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/containsWhitespace.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: containsWhitespace 3 | tags: string,regexp,beginner 4 | firstSeen: 2020-03-25T12:37:13+02:00 5 | lastUpdated: 2020-10-18T23:04:45+03:00 6 | --- 7 | 8 | Checks if the given string contains any whitespace characters. 9 | 10 | - Use `RegExp.prototype.test()` with an appropriate regular expression to check if the given string contains any whitespace characters. 11 | 12 | ```js 13 | const containsWhitespace = str => /\s/.test(str); 14 | ``` 15 | 16 | ```js 17 | containsWhitespace('lorem'); // false 18 | containsWhitespace('lorem ipsum'); // true 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/copySign.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: copySign 3 | tags: math,beginner 4 | firstSeen: 2020-10-07T23:52:57+03:00 5 | lastUpdated: 2020-10-07T23:52:57+03:00 6 | --- 7 | 8 | Returns the absolute value of the first number, but the sign of the second. 9 | 10 | - Use `Math.sign()` to check if the two numbers have the same sign. 11 | - Return `x` if they do, `-x` otherwise. 12 | 13 | ```js 14 | const copySign = (x, y) => Math.sign(x) === Math.sign(y) ? x : -x; 15 | ``` 16 | 17 | ```js 18 | copySign(2, 3); // 2 19 | copySign(2, -3); // -2 20 | copySign(-2, 3); // 2 21 | copySign(-2, -3); // -2 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/countOccurrences.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: countOccurrences 3 | tags: array,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-18T23:04:45+03:00 6 | --- 7 | 8 | Counts the occurrences of a value in an array. 9 | 10 | - Use `Array.prototype.reduce()` to increment a counter each time the specific value is encountered inside the array. 11 | 12 | ```js 13 | const countOccurrences = (arr, val) => 14 | arr.reduce((a, v) => (v === val ? a + 1 : a), 0); 15 | ``` 16 | 17 | ```js 18 | countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/createDirIfNotExists.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: createDirIfNotExists 3 | tags: node,beginner 4 | firstSeen: 2018-12-12T19:25:16+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Creates a directory, if it does not exist. 9 | 10 | - Use `fs.existsSync()` to check if the directory exists, `fs.mkdirSync()` to create it. 11 | 12 | ```js 13 | const fs = require('fs'); 14 | 15 | const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined); 16 | ``` 17 | 18 | ```js 19 | createDirIfNotExists('test'); 20 | // creates the directory 'test', if it doesn't exist 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/currentURL.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: currentURL 3 | tags: browser,beginner 4 | firstSeen: 2017-12-18T11:05:03+02:00 5 | lastUpdated: 2020-10-20T11:46:23+03:00 6 | --- 7 | 8 | Returns the current URL. 9 | 10 | - Use `Window.location.href` to get the current URL. 11 | 12 | ```js 13 | const currentURL = () => window.location.href; 14 | ``` 15 | 16 | ```js 17 | currentURL(); // 'https://www.google.com/' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/dayName.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: dayName 3 | tags: date,beginner 4 | firstSeen: 2020-10-04T00:31:08+03:00 5 | lastUpdated: 2020-11-01T20:50:57+02:00 6 | --- 7 | 8 | Gets the name of the weekday from a `Date` object. 9 | 10 | - Use `Date.prototype.toLocaleDateString()` with the `{ weekday: 'long' }` option to retrieve the weekday. 11 | - Use the optional second argument to get a language-specific name or omit it to use the default locale. 12 | 13 | ```js 14 | const dayName = (date, locale) => 15 | date.toLocaleDateString(locale, { weekday: 'long' }); 16 | ``` 17 | 18 | ```js 19 | dayName(new Date()); // 'Saturday' 20 | dayName(new Date('09/23/2020'), 'de-DE'); // 'Samstag' 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/dayOfYear.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: dayOfYear 3 | tags: date,beginner 4 | firstSeen: 2018-09-29T13:22:20+03:00 5 | lastUpdated: 2020-10-19T18:51:03+03:00 6 | --- 7 | 8 | Gets the day of the year (number in the range 1-366) from a `Date` object. 9 | 10 | - Use `new Date()` and `Date.prototype.getFullYear()` to get the first day of the year as a `Date` object. 11 | - Subtract the first day of the year from `date` and divide with the milliseconds in each day to get the result. 12 | - Use `Math.floor()` to appropriately round the resulting day count to an integer. 13 | 14 | ```js 15 | const dayOfYear = date => 16 | Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); 17 | ``` 18 | 19 | ```js 20 | dayOfYear(new Date()); // 272 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/daysAgo.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: daysAgo 3 | tags: date,beginner 4 | firstSeen: 2020-10-06T05:35:23+03:00 5 | lastUpdated: 2020-10-20T11:21:07+03:00 6 | --- 7 | 8 | Calculates the date of `n` days ago from today as a string representation. 9 | 10 | - Use `new Date()` to get the current date, `Math.abs()` and `Date.prototype.getDate()` to update the date accordingly and set to the result using `Date.prototype.setDate()`. 11 | - Use `Date.prototype.toISOString()` to return a string in `yyyy-mm-dd` format. 12 | 13 | ```js 14 | const daysAgo = n => { 15 | let d = new Date(); 16 | d.setDate(d.getDate() - Math.abs(n)); 17 | return d.toISOString().split('T')[0]; 18 | }; 19 | ``` 20 | 21 | ```js 22 | daysAgo(20); // 2020-09-16 (if current date is 2020-10-06) 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/daysFromNow.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: daysFromNow 3 | tags: date,beginner 4 | firstSeen: 2020-10-09T02:49:17+03:00 5 | lastUpdated: 2020-10-20T11:21:07+03:00 6 | --- 7 | 8 | Calculates the date of `n` days from today as a string representation. 9 | 10 | - Use `new Date()` to get the current date, `Math.abs()` and `Date.prototype.getDate()` to update the date accordingly and set to the result using `Date.prototype.setDate()`. 11 | - Use `Date.prototype.toISOString()` to return a string in `yyyy-mm-dd` format. 12 | 13 | ```js 14 | const daysFromNow = n => { 15 | let d = new Date(); 16 | d.setDate(d.getDate() + Math.abs(n)); 17 | return d.toISOString().split('T')[0]; 18 | }; 19 | ``` 20 | 21 | ```js 22 | daysFromNow(5); // 2020-10-13 (if current date is 2020-10-08) 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/daysInMonth.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: daysInMonth 3 | tags: date,beginner 4 | firstSeen: 2021-06-13T05:00:00-04:00 5 | --- 6 | 7 | Gets the number of days in the given `month` of the specified `year`. 8 | 9 | - Use the `new Date()` constructor to create a date from the given `year` and `month`. 10 | - Set the days parameter to `0` to get the last day of the previous month, as months are zero-indexed. 11 | - Use `Date.prototype.getDate()` to return the number of days in the given `month`. 12 | 13 | ```js 14 | const daysInMonth = (year, month) => new Date(year, month, 0).getDate(); 15 | ``` 16 | 17 | ```js 18 | daysInMonth(2020, 12)); // 31 19 | daysInMonth(2024, 2)); // 29 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/deepFlatten.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: deepFlatten 3 | tags: array,recursion,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Deep flattens an array. 9 | 10 | - Use recursion. 11 | - Use `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. 12 | - Recursively flatten each element that is an array. 13 | 14 | ```js 15 | const deepFlatten = arr => 16 | [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); 17 | ``` 18 | 19 | ```js 20 | deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/defaults.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: defaults 3 | tags: object,intermediate 4 | firstSeen: 2018-01-19T13:51:05+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Assigns default values for all properties in an object that are `undefined`. 9 | 10 | - Use `Object.assign()` to create a new empty object and copy the original one to maintain key order. 11 | - Use `Array.prototype.reverse()` and the spread operator (`...`) to combine the default values from left to right. 12 | - Finally, use `obj` again to overwrite properties that originally had a value. 13 | 14 | ```js 15 | const defaults = (obj, ...defs) => 16 | Object.assign({}, obj, ...defs.reverse(), obj); 17 | ``` 18 | 19 | ```js 20 | defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 } 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/degreesToRads.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: degreesToRads 3 | tags: math,beginner 4 | firstSeen: 2018-02-14T12:24:50+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Converts an angle from degrees to radians. 9 | 10 | - Use `Math.PI` and the degree to radian formula to convert the angle from degrees to radians. 11 | 12 | ```js 13 | const degreesToRads = deg => (deg * Math.PI) / 180.0; 14 | ``` 15 | 16 | ```js 17 | degreesToRads(90.0); // ~1.5708 18 | ``` -------------------------------------------------------------------------------- /snippets/delay.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: delay 3 | tags: function,intermediate 4 | firstSeen: 2018-01-24T14:32:20+02:00 5 | lastUpdated: 2020-10-19T18:51:03+03:00 6 | --- 7 | 8 | Invokes the provided function after `ms` milliseconds. 9 | 10 | - Use `setTimeout()` to delay execution of `fn`. 11 | - Use the spread (`...`) operator to supply the function with an arbitrary number of arguments. 12 | 13 | ```js 14 | const delay = (fn, ms, ...args) => setTimeout(fn, ms, ...args); 15 | ``` 16 | 17 | ```js 18 | delay( 19 | function(text) { 20 | console.log(text); 21 | }, 22 | 1000, 23 | 'later' 24 | ); // Logs 'later' after one second. 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/detectDeviceType.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: detectDeviceType 3 | tags: browser,regexp,intermediate 4 | firstSeen: 2017-12-24T09:39:23+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Detects whether the page is being viewed on a mobile device or a desktop. 9 | 10 | - Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop. 11 | 12 | ```js 13 | const detectDeviceType = () => 14 | /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( 15 | navigator.userAgent 16 | ) 17 | ? 'Mobile' 18 | : 'Desktop'; 19 | ``` 20 | 21 | ```js 22 | detectDeviceType(); // 'Mobile' or 'Desktop' 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/detectLanguage.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: detectLanguage 3 | tags: browser,intermediate 4 | firstSeen: 2020-10-05T18:03:26+03:00 5 | lastUpdated: 2020-10-06T18:47:16+03:00 6 | --- 7 | 8 | Detects the preferred language of the current user. 9 | 10 | - Use `NavigationLanguage.language` or the first `NavigationLanguage.languages` if available, otherwise return `defaultLang`. 11 | - Omit the second argument, `defaultLang`, to use `'en-US'` as the default language code. 12 | 13 | ```js 14 | const detectLanguage = (defaultLang = 'en-US') => 15 | navigator.language || 16 | (Array.isArray(navigator.languages) && navigator.languages[0]) || 17 | defaultLang; 18 | ``` 19 | 20 | ```js 21 | detectLanguage(); // 'nl-NL' 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/difference.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: difference 3 | tags: array,beginner 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-10-19T18:51:03+03:00 6 | --- 7 | 8 | Calculates the difference between two arrays, without filtering duplicate values. 9 | 10 | - Create a `Set` from `b` to get the unique values in `b`. 11 | - Use `Array.prototype.filter()` on `a` to only keep values not contained in `b`, using `Set.prototype.has()`. 12 | 13 | ```js 14 | const difference = (a, b) => { 15 | const s = new Set(b); 16 | return a.filter(x => !s.has(x)); 17 | }; 18 | ``` 19 | 20 | ```js 21 | difference([1, 2, 3, 3], [1, 2, 4]); // [3, 3] 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/digitize.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: digitize 3 | tags: math,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-18T14:58:09+03:00 6 | --- 7 | 8 | Converts a number to an array of digits, removing its sign if necessary. 9 | 10 | - Use `Math.abs()` to strip the number's sign. 11 | - Convert the number to a string, using the spread operator (`...`) to build an array. 12 | - Use `Array.prototype.map()` and `parseInt()` to transform each value to an integer. 13 | 14 | ```js 15 | const digitize = n => [...`${Math.abs(n)}`].map(i => parseInt(i)); 16 | ``` 17 | 18 | ```js 19 | digitize(123); // [1, 2, 3] 20 | digitize(-123); // [1, 2, 3] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/distance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: distance 3 | tags: math,algorithm,beginner 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-12-28T13:49:24+02:00 6 | --- 7 | 8 | Calculates the distance between two points. 9 | 10 | - Use `Math.hypot()` to calculate the Euclidean distance between two points. 11 | 12 | ```js 13 | const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); 14 | ``` 15 | 16 | ```js 17 | distance(1, 1, 2, 3); // ~2.2361 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/divmod.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: divmod 3 | tags: math,beginner 4 | firstSeen: 2020-10-07T23:59:13+03:00 5 | lastUpdated: 2020-10-07T23:59:13+03:00 6 | --- 7 | 8 | Returns an array consisting of the quotient and remainder of the given numbers. 9 | 10 | - Use `Math.floor()` to get the quotient of the division `x / y`. 11 | - Use the modulo operator (`%`) to get the remainder of the division `x / y`. 12 | 13 | ```js 14 | const divmod = (x, y) => [Math.floor(x / y), x % y]; 15 | ``` 16 | 17 | ```js 18 | divmod(8, 3); // [2, 2] 19 | divmod(3, 8); // [0, 3] 20 | divmod(5, 5); // [1, 0] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/drop.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: drop 3 | tags: array,beginner 4 | firstSeen: 2018-01-26T12:23:18+02:00 5 | lastUpdated: 2020-11-01T20:50:57+02:00 6 | --- 7 | 8 | Creates a new array with `n` elements removed from the left. 9 | 10 | - Use `Array.prototype.slice()` to remove the specified number of elements from the left. 11 | - Omit the last argument, `n`, to use a default value of `1`. 12 | 13 | ```js 14 | const drop = (arr, n = 1) => arr.slice(n); 15 | ``` 16 | 17 | ```js 18 | drop([1, 2, 3]); // [2, 3] 19 | drop([1, 2, 3], 2); // [3] 20 | drop([1, 2, 3], 42); // [] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/dropRight.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: dropRight 3 | tags: array,beginner 4 | firstSeen: 2017-12-19T12:06:47+02:00 5 | lastUpdated: 2020-11-01T20:50:57+02:00 6 | --- 7 | 8 | Creates a new array with `n` elements removed from the right. 9 | 10 | - Use `Array.prototype.slice()` to remove the specified number of elements from the right. 11 | - Omit the last argument, `n`, to use a default value of `1`. 12 | 13 | ```js 14 | const dropRight = (arr, n = 1) => arr.slice(0, -n); 15 | ``` 16 | 17 | ```js 18 | dropRight([1, 2, 3]); // [1, 2] 19 | dropRight([1, 2, 3], 2); // [1] 20 | dropRight([1, 2, 3], 42); // [] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/dropRightWhile.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: dropRightWhile 3 | tags: array,intermediate 4 | firstSeen: 2018-01-26T12:23:18+02:00 5 | lastUpdated: 2020-10-19T18:51:03+03:00 6 | --- 7 | 8 | Removes elements from the end of an array until the passed function returns `true`. 9 | Returns the remaining elements in the array. 10 | 11 | - Loop through the array, using `Array.prototype.slice()` to drop the last element of the array until the value returned from `func` is `true`. 12 | - Return the remaining elements. 13 | 14 | ```js 15 | const dropRightWhile = (arr, func) => { 16 | let rightIndex = arr.length; 17 | while (rightIndex-- && !func(arr[rightIndex])); 18 | return arr.slice(0, rightIndex + 1); 19 | }; 20 | ``` 21 | 22 | ```js 23 | dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2] 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/dropWhile.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: dropWhile 3 | tags: array,intermediate 4 | firstSeen: 2018-01-26T12:23:18+02:00 5 | lastUpdated: 2020-10-19T18:51:03+03:00 6 | --- 7 | 8 | Removes elements in an array until the passed function returns `true`. 9 | Returns the remaining elements in the array. 10 | 11 | - Loop through the array, using `Array.prototype.slice()` to drop the first element of the array until the value returned from `func` is `true`. 12 | - Return the remaining elements. 13 | 14 | ```js 15 | const dropWhile = (arr, func) => { 16 | while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); 17 | return arr; 18 | }; 19 | ``` 20 | 21 | ```js 22 | dropWhile([1, 2, 3, 4], n => n >= 3); // [3, 4] 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/either.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: either 3 | tags: function,logic,beginner 4 | firstSeen: 2020-05-13T11:35:46+03:00 5 | lastUpdated: 2020-10-19T18:51:03+03:00 6 | --- 7 | 8 | Checks if at least one function returns `true` for a given set of arguments. 9 | 10 | - Use the logical or (`||`) operator on the result of calling the two functions with the supplied `args`. 11 | 12 | ```js 13 | const either = (f, g) => (...args) => f(...args) || g(...args); 14 | ``` 15 | 16 | ```js 17 | const isEven = num => num % 2 === 0; 18 | const isPositive = num => num > 0; 19 | const isPositiveOrEven = either(isPositive, isEven); 20 | isPositiveOrEven(4); // true 21 | isPositiveOrEven(3); // true 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/elementContains.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: elementContains 3 | tags: browser,intermediate 4 | firstSeen: 2018-06-19T20:57:58+03:00 5 | lastUpdated: 2020-11-03T22:11:18+02:00 6 | --- 7 | 8 | Checks if the `parent` element contains the `child` element. 9 | 10 | - Check that `parent` is not the same element as `child`. 11 | - Use `Node.contains()` to check if the `parent` element contains the `child` element. 12 | 13 | ```js 14 | const elementContains = (parent, child) => 15 | parent !== child && parent.contains(child); 16 | ``` 17 | 18 | ```js 19 | elementContains( 20 | document.querySelector('head'), 21 | document.querySelector('title') 22 | ); 23 | // true 24 | elementContains(document.querySelector('body'), document.querySelector('body')); 25 | // false 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/elementIsFocused.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: elementIsFocused 3 | tags: browser,beginner 4 | firstSeen: 2020-08-07T15:21:27+03:00 5 | lastUpdated: 2020-10-19T18:51:03+03:00 6 | --- 7 | 8 | Checks if the given element is focused. 9 | 10 | - Use `Document.activeElement` to determine if the given element is focused. 11 | 12 | ```js 13 | const elementIsFocused = el => (el === document.activeElement); 14 | ``` 15 | 16 | ```js 17 | elementIsFocused(el); // true if the element is focused 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/escapeRegExp.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: escapeRegExp 3 | tags: string,regexp,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Escapes a string to use in a regular expression. 9 | 10 | - Use `String.prototype.replace()` to escape special characters. 11 | 12 | ```js 13 | const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); 14 | ``` 15 | 16 | ```js 17 | escapeRegExp('(test)'); // \\(test\\) 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/euclideanDistance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: euclideanDistance 3 | tags: math,algorithm,intermediate 4 | firstSeen: 2020-12-28T13:41:19+02:00 5 | lastUpdated: 2020-12-28T13:41:19+02:00 6 | --- 7 | 8 | Calculates the distance between two points in any number of dimensions. 9 | 10 | - Use `Object.keys()` and `Array.prototype.map()` to map each coordinate to its difference between the two points. 11 | - Use `Math.hypot()` to calculate the Euclidean distance between the two points. 12 | 13 | ```js 14 | const euclideanDistance = (a, b) => 15 | Math.hypot(...Object.keys(a).map(k => b[k] - a[k])); 16 | ``` 17 | 18 | ```js 19 | euclideanDistance([1, 1], [2, 3]); // ~2.2361 20 | euclideanDistance([1, 1, 1], [2, 3, 2]); // ~2.4495 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/everyNth.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: everyNth 3 | tags: array,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-19T18:51:03+03:00 6 | --- 7 | 8 | Returns every `nth` element in an array. 9 | 10 | - Use `Array.prototype.filter()` to create a new array that contains every `nth` element of a given array. 11 | 12 | ```js 13 | const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); 14 | ``` 15 | 16 | ```js 17 | everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/expandTabs.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: expandTabs 3 | tags: string,regexp,beginner 4 | firstSeen: 2020-06-01T17:05:39+03:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Convert tabs to spaces, where each tab corresponds to `count` spaces. 9 | 10 | - Use `String.prototype.replace()` with a regular expression and `String.prototype.repeat()` to replace each tab character with `count` spaces. 11 | 12 | ```js 13 | const expandTabs = (str, count) => str.replace(/\t/g, ' '.repeat(count)); 14 | ``` 15 | 16 | ```js 17 | expandTabs('\t\tlorem', 3); // ' lorem' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/factorial.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: factorial 3 | tags: math,algorithm,recursion,beginner 4 | firstSeen: 2017-12-07T14:41:33+02:00 5 | lastUpdated: 2020-12-28T13:49:24+02:00 6 | --- 7 | 8 | Calculates the factorial of a number. 9 | 10 | - Use recursion. 11 | - If `n` is less than or equal to `1`, return `1`. 12 | - Otherwise, return the product of `n` and the factorial of `n - 1`. 13 | - Throw a `TypeError` if `n` is a negative number. 14 | 15 | ```js 16 | const factorial = n => 17 | n < 0 18 | ? (() => { 19 | throw new TypeError('Negative numbers are not allowed!'); 20 | })() 21 | : n <= 1 22 | ? 1 23 | : n * factorial(n - 1); 24 | ``` 25 | 26 | ```js 27 | factorial(6); // 720 28 | ``` 29 | -------------------------------------------------------------------------------- /snippets/fahrenheitToCelsius.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: fahrenheitToCelsius 3 | tags: math,beginner 4 | unlisted: true 5 | firstSeen: 2020-04-16T11:00:06+03:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Converts Fahrenheit to Celsius. 10 | 11 | - Follow the conversion formula `C = (F - 32) * 5/9`. 12 | 13 | ```js 14 | const fahrenheitToCelsius = degrees => (degrees - 32) * 5 / 9; 15 | ``` 16 | 17 | ```js 18 | fahrenheitToCelsius(32); // 0 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/fibonacci.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: fibonacci 3 | tags: math,algorithm,intermediate 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-12-28T13:49:24+02:00 6 | --- 7 | 8 | Generates an array, containing the Fibonacci sequence, up until the nth term. 9 | 10 | - Use `Array.from()` to create an empty array of the specific length, initializing the first two values (`0` and `1`). 11 | - Use `Array.prototype.reduce()` and `Array.prototype.concat()` to add values into the array, using the sum of the last two values, except for the first two. 12 | 13 | ```js 14 | const fibonacci = n => 15 | Array.from({ length: n }).reduce( 16 | (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), 17 | [] 18 | ); 19 | ``` 20 | 21 | ```js 22 | fibonacci(6); // [0, 1, 1, 2, 3, 5] 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/filterNonUnique.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: filterNonUnique 3 | tags: array,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-11-02T19:40:45+02:00 6 | --- 7 | 8 | Creates an array with the non-unique values filtered out. 9 | 10 | - Use `new Set()` and the spread operator (`...`) to create an array of the unique values in `arr`. 11 | - Use `Array.prototype.filter()` to create an array containing only the unique values. 12 | 13 | ```js 14 | const filterNonUnique = arr => 15 | [...new Set(arr)].filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); 16 | ``` 17 | 18 | ```js 19 | filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5] 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/filterUnique.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: filterUnique 3 | tags: array,beginner 4 | firstSeen: 2020-11-02T19:41:00+02:00 5 | lastUpdated: 2020-11-02T19:41:00+02:00 6 | --- 7 | 8 | Creates an array with the unique values filtered out. 9 | 10 | - Use `new Set()` and the spread operator (`...`) to create an array of the unique values in `arr`. 11 | - Use `Array.prototype.filter()` to create an array containing only the non-unique values. 12 | 13 | ```js 14 | const filterUnique = arr => 15 | [...new Set(arr)].filter(i => arr.indexOf(i) !== arr.lastIndexOf(i)); 16 | ``` 17 | 18 | ```js 19 | filterUnique([1, 2, 2, 3, 4, 4, 5]); // [2, 4] 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/findClosestAnchor.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: findClosestAnchor 3 | tags: browser,intermediate 4 | firstSeen: 2021-04-22T08:45:39+03:00 5 | lastUpdated: 2021-04-22T08:45:39+03:00 6 | --- 7 | 8 | Finds the anchor node closest to the given `node`, if any. 9 | 10 | - Use a `for` loop and `Node.parentNode` to traverse the node tree upwards from the given `node`. 11 | - Use `Node.nodeName` and `String.prototype.toLowerCase()` to check if any given node is an anchor (`'a'`). 12 | - If no matching node is found, return `null`. 13 | 14 | ```js 15 | const findClosestAnchor = node => { 16 | for (let n = node; n.parentNode; n = n.parentNode) 17 | if (n.nodeName.toLowerCase() === 'a') return n; 18 | return null; 19 | }; 20 | ``` 21 | 22 | ```js 23 | findClosestAnchor(document.querySelector('a > span')); // a 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/findKeys.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: findKeys 3 | tags: object,beginner 4 | firstSeen: 2020-10-25T09:59:13+02:00 5 | lastUpdated: 2020-11-15T14:43:44+02:00 6 | --- 7 | 8 | Finds all the keys in the provided object that match the given value. 9 | 10 | - Use `Object.keys(obj)` to get all the properties of the object. 11 | - Use `Array.prototype.filter()` to test each key-value pair and return all keys that are equal to the given value. 12 | 13 | 14 | ```js 15 | const findKeys = (obj, val) => 16 | Object.keys(obj).filter(key => obj[key] === val); 17 | ``` 18 | 19 | ```js 20 | const ages = { 21 | Leo: 20, 22 | Zoey: 21, 23 | Jane: 20, 24 | }; 25 | findKeys(ages, 20); // [ 'Leo', 'Jane' ] 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/findLast.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: findLast 3 | tags: array,beginner 4 | firstSeen: 2018-01-11T13:51:58+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Finds the last element for which the provided function returns a truthy value. 9 | 10 | - Use `Array.prototype.filter()` to remove elements for which `fn` returns falsy values. 11 | - Use `Array.prototype.pop()` to get the last element in the filtered array. 12 | 13 | ```js 14 | const findLast = (arr, fn) => arr.filter(fn).pop(); 15 | ``` 16 | 17 | ```js 18 | findLast([1, 2, 3, 4], n => n % 2 === 1); // 3 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/flip.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: flip 3 | tags: function,intermediate 4 | firstSeen: 2017-12-22T02:42:15+02:00 5 | lastUpdated: 2021-06-13T13:50:25+03:00 6 | --- 7 | 8 | Takes a function as an argument, then makes the first argument the last. 9 | 10 | - Use argument destructuring and a closure with variadic arguments. 11 | - Splice the first argument, using the spread operator (`...`), to make it the last before applying the rest. 12 | 13 | ```js 14 | const flip = fn => (first, ...rest) => fn(...rest, first); 15 | ``` 16 | 17 | ```js 18 | let a = { name: 'John Smith' }; 19 | let b = {}; 20 | const mergeFrom = flip(Object.assign); 21 | let mergePerson = mergeFrom.bind(null, a); 22 | mergePerson(b); // == b 23 | b = {}; 24 | Object.assign(b, a); // == b 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/forEachRight.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: forEachRight 3 | tags: array,intermediate 4 | firstSeen: 2018-01-09T01:38:50+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Executes a provided function once for each array element, starting from the array's last element. 9 | 10 | - Use `Array.prototype.slice()` to clone the given array and `Array.prototype.reverse()` to reverse it. 11 | - Use `Array.prototype.forEach()` to iterate over the reversed array. 12 | 13 | ```js 14 | const forEachRight = (arr, callback) => 15 | arr 16 | .slice() 17 | .reverse() 18 | .forEach(callback); 19 | ``` 20 | 21 | ```js 22 | forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1' 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/forOwn.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: forOwn 3 | tags: object,intermediate 4 | firstSeen: 2018-01-18T16:45:56+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Iterates over all own properties of an object, running a callback for each one. 9 | 10 | - Use `Object.keys(obj)` to get all the properties of the object. 11 | - Use `Array.prototype.forEach()` to run the provided function for each key-value pair. 12 | - The callback receives three arguments - the value, the key and the object. 13 | 14 | ```js 15 | const forOwn = (obj, fn) => 16 | Object.keys(obj).forEach(key => fn(obj[key], key, obj)); 17 | ``` 18 | 19 | ```js 20 | forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/forOwnRight.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: forOwnRight 3 | tags: object,intermediate 4 | firstSeen: 2018-01-18T16:45:56+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Iterates over all own properties of an object in reverse, running a callback for each one. 9 | 10 | - Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order. 11 | - Use `Array.prototype.forEach()` to run the provided function for each key-value pair. 12 | - The callback receives three arguments - the value, the key and the object. 13 | 14 | ```js 15 | const forOwnRight = (obj, fn) => 16 | Object.keys(obj) 17 | .reverse() 18 | .forEach(key => fn(obj[key], key, obj)); 19 | ``` 20 | 21 | ```js 22 | forOwnRight({ foo: 'bar', a: 1 }, v => console.log(v)); // 1, 'bar' 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/formToObject.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: formToObject 3 | tags: browser,object,intermediate 4 | firstSeen: 2019-03-13T14:50:06+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Encodes a set of form elements as an `object`. 9 | 10 | - Use the `FormData` constructor to convert the HTML `form` to `FormData` and `Array.from()` to convert to an array. 11 | - Collect the object from the array using `Array.prototype.reduce()`. 12 | 13 | ```js 14 | const formToObject = form => 15 | Array.from(new FormData(form)).reduce( 16 | (acc, [key, value]) => ({ 17 | ...acc, 18 | [key]: value 19 | }), 20 | {} 21 | ); 22 | ``` 23 | 24 | ```js 25 | formToObject(document.querySelector('#form')); 26 | // { email: 'test@email.com', name: 'Test Name' } 27 | ``` 28 | -------------------------------------------------------------------------------- /snippets/formatNumber.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: formatNumber 3 | tags: string,math,beginner 4 | firstSeen: 2020-07-30T11:38:51+03:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Formats a number using the local number format order. 9 | 10 | - Use `Number.prototype.toLocaleString()` to convert a number to using the local number format separators. 11 | 12 | ```js 13 | const formatNumber = num => num.toLocaleString(); 14 | ``` 15 | 16 | ```js 17 | formatNumber(123456); // '123,456' in `en-US` 18 | formatNumber(15675436903); // '15.675.436.903' in `de-DE` 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/frequencies.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: frequencies 3 | tags: array,object,intermediate 4 | firstSeen: 2020-01-03T15:32:35+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Creates an object with the unique values of an array as keys and their frequencies as the values. 9 | 10 | - Use `Array.prototype.reduce()` to map unique values to an object's keys, adding to existing keys every time the same value is encountered. 11 | 12 | ```js 13 | const frequencies = arr => 14 | arr.reduce((a, v) => { 15 | a[v] = a[v] ? a[v] + 1 : 1; 16 | return a; 17 | }, {}); 18 | ``` 19 | 20 | ```js 21 | frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']); // { a: 4, b: 2, c: 1 } 22 | frequencies([...'ball']); // { b: 1, a: 1, l: 2 } 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/fromTimestamp.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: fromTimestamp 3 | tags: date,beginner 4 | firstSeen: 2020-10-15T21:57:17+03:00 5 | lastUpdated: 2020-10-15T21:57:17+03:00 6 | --- 7 | 8 | Creates a `Date` object from a Unix timestamp. 9 | 10 | - Convert the timestamp to milliseconds by multiplying with `1000`. 11 | - Use `new Date()` to create a new `Date` object. 12 | 13 | ```js 14 | const fromTimestamp = timestamp => new Date(timestamp * 1000); 15 | ``` 16 | 17 | ```js 18 | fromTimestamp(1602162242); // 2020-10-08T13:04:02.000Z 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/frozenSet.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: frozenSet 3 | tags: array,intermediate 4 | firstSeen: 2020-10-11T11:52:48+03:00 5 | lastUpdated: 2020-10-11T11:52:48+03:00 6 | --- 7 | 8 | Creates a frozen `Set` object. 9 | 10 | - Use the `new Set()` constructor to create a new `Set` object from `iterable`. 11 | - Set the `add`, `delete` and `clear` methods of the newly created object to `undefined`, so that they cannot be used, practically freezing the object. 12 | 13 | ```js 14 | const frozenSet = iterable => { 15 | const s = new Set(iterable); 16 | s.add = undefined; 17 | s.delete = undefined; 18 | s.clear = undefined; 19 | return s; 20 | }; 21 | ``` 22 | 23 | ```js 24 | frozenSet([1, 2, 3, 1, 2]); 25 | // Set { 1, 2, 3, add: undefined, delete: undefined, clear: undefined } 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/functionName.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: functionName 3 | tags: function,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Logs the name of a function. 9 | 10 | - Use `console.debug()` and the `name` property of the passed function to log the function's name to the `debug` channel of the console. 11 | - Return the given function `fn`. 12 | 13 | ```js 14 | const functionName = fn => (console.debug(fn.name), fn); 15 | ``` 16 | 17 | ```js 18 | let m = functionName(Math.max)(5, 6); 19 | // max (logged in debug channel of console) 20 | // m = 6 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/gcd.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: gcd 3 | tags: math,algorithm,recursion,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-12-29T12:36:50+02:00 6 | --- 7 | 8 | Calculates the greatest common divisor between two or more numbers/arrays. 9 | 10 | - The inner `_gcd` function uses recursion. 11 | - Base case is when `y` equals `0`. In this case, return `x`. 12 | - Otherwise, return the GCD of `y` and the remainder of the division `x/y`. 13 | 14 | ```js 15 | const gcd = (...arr) => { 16 | const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); 17 | return [...arr].reduce((a, b) => _gcd(a, b)); 18 | }; 19 | ``` 20 | 21 | ```js 22 | gcd(8, 36); // 4 23 | gcd(...[12, 8, 32]); // 4 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/generateItems.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: generateItems 3 | tags: array,function,intermediate 4 | firstSeen: 2020-10-09T20:41:21+03:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Generates an array with the given amount of items, using the given function. 9 | 10 | - Use `Array.from()` to create an empty array of the specific length, calling `fn` with the index of each newly created element. 11 | - The callback takes one argument - the index of each element. 12 | 13 | ```js 14 | const generateItems = (n, fn) => Array.from({ length: n }, (_, i) => fn(i)); 15 | ``` 16 | 17 | ```js 18 | generateItems(10, Math.random); 19 | // [0.21, 0.08, 0.40, 0.96, 0.96, 0.24, 0.19, 0.96, 0.42, 0.70] 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/generatorToArray.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: generatorToArray 3 | tags: function,array,generator,beginner 4 | firstSeen: 2020-12-31T13:22:18+02:00 5 | lastUpdated: 2020-12-31T13:22:18+02:00 6 | --- 7 | 8 | Converts the output of a generator function to an array. 9 | 10 | - Use the spread operator (`...`) to convert the output of the generator function to an array. 11 | 12 | ```js 13 | const generatorToArray = gen => [...gen]; 14 | ``` 15 | 16 | ```js 17 | const s = new Set([1, 2, 1, 3, 1, 4]); 18 | generatorToArray(s.entries()); // [[ 1, 1 ], [ 2, 2 ], [ 3, 3 ], [ 4, 4 ]] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/getAncestors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getAncestors 3 | tags: browser,beginner 4 | firstSeen: 2020-10-15T09:28:34+03:00 5 | lastUpdated: 2021-01-05T22:45:34+02:00 6 | --- 7 | 8 | Returns all the ancestors of an element from the document root to the given element. 9 | 10 | - Use `Node.parentNode` and a `while` loop to move up the ancestor tree of the element. 11 | - Use `Array.prototype.unshift()` to add each new ancestor to the start of the array. 12 | 13 | ```js 14 | const getAncestors = el => { 15 | let ancestors = []; 16 | while (el) { 17 | ancestors.unshift(el); 18 | el = el.parentNode; 19 | } 20 | return ancestors; 21 | }; 22 | ``` 23 | 24 | ```js 25 | getAncestors(document.querySelector('nav')); 26 | // [document, html, body, header, nav] 27 | ``` 28 | -------------------------------------------------------------------------------- /snippets/getBaseURL.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getBaseURL 3 | tags: string,browser,regexp,beginner 4 | firstSeen: 2020-05-03T12:20:54+03:00 5 | lastUpdated: 2021-01-03T20:32:13+02:00 6 | --- 7 | 8 | Gets the current URL without any parameters or fragment identifiers. 9 | 10 | - Use `String.prototype.replace()` with an appropriate regular expression to remove everything after either `'?'` or `'#'`, if found. 11 | 12 | ```js 13 | const getBaseURL = url => url.replace(/[?#].*$/, ''); 14 | ``` 15 | 16 | ```js 17 | getBaseURL('http://url.com/page?name=Adam&surname=Smith'); 18 | // 'http://url.com/page' 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/getColonTimeFromDate.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getColonTimeFromDate 3 | tags: date,string,beginner 4 | firstSeen: 2018-01-13T17:14:48+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Returns a string of the form `HH:MM:SS` from a `Date` object. 9 | 10 | - Use `Date.prototype.toTimeString()` and `String.prototype.slice()` to get the `HH:MM:SS` part of a given `Date` object. 11 | 12 | ```js 13 | const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); 14 | ``` 15 | 16 | ```js 17 | getColonTimeFromDate(new Date()); // '08:38:00' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/getDaysDiffBetweenDates.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getDaysDiffBetweenDates 3 | tags: date,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2021-04-24T12:42:47+03:00 6 | --- 7 | 8 | Calculates the difference (in days) between two dates. 9 | 10 | - Subtract the two `Date` objects and divide by the number of milliseconds in a day to get the difference (in days) between them. 11 | 12 | ```js 13 | const getDaysDiffBetweenDates = (dateInitial, dateFinal) => 14 | (dateFinal - dateInitial) / (1000 * 3600 * 24); 15 | ``` 16 | 17 | ```js 18 | getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/getHoursDiffBetweenDates.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getHoursDiffBetweenDates 3 | tags: date,beginner 4 | firstSeen: 2021-04-24T12:56:21+03:00 5 | lastUpdated: 2021-04-24T12:56:21+03:00 6 | --- 7 | 8 | Calculates the difference (in hours) between two dates. 9 | 10 | - Subtract the two `Date` objects and divide by the number of milliseconds in an hour to get the difference (in hours) between them. 11 | 12 | ```js 13 | const getHoursDiffBetweenDates = (dateInitial, dateFinal) => 14 | (dateFinal - dateInitial) / (1000 * 3600); 15 | ``` 16 | 17 | ```js 18 | getHoursDiffBetweenDates( 19 | new Date('2021-04-24 10:25:00'), 20 | new Date('2021-04-25 10:25:00') 21 | ); // 24 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/getMinutesDiffBetweenDates.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getMinutesDiffBetweenDates 3 | tags: date,beginner 4 | firstSeen: 2021-04-24T12:48:49+03:00 5 | lastUpdated: 2021-04-24T12:48:49+03:00 6 | --- 7 | 8 | Calculates the difference (in minutes) between two dates. 9 | 10 | - Subtract the two `Date` objects and divide by the number of milliseconds in a minute to get the difference (in minutes) between them. 11 | 12 | ```js 13 | const getMinutesDiffBetweenDates = (dateInitial, dateFinal) => 14 | (dateFinal - dateInitial) / (1000 * 60); 15 | ``` 16 | 17 | ```js 18 | getMinutesDiffBetweenDates( 19 | new Date('2021-04-24 01:00:15'), 20 | new Date('2021-04-24 02:00:15') 21 | ); // 60 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/getMonthsDiffBetweenDates.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getMonthsDiffBetweenDates 3 | tags: date,intermediate 4 | firstSeen: 2020-08-07T15:15:26+03:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Calculates the difference (in months) between two dates. 9 | 10 | - Use `Date.prototype.getFullYear()` and `Date.prototype.getMonth()` to calculate the difference (in months) between two `Date` objects. 11 | 12 | ```js 13 | const getMonthsDiffBetweenDates = (dateInitial, dateFinal) => 14 | Math.max( 15 | (dateFinal.getFullYear() - dateInitial.getFullYear()) * 12 + 16 | dateFinal.getMonth() - 17 | dateInitial.getMonth(), 18 | 0 19 | ); 20 | ``` 21 | 22 | ```js 23 | getMonthsDiffBetweenDates(new Date('2017-12-13'), new Date('2018-04-29')); // 4 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/getProtocol.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getProtocol 3 | tags: browser,beginner 4 | firstSeen: 2020-10-07T01:40:53+03:00 5 | lastUpdated: 2020-10-20T11:46:23+03:00 6 | --- 7 | 8 | Gets the protocol being used on the current page. 9 | 10 | - Use `Window.location.protocol` to get the protocol (`http:` or `https:`) of the current page. 11 | 12 | ```js 13 | const getProtocol = () => window.location.protocol; 14 | ``` 15 | 16 | ```js 17 | getProtocol(); // 'https:' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/getScrollPosition.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getScrollPosition 3 | tags: browser,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Returns the scroll position of the current page. 9 | 10 | - Use `Window.pageXOffset` and `Window.pageYOffset` if they are defined, otherwise `Element.scrollLeft` and `Element.scrollTop`. 11 | - Omit the single argument, `el`, to use a default value of `window`. 12 | 13 | ```js 14 | const getScrollPosition = (el = window) => ({ 15 | x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, 16 | y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop 17 | }); 18 | ``` 19 | 20 | ```js 21 | getScrollPosition(); // {x: 0, y: 200} 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/getSecondsDiffBetweenDates.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getSecondsDiffBetweenDates 3 | tags: date,beginner 4 | firstSeen: 2021-04-24T12:39:48+03:00 5 | lastUpdated: 2021-04-24T12:39:48+03:00 6 | --- 7 | 8 | Calculates the difference (in seconds) between two dates. 9 | 10 | - Subtract the two `Date` objects and divide by the number of milliseconds in a second to get the difference (in seconds) between them. 11 | 12 | ```js 13 | const getSecondsDiffBetweenDates = (dateInitial, dateFinal) => 14 | (dateFinal - dateInitial) / 1000; 15 | ``` 16 | 17 | ```js 18 | getSecondsDiffBetweenDates( 19 | new Date('2020-12-24 00:00:15'), 20 | new Date('2020-12-24 00:00:17') 21 | ); // 2 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/getSelectedText.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getSelectedText 3 | tags: browser,beginner 4 | firstSeen: 2020-08-07T15:34:53+03:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Gets the currently selected text. 9 | 10 | - Use `Window.getSelection()` and `Selection.toString()` to get the currently selected text. 11 | 12 | ```js 13 | const getSelectedText = () => window.getSelection().toString(); 14 | ``` 15 | 16 | ```js 17 | getSelectedText(); // 'Lorem ipsum' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/getSiblings.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getSiblings 3 | tags: browser,intermediate 4 | firstSeen: 2020-08-07T15:31:48+03:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Returns an array containing all the siblings of the given element. 9 | 10 | - Use `Node.parentNode` and `Node.childNodes` to get a `NodeList` of all the elements contained in the element's parent. 11 | - Use the spread operator (`...`) and `Array.prototype.filter()` to convert to an array and remove the given element from it. 12 | 13 | ```js 14 | const getSiblings = el => 15 | [...el.parentNode.childNodes].filter(node => node !== el); 16 | ``` 17 | 18 | ```js 19 | getSiblings(document.querySelector('head')); // ['body'] 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/getStyle.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getStyle 3 | tags: browser,css,beginner 4 | firstSeen: 2017-12-29T00:08:17+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Retrieves the value of a CSS rule for the specified element. 9 | 10 | - Use `Window.getComputedStyle()` to get the value of the CSS rule for the specified element. 11 | 12 | ```js 13 | const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; 14 | ``` 15 | 16 | ```js 17 | getStyle(document.querySelector('p'), 'font-size'); // '16px' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/getTimestamp.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getTimestamp 3 | tags: date,beginner 4 | firstSeen: 2020-10-08T17:15:56+03:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Gets the Unix timestamp from a `Date` object. 9 | 10 | - Use `Date.prototype.getTime()` to get the timestamp in milliseconds and divide by `1000` to get the timestamp in seconds. 11 | - Use `Math.floor()` to appropriately round the resulting timestamp to an integer. 12 | - Omit the argument, `date`, to use the current date. 13 | 14 | ```js 15 | const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000); 16 | ``` 17 | 18 | ```js 19 | getTimestamp(); // 1602162242 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/getType.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getType 3 | tags: type,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Returns the native type of a value. 9 | 10 | - Return `'undefined'` or `'null'` if the value is `undefined` or `null`. 11 | - Otherwise, use `Object.prototype.constructor.name` to get the name of the constructor. 12 | 13 | ```js 14 | const getType = v => 15 | (v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name); 16 | ``` 17 | 18 | ```js 19 | getType(new Set([1, 2, 3])); // 'Set' 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/getVerticalOffset.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: getVerticalOffset 3 | tags: browser,beginner 4 | firstSeen: 2021-01-05T22:41:09+02:00 5 | lastUpdated: 2021-01-05T22:41:09+02:00 6 | --- 7 | 8 | Finds the distance from a given element to the top of the document. 9 | 10 | - Use a `while` loop and `HTMLElement.offsetParent` to move up the offset parents of the given element. 11 | - Add `HTMLElement.offsetTop` for each element and return the result. 12 | 13 | ```js 14 | const getVerticalOffset = el => { 15 | let offset = el.offsetTop, 16 | _el = el; 17 | while (_el.offsetParent) { 18 | _el = _el.offsetParent; 19 | offset += _el.offsetTop; 20 | } 21 | return offset; 22 | }; 23 | ``` 24 | 25 | ```js 26 | getVerticalOffset('.my-element'); // 120 27 | ``` 28 | -------------------------------------------------------------------------------- /snippets/hammingDistance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: hammingDistance 3 | tags: math,algorithm,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-12-28T13:49:24+02:00 6 | --- 7 | 8 | Calculates the Hamming distance between two values. 9 | 10 | - Use the XOR operator (`^`) to find the bit difference between the two numbers. 11 | - Convert to a binary string using `Number.prototype.toString(2)`. 12 | - Count and return the number of `1`s in the string, using `String.prototype.match(/1/g)`. 13 | 14 | ```js 15 | const hammingDistance = (num1, num2) => 16 | ((num1 ^ num2).toString(2).match(/1/g) || '').length; 17 | ``` 18 | 19 | ```js 20 | hammingDistance(2, 3); // 1 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/hasClass.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: hasClass 3 | tags: browser,css,beginner 4 | firstSeen: 2017-12-28T23:46:33+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Checks if the given element has the specified class. 9 | 10 | - Use `Element.classList` and `DOMTokenList.contains()` to check if the element has the specified class. 11 | 12 | ```js 13 | const hasClass = (el, className) => el.classList.contains(className); 14 | ``` 15 | 16 | ```js 17 | hasClass(document.querySelector('p.special'), 'special'); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/hasDuplicates.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: hasDuplicates 3 | tags: array,beginner 4 | firstSeen: 2020-10-22T20:23:09+03:00 5 | lastUpdated: 2020-10-22T20:23:09+03:00 6 | --- 7 | 8 | Checks if there are duplicate values in a flat array. 9 | 10 | - Use `Set()` to get the unique values in the array. 11 | - Use `Set.prototype.size` and `Array.prototype.length` to check if the count of the unique values is the same as elements in the original array. 12 | 13 | ```js 14 | const hasDuplicates = arr => new Set(arr).size !== arr.length; 15 | ``` 16 | 17 | ```js 18 | hasDuplicates([0, 1, 1, 2]); // true 19 | hasDuplicates([0, 1, 2, 3]); // false 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/hasMany.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: hasMany 3 | tags: array,beginner 4 | firstSeen: 2021-07-11T05:00:00-04:00 5 | --- 6 | 7 | Checks if an array has more than one value matching the given function. 8 | 9 | - Use `Array.prototype.filter()` in combination with `fn` to find all matching array elements. 10 | - Use `Array.prototype.length` to check if more than one element match `fn`. 11 | 12 | ```js 13 | const hasMany = (arr, fn) => arr.filter(fn).length > 1; 14 | ``` 15 | 16 | ```js 17 | hasMany([1, 3], x => x % 2); // true 18 | hasMany([1, 2], x => x % 2); // false 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/hasOne.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: hasOne 3 | tags: array,beginner 4 | firstSeen: 2021-07-04T05:00:00-04:00 5 | --- 6 | 7 | Checks if an array has only one value matching the given function. 8 | 9 | - Use `Array.prototype.filter()` in combination with `fn` to find all matching array elements. 10 | - Use `Array.prototype.length` to check if only one element matches `fn`. 11 | 12 | ```js 13 | const hasOne = (arr, fn) => arr.filter(fn).length === 1; 14 | ``` 15 | 16 | ```js 17 | hasOne([1, 2], x => x % 2); // true 18 | hasOne([1, 3], x => x % 2); // false 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/head.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: head 3 | tags: array,beginner 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-10-19T22:49:51+03:00 6 | --- 7 | 8 | Returns the head of an array. 9 | 10 | - Check if `arr` is truthy and has a `length` property. 11 | - Use `arr[0]` if possible to return the first element, otherwise return `undefined`. 12 | 13 | ```js 14 | const head = arr => (arr && arr.length ? arr[0] : undefined); 15 | ``` 16 | 17 | ```js 18 | head([1, 2, 3]); // 1 19 | head([]); // undefined 20 | head(null); // undefined 21 | head(undefined); // undefined 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/hide.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: hide 3 | tags: browser,css,beginner 4 | firstSeen: 2017-12-28T23:33:21+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Hides all the elements specified. 9 | 10 | - Use the spread operator (`...`) and `Array.prototype.forEach()` to apply `display: none` to each element specified. 11 | 12 | ```js 13 | const hide = (...el) => [...el].forEach(e => (e.style.display = 'none')); 14 | ``` 15 | 16 | ```js 17 | hide(...document.querySelectorAll('img')); // Hides all elements on the page 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/inRange.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: inRange 3 | tags: math,beginner 4 | firstSeen: 2017-12-20T18:33:58+02:00 5 | lastUpdated: 2020-11-01T20:50:57+02:00 6 | --- 7 | 8 | Checks if the given number falls within the given range. 9 | 10 | - Use arithmetic comparison to check if the given number is in the specified range. 11 | - If the second argument, `end`, is not specified, the range is considered to be from `0` to `start`. 12 | 13 | ```js 14 | const inRange = (n, start, end = null) => { 15 | if (end && start > end) [end, start] = [start, end]; 16 | return end == null ? n >= 0 && n < start : n >= start && n < end; 17 | }; 18 | ``` 19 | 20 | ```js 21 | inRange(3, 2, 5); // true 22 | inRange(3, 4); // true 23 | inRange(2, 3, 5); // false 24 | inRange(3, 2); // false 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/includesAll.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: includesAll 3 | tags: array,beginner 4 | firstSeen: 2019-11-04T21:37:16+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if all the elements in `values` are included in `arr`. 9 | 10 | - Use `Array.prototype.every()` and `Array.prototype.includes()` to check if all elements of `values` are included in `arr`. 11 | 12 | ```js 13 | const includesAll = (arr, values) => values.every(v => arr.includes(v)); 14 | ``` 15 | 16 | ```js 17 | includesAll([1, 2, 3, 4], [1, 4]); // true 18 | includesAll([1, 2, 3, 4], [1, 5]); // false 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/includesAny.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: includesAny 3 | tags: array,beginner 4 | firstSeen: 2019-11-03T23:49:17+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if at least one element of `values` is included in `arr`. 9 | 10 | - Use `Array.prototype.some()` and `Array.prototype.includes()` to check if at least one element of `values` is included in `arr`. 11 | 12 | ```js 13 | const includesAny = (arr, values) => values.some(v => arr.includes(v)); 14 | ``` 15 | 16 | ```js 17 | includesAny([1, 2, 3, 4], [2, 9]); // true 18 | includesAny([1, 2, 3, 4], [8, 9]); // false 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/indentString.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: indentString 3 | tags: string,beginner 4 | firstSeen: 2018-09-24T22:14:27+03:00 5 | lastUpdated: 2020-11-01T20:50:57+02:00 6 | --- 7 | 8 | Indents each line in the provided string. 9 | 10 | - Use `String.prototype.replace()` and a regular expression to add the character specified by `indent` `count` times at the start of each line. 11 | - Omit the third argument, `indent`, to use a default indentation character of `' '`. 12 | 13 | ```js 14 | const indentString = (str, count, indent = ' ') => 15 | str.replace(/^/gm, indent.repeat(count)); 16 | ``` 17 | 18 | ```js 19 | indentString('Lorem\nIpsum', 2); // ' Lorem\n Ipsum' 20 | indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum' 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/indexBy.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: indexBy 3 | tags: array,object,intermediate 4 | firstSeen: 2021-06-20T05:00:00-04:00 5 | --- 6 | 7 | Creates an object from an array, using a function to map each value to a key. 8 | 9 | - Use `Array.prototype.reduce()` to create an object from `arr`. 10 | - Apply `fn` to each value of `arr` to produce a key and add the key-value pair to the object. 11 | 12 | ```js 13 | const indexBy = (arr, fn) => 14 | arr.reduce((obj, v, i) => { 15 | obj[fn(v, i, arr)] = v; 16 | return obj; 17 | }, {}); 18 | ``` 19 | 20 | ```js 21 | indexBy([ 22 | { id: 10, name: 'apple' }, 23 | { id: 20, name: 'orange' } 24 | ], x => x.id); 25 | // { '10': { id: 10, name: 'apple' }, '20': { id: 20, name: 'orange' } } 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/indexOfAll.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: indexOfAll 3 | tags: array,intermediate 4 | firstSeen: 2018-01-06T12:07:56+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Finds all indexes of `val` in an array. 9 | If `val` never occurs, returns an empty array. 10 | 11 | - Use `Array.prototype.reduce()` to loop over elements and store indexes for matching elements. 12 | 13 | ```js 14 | const indexOfAll = (arr, val) => 15 | arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); 16 | ``` 17 | 18 | ```js 19 | indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0, 3] 20 | indexOfAll([1, 2, 3], 4); // [] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/indexOn.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: indexOn 3 | tags: array,object,intermediate 4 | firstSeen: 2021-06-27T05:00:00-04:00 5 | --- 6 | 7 | Creates an object from an array, using the specified key and excluding it from each value. 8 | 9 | - Use `Array.prototype.reduce()` to create an object from `arr`. 10 | - Use object destructuring to get the value of the given `key` and the associated `data` and add the key-value pair to the object. 11 | 12 | ```js 13 | const indexOn = (arr, key) => 14 | arr.reduce((obj, v) => { 15 | const { [key]: id, ...data } = v; 16 | obj[id] = data; 17 | return obj; 18 | }, {}); 19 | ``` 20 | 21 | ```js 22 | indexOn([ 23 | { id: 10, name: 'apple' }, 24 | { id: 20, name: 'orange' } 25 | ], 'id'); 26 | // { '10': { name: 'apple' }, '20': { name: 'orange' } } 27 | ``` 28 | -------------------------------------------------------------------------------- /snippets/initial.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: initial 3 | tags: array,beginner 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-11-03T21:46:13+02:00 6 | --- 7 | 8 | Returns all the elements of an array except the last one. 9 | 10 | - Use `Array.prototype.slice(0, -1)` to return all but the last element of the array. 11 | 12 | ```js 13 | const initial = arr => arr.slice(0, -1); 14 | ``` 15 | 16 | ```js 17 | initial([1, 2, 3]); // [1, 2] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/initialize2DArray.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: initialize2DArray 3 | tags: array,intermediate 4 | firstSeen: 2017-12-19T23:38:18+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Initializes a 2D array of given width and height and value. 9 | 10 | - Use `Array.from()` and `Array.prototype.map()` to generate `h` rows where each is a new array of size `w`. 11 | - Use `Array.prototype.fill()` to initialize all items with value `val`. 12 | - Omit the last argument, `val`, to use a default value of `null`. 13 | 14 | ```js 15 | const initialize2DArray = (w, h, val = null) => 16 | Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); 17 | ``` 18 | 19 | ```js 20 | initialize2DArray(2, 2, 0); // [[0, 0], [0, 0]] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/initializeArrayWithValues.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: initializeArrayWithValues 3 | tags: array,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Initializes and fills an array with the specified values. 9 | 10 | - Use `Array.from()` to create an array of the desired length, `Array.prototype.fill()` to fill it with the desired values. 11 | - Omit the last argument, `val`, to use a default value of `0`. 12 | 13 | ```js 14 | const initializeArrayWithValues = (n, val = 0) => 15 | Array.from({ length: n }).fill(val); 16 | ``` 17 | 18 | ```js 19 | initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2] 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/initializeNDArray.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: initializeNDArray 3 | tags: array,recursion,intermediate 4 | firstSeen: 2018-04-14T10:52:39+03:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Create a n-dimensional array with given value. 9 | 10 | - Use recursion. 11 | - Use `Array.from()`, `Array.prototype.map()` to generate rows where each is a new array initialized using `initializeNDArray()`. 12 | 13 | ```js 14 | const initializeNDArray = (val, ...args) => 15 | args.length === 0 16 | ? val 17 | : Array.from({ length: args[0] }).map(() => 18 | initializeNDArray(val, ...args.slice(1)) 19 | ); 20 | ``` 21 | 22 | ```js 23 | initializeNDArray(1, 3); // [1, 1, 1] 24 | initializeNDArray(5, 2, 2, 2); // [[[5, 5], [5, 5]], [[5, 5], [5, 5]]] 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/insertAfter.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: insertAfter 3 | tags: browser,beginner 4 | firstSeen: 2018-06-19T20:57:58+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Inserts an HTML string after the end of the specified element. 9 | 10 | - Use `Element.insertAdjacentHTML()` with a position of `'afterend'` to parse `htmlString` and insert it after the end of `el`. 11 | 12 | ```js 13 | const insertAfter = (el, htmlString) => 14 | el.insertAdjacentHTML('afterend', htmlString); 15 | ``` 16 | 17 | ```js 18 | insertAfter(document.getElementById('myId'), '

    after

    '); 19 | //
    ...

    after

    20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/insertAt.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: insertAt 3 | tags: array,intermediate 4 | firstSeen: 2020-05-22T09:07:35+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Mutates the original array to insert the given values after the specified index. 9 | 10 | - Use `Array.prototype.splice()` with an appropriate index and a delete count of `0`, spreading the given values to be inserted. 11 | 12 | ```js 13 | const insertAt = (arr, i, ...v) => { 14 | arr.splice(i + 1, 0, ...v); 15 | return arr; 16 | }; 17 | ``` 18 | 19 | ```js 20 | let myArray = [1, 2, 3, 4]; 21 | insertAt(myArray, 2, 5); // myArray = [1, 2, 3, 5, 4] 22 | 23 | let otherArray = [2, 10]; 24 | insertAt(otherArray, 0, 4, 6, 8); // otherArray = [2, 4, 6, 8, 10] 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/insertBefore.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: insertBefore 3 | tags: browser,beginner 4 | firstSeen: 2018-06-19T20:57:58+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Inserts an HTML string before the start of the specified element. 9 | 10 | - Use `Element.insertAdjacentHTML()` with a position of `'beforebegin'` to parse `htmlString` and insert it before the start of `el`. 11 | 12 | ```js 13 | const insertBefore = (el, htmlString) => 14 | el.insertAdjacentHTML('beforebegin', htmlString); 15 | ``` 16 | 17 | ```js 18 | insertBefore(document.getElementById('myId'), '

    before

    '); 19 | //

    before

    ...
    20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/intersection.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: intersection 3 | tags: array,intermediate 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Returns the elements that exist in both arrays, filtering duplicate values. 9 | 10 | - Create a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values contained in `b`. 11 | 12 | ```js 13 | const intersection = (a, b) => { 14 | const s = new Set(b); 15 | return [...new Set(a)].filter(x => s.has(x)); 16 | }; 17 | ``` 18 | 19 | ```js 20 | intersection([1, 2, 3], [4, 3, 2]); // [2, 3] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/intersectionWith.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: intersectionWith 3 | tags: array,intermediate 4 | firstSeen: 2018-01-24T12:53:18+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Returns the elements that exist in both arrays, using a provided comparator function. 9 | 10 | - Use `Array.prototype.filter()` and `Array.prototype.findIndex()` in combination with the provided comparator to determine intersecting values. 11 | 12 | ```js 13 | const intersectionWith = (a, b, comp) => 14 | a.filter(x => b.findIndex(y => comp(x, y)) !== -1); 15 | ``` 16 | 17 | ```js 18 | intersectionWith( 19 | [1, 1.2, 1.5, 3, 0], 20 | [1.9, 3, 0, 3.9], 21 | (a, b) => Math.round(a) === Math.round(b) 22 | ); // [1.5, 3, 0] 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/isAbsoluteURL.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isAbsoluteURL 3 | tags: string,browser,regexp,intermediate 4 | firstSeen: 2017-12-31T14:42:45+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given string is an absolute URL. 9 | 10 | - Use `RegExp.prototype.test()` to test if the string is an absolute URL. 11 | 12 | ```js 13 | const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); 14 | ``` 15 | 16 | ```js 17 | isAbsoluteURL('https://google.com'); // true 18 | isAbsoluteURL('ftp://www.myserver.net'); // true 19 | isAbsoluteURL('/foo/bar'); // false 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/isAfterDate.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isAfterDate 3 | tags: date,beginner 4 | firstSeen: 2018-09-29T13:58:38+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if a date is after another date. 9 | 10 | - Use the greater than operator (`>`) to check if the first date comes after the second one. 11 | 12 | ```js 13 | const isAfterDate = (dateA, dateB) => dateA > dateB; 14 | ``` 15 | 16 | ```js 17 | isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/isAlpha.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isAlpha 3 | tags: string,regexp,beginner 4 | firstSeen: 2020-12-31T14:01:42+02:00 5 | lastUpdated: 2020-12-31T14:01:42+02:00 6 | --- 7 | 8 | Checks if a string contains only alpha characters. 9 | 10 | - Use `RegExp.prototype.test()` to check if the given string matches against the alphabetic regexp pattern. 11 | 12 | ```js 13 | const isAlpha = str => /^[a-zA-Z]*$/.test(str); 14 | ``` 15 | 16 | ```js 17 | isAlpha('sampleInput'); // true 18 | isAlpha('this Will fail'); // false 19 | isAlpha('123'); // false 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/isAlphaNumeric.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isAlphaNumeric 3 | tags: string,regexp,beginner 4 | firstSeen: 2020-09-06T07:59:16+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if a string contains only alphanumeric characters. 9 | 10 | - Use `RegExp.prototype.test()` to check if the input string matches against the alphanumeric regexp pattern. 11 | 12 | ```js 13 | const isAlphaNumeric = str => /^[a-z0-9]+$/gi.test(str); 14 | ``` 15 | 16 | ```js 17 | isAlphaNumeric('hello123'); // true 18 | isAlphaNumeric('123'); // true 19 | isAlphaNumeric('hello 123'); // false (space character is not alphanumeric) 20 | isAlphaNumeric('#$hello'); // false 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/isArrayLike.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isArrayLike 3 | tags: type,array,intermediate 4 | firstSeen: 2017-12-31T14:53:01+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the provided argument is array-like (i.e. is iterable). 9 | 10 | - Check if the provided argument is not `null` and that its `Symbol.iterator` property is a function. 11 | 12 | ```js 13 | const isArrayLike = obj => 14 | obj != null && typeof obj[Symbol.iterator] === 'function'; 15 | ``` 16 | 17 | ```js 18 | isArrayLike([1, 2, 3]); // true 19 | isArrayLike(document.querySelectorAll('.className')); // true 20 | isArrayLike('abc'); // true 21 | isArrayLike(null); // false 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/isAsyncFunction.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isAsyncFunction 3 | tags: type,function,intermediate 4 | firstSeen: 2020-08-07T15:41:55+03:00 5 | lastUpdated: 2020-10-20T11:21:07+03:00 6 | --- 7 | 8 | Checks if the given argument is an `async` function. 9 | 10 | - Use `Object.prototype.toString()` and `Function.prototype.call()` and check if the result is `'[object AsyncFunction]'`. 11 | 12 | ```js 13 | const isAsyncFunction = val => 14 | Object.prototype.toString.call(val) === '[object AsyncFunction]'; 15 | ``` 16 | 17 | ```js 18 | isAsyncFunction(function() {}); // false 19 | isAsyncFunction(async function() {}); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/isBeforeDate.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isBeforeDate 3 | tags: date,beginner 4 | firstSeen: 2018-09-29T13:58:38+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if a date is before another date. 9 | 10 | - Use the less than operator (`<`) to check if the first date comes before the second one. 11 | 12 | ```js 13 | const isBeforeDate = (dateA, dateB) => dateA < dateB; 14 | ``` 15 | 16 | ```js 17 | isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/isBetweenDates.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isBetweenDates 3 | tags: date,beginner 4 | firstSeen: 2020-10-07T20:31:52+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if a date is between two other dates. 9 | 10 | - Use the greater than (`>`) and less than (`<`) operators to check if `date` is between `dateStart` and `dateEnd`. 11 | 12 | ```js 13 | const isBetweenDates = (dateStart, dateEnd, date) => 14 | date > dateStart && date < dateEnd; 15 | ``` 16 | 17 | ```js 18 | isBetweenDates( 19 | new Date(2010, 11, 20), 20 | new Date(2010, 11, 30), 21 | new Date(2010, 11, 19) 22 | ); // false 23 | isBetweenDates( 24 | new Date(2010, 11, 20), 25 | new Date(2010, 11, 30), 26 | new Date(2010, 11, 25) 27 | ); // true 28 | ``` 29 | -------------------------------------------------------------------------------- /snippets/isBoolean.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isBoolean 3 | tags: type,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Checks if the given argument is a native boolean element. 9 | 10 | - Use `typeof` to check if a value is classified as a boolean primitive. 11 | 12 | ```js 13 | const isBoolean = val => typeof val === 'boolean'; 14 | ``` 15 | 16 | ```js 17 | isBoolean(null); // false 18 | isBoolean(false); // true 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/isBrowserTabFocused.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isBrowserTabFocused 3 | tags: browser,beginner 4 | firstSeen: 2018-04-15T19:18:44+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the browser tab of the page is focused. 9 | 10 | - Use the `Document.hidden` property, introduced by the [Page Visibility API](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API) to check if the browser tab of the page is visible or hidden. 11 | 12 | ```js 13 | const isBrowserTabFocused = () => !document.hidden; 14 | ``` 15 | 16 | ```js 17 | isBrowserTabFocused(); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/isDeepFrozen.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isDeepFrozen 3 | tags: object,recursion,intermediate 4 | firstSeen: 2020-09-04T20:20:11+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if an object is deeply frozen. 9 | 10 | - Use recursion. 11 | - Use `Object.isFrozen()` on the given object. 12 | - Use `Object.keys()`, `Array.prototype.every()` to check that all keys are either deeply frozen objects or non-object values. 13 | 14 | ```js 15 | const isDeepFrozen = obj => 16 | Object.isFrozen(obj) && 17 | Object.keys(obj).every( 18 | prop => typeof obj[prop] !== 'object' || isDeepFrozen(obj[prop]) 19 | ); 20 | ``` 21 | 22 | ```js 23 | const x = Object.freeze({ a: 1 }); 24 | const y = Object.freeze({ b: { c: 2 } }); 25 | isDeepFrozen(x); // true 26 | isDeepFrozen(y); // false 27 | ``` 28 | -------------------------------------------------------------------------------- /snippets/isDisjoint.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isDisjoint 3 | tags: array,intermediate 4 | firstSeen: 2020-10-11T11:53:01+03:00 5 | lastUpdated: 2020-10-11T11:53:01+03:00 6 | --- 7 | 8 | Checks if the two iterables are disjointed (have no common values). 9 | 10 | - Use the `new Set()` constructor to create a new `Set` object from each iterable. 11 | - Use `Array.prototype.every()` and `Set.prototype.has()` to check that the two iterables have no common values. 12 | 13 | ```js 14 | const isDisjoint = (a, b) => { 15 | const sA = new Set(a), sB = new Set(b); 16 | return [...sA].every(v => !sB.has(v)); 17 | }; 18 | ``` 19 | 20 | ```js 21 | isDisjoint(new Set([1, 2]), new Set([3, 4])); // true 22 | isDisjoint(new Set([1, 2]), new Set([1, 3])); // false 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/isDivisible.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isDivisible 3 | tags: math,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Checks if the first numeric argument is divisible by the second one. 9 | 10 | - Use the modulo operator (`%`) to check if the remainder is equal to `0`. 11 | 12 | ```js 13 | const isDivisible = (dividend, divisor) => dividend % divisor === 0; 14 | ``` 15 | 16 | ```js 17 | isDivisible(6, 3); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/isEven.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isEven 3 | tags: math,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given number is even. 9 | 10 | - Checks whether a number is odd or even using the modulo (`%`) operator. 11 | - Returns `true` if the number is even, `false` if the number is odd. 12 | 13 | ```js 14 | const isEven = num => num % 2 === 0; 15 | ``` 16 | 17 | ```js 18 | isEven(3); // false 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/isFunction.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isFunction 3 | tags: type,function,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Checks if the given argument is a function. 9 | 10 | - Use `typeof` to check if a value is classified as a function primitive. 11 | 12 | ```js 13 | const isFunction = val => typeof val === 'function'; 14 | ``` 15 | 16 | ```js 17 | isFunction('x'); // false 18 | isFunction(x => x); // true 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/isGeneratorFunction.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isGeneratorFunction 3 | tags: type,function,intermediate 4 | firstSeen: 2020-08-07T15:40:38+03:00 5 | lastUpdated: 2020-10-20T11:21:07+03:00 6 | --- 7 | 8 | Checks if the given argument is a generator function. 9 | 10 | - Use `Object.prototype.toString()` and `Function.prototype.call()` and check if the result is `'[object GeneratorFunction]'`. 11 | 12 | ```js 13 | const isGeneratorFunction = val => 14 | Object.prototype.toString.call(val) === '[object GeneratorFunction]'; 15 | ``` 16 | 17 | ```js 18 | isGeneratorFunction(function() {}); // false 19 | isGeneratorFunction(function*() {}); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/isLeapYear.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isLeapYear 3 | tags: date,beginner 4 | firstSeen: 2020-02-05T14:00:03+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given `year` is a leap year. 9 | 10 | - Use `new Date()`, setting the date to February 29th of the given `year`. 11 | - Use `Date.prototype.getMonth()` to check if the month is equal to `1`. 12 | 13 | ```js 14 | const isLeapYear = year => new Date(year, 1, 29).getMonth() === 1; 15 | ``` 16 | 17 | ```js 18 | isLeapYear(2019); // false 19 | isLeapYear(2020); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/isLowerCase.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isLowerCase 3 | tags: string,beginner 4 | firstSeen: 2018-01-06T11:16:05+02:00 5 | lastUpdated: 2020-10-20T11:21:07+03:00 6 | --- 7 | 8 | Checks if a string is lower case. 9 | 10 | - Convert the given string to lower case, using `String.prototype.toLowerCase()` and compare it to the original. 11 | 12 | ```js 13 | const isLowerCase = str => str === str.toLowerCase(); 14 | ``` 15 | 16 | ```js 17 | isLowerCase('abc'); // true 18 | isLowerCase('a3@$'); // true 19 | isLowerCase('Ab4'); // false 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/isNegativeZero.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isNegativeZero 3 | tags: math,intermediate 4 | firstSeen: 2018-11-12T15:45:36+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given value is equal to negative zero (`-0`). 9 | 10 | - Check whether a passed value is equal to `0` and if `1` divided by the value equals `-Infinity`. 11 | 12 | ```js 13 | const isNegativeZero = val => val === 0 && 1 / val === -Infinity; 14 | ``` 15 | 16 | ```js 17 | isNegativeZero(-0); // true 18 | isNegativeZero(0); // false 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/isNil.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isNil 3 | tags: type,beginner 4 | firstSeen: 2018-01-16T16:50:21+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the specified value is `null` or `undefined`. 9 | 10 | - Use the strict equality operator to check if the value of `val` is equal to `null` or `undefined`. 11 | 12 | ```js 13 | const isNil = val => val === undefined || val === null; 14 | ``` 15 | 16 | ```js 17 | isNil(null); // true 18 | isNil(undefined); // true 19 | isNil(''); // false 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/isNode.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isNode 3 | tags: node,browser,intermediate 4 | firstSeen: 2020-10-12T20:01:21+03:00 5 | lastUpdated: 2021-04-02T11:45:13+03:00 6 | --- 7 | 8 | Determines if the current runtime environment is Node.js. 9 | 10 | - Use the `process` global object that provides information about the current Node.js process. 11 | - Check if `process`, `process.versions` and `process.versions.node` are defined. 12 | 13 | ```js 14 | const isNode = () => 15 | typeof process !== 'undefined' && 16 | !!process.versions && 17 | !!process.versions.node; 18 | ``` 19 | 20 | ```js 21 | isNode(); // true (Node) 22 | isNode(); // false (browser) 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/isNull.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isNull 3 | tags: type,beginner 4 | firstSeen: 2017-12-31T12:26:19+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the specified value is `null`. 9 | 10 | - Use the strict equality operator to check if the value of `val` is equal to `null`. 11 | 12 | ```js 13 | const isNull = val => val === null; 14 | ``` 15 | 16 | ```js 17 | isNull(null); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/isNumber.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isNumber 3 | tags: type,math,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Checks if the given argument is a number. 9 | 10 | - Use `typeof` to check if a value is classified as a number primitive. 11 | - To safeguard against `NaN`, check if `val === val` (as `NaN` has a `typeof` equal to `number` and is the only value not equal to itself). 12 | 13 | ```js 14 | const isNumber = val => typeof val === 'number' && val === val; 15 | ``` 16 | 17 | ```js 18 | isNumber(1); // true 19 | isNumber('1'); // false 20 | isNumber(NaN); // false 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/isObject.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isObject 3 | tags: type,object,beginner 4 | firstSeen: 2018-01-11T12:24:06+02:00 5 | lastUpdated: 2021-01-08T00:23:44+02:00 6 | --- 7 | 8 | Checks if the passed value is an object or not. 9 | 10 | - Uses the `Object` constructor to create an object wrapper for the given value. 11 | - If the value is `null` or `undefined`, create and return an empty object. 12 | - Otherwise, return an object of a type that corresponds to the given value. 13 | 14 | ```js 15 | const isObject = obj => obj === Object(obj); 16 | ``` 17 | 18 | ```js 19 | isObject([1, 2, 3, 4]); // true 20 | isObject([]); // true 21 | isObject(['Hello!']); // true 22 | isObject({ a: 1 }); // true 23 | isObject({}); // true 24 | isObject(true); // false 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/isObjectLike.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isObjectLike 3 | tags: type,object,beginner 4 | firstSeen: 2018-01-23T19:30:03+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Checks if a value is object-like. 9 | 10 | - Check if the provided value is not `null` and its `typeof` is equal to `'object'`. 11 | 12 | ```js 13 | const isObjectLike = val => val !== null && typeof val === 'object'; 14 | ``` 15 | 16 | ```js 17 | isObjectLike({}); // true 18 | isObjectLike([1, 2, 3]); // true 19 | isObjectLike(x => x); // false 20 | isObjectLike(null); // false 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/isOdd.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isOdd 3 | tags: math,beginner 4 | firstSeen: 2019-09-25T20:35:06+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given number is odd. 9 | 10 | - Check whether a number is odd or even using the modulo (`%`) operator. 11 | - Return `true` if the number is odd, `false` if the number is even. 12 | 13 | ```js 14 | const isOdd = num => num % 2 === 1; 15 | ``` 16 | 17 | ```js 18 | isOdd(3); // true 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/isPlainObject.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isPlainObject 3 | tags: type,object,intermediate 4 | firstSeen: 2018-01-19T13:59:12+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the provided value is an object created by the Object constructor. 9 | 10 | - Check if the provided value is truthy. 11 | - Use `typeof` to check if it is an object and `Object.prototype.constructor` to make sure the constructor is equal to `Object`. 12 | 13 | ```js 14 | const isPlainObject = val => 15 | !!val && typeof val === 'object' && val.constructor === Object; 16 | ``` 17 | 18 | ```js 19 | isPlainObject({ a: 1 }); // true 20 | isPlainObject(new Map()); // false 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/isPowerOfTen.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isPowerOfTen 3 | tags: math,beginner 4 | firstSeen: 2021-01-06T22:53:58+02:00 5 | lastUpdated: 2021-01-06T22:53:58+02:00 6 | --- 7 | 8 | Checks if the given number is a power of `10`. 9 | 10 | - Use `Math.log10()` and the modulo operator (`%`) to determine if `n` is a power of `10`. 11 | 12 | ```js 13 | const isPowerOfTen = n => Math.log10(n) % 1 === 0; 14 | ``` 15 | 16 | ```js 17 | isPowerOfTen(1); // true 18 | isPowerOfTen(10); // true 19 | isPowerOfTen(20); // false 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/isPowerOfTwo.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isPowerOfTwo 3 | tags: math,beginner 4 | firstSeen: 2019-12-31T13:17:12+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given number is a power of `2`. 9 | 10 | - Use the bitwise binary AND operator (`&`) to determine if `n` is a power of `2`. 11 | - Additionally, check that `n` is not falsy. 12 | 13 | ```js 14 | const isPowerOfTwo = n => !!n && (n & (n - 1)) == 0; 15 | ``` 16 | 17 | ```js 18 | isPowerOfTwo(0); // false 19 | isPowerOfTwo(1); // true 20 | isPowerOfTwo(8); // true 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/isPrime.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isPrime 3 | tags: math,algorithm,beginner 4 | firstSeen: 2017-12-19T22:35:56+02:00 5 | lastUpdated: 2021-01-12T19:36:36+02:00 6 | --- 7 | 8 | Checks if the provided integer is a prime number. 9 | 10 | - Check numbers from `2` to the square root of the given number. 11 | - Return `false` if any of them divides the given number, else return `true`, unless the number is less than `2`. 12 | 13 | ```js 14 | const isPrime = num => { 15 | const boundary = Math.floor(Math.sqrt(num)); 16 | for (let i = 2; i <= boundary; i++) if (num % i === 0) return false; 17 | return num >= 2; 18 | }; 19 | ``` 20 | 21 | ```js 22 | isPrime(11); // true 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/isPrimitive.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isPrimitive 3 | tags: type,intermediate 4 | firstSeen: 2017-12-31T12:48:13+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Checks if the passed value is primitive or not. 9 | 10 | - Create an object from `val` and compare it with `val` to determine if the passed value is primitive (i.e. not equal to the created object). 11 | 12 | ```js 13 | const isPrimitive = val => Object(val) !== val; 14 | ``` 15 | 16 | ```js 17 | isPrimitive(null); // true 18 | isPrimitive(undefined); // true 19 | isPrimitive(50); // true 20 | isPrimitive('Hello!'); // true 21 | isPrimitive(false); // true 22 | isPrimitive(Symbol()); // true 23 | isPrimitive([]); // false 24 | isPrimitive({}); // false 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/isSameDate.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isSameDate 3 | tags: date,beginner 4 | firstSeen: 2018-09-29T13:58:38+03:00 5 | lastUpdated: 2020-11-03T22:11:18+02:00 6 | --- 7 | 8 | Checks if a date is the same as another date. 9 | 10 | - Use `Date.prototype.toISOString()` and strict equality checking (`===`) to check if the first date is the same as the second one. 11 | 12 | ```js 13 | const isSameDate = (dateA, dateB) => 14 | dateA.toISOString() === dateB.toISOString(); 15 | ``` 16 | 17 | ```js 18 | isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/isSameOrigin.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isSameOrigin 3 | tags: object,beginner 4 | firstSeen: 2021-04-22T08:27:41+03:00 5 | lastUpdated: 2021-04-22T08:27:41+03:00 6 | --- 7 | 8 | Checks if two URLs are on the same origin. 9 | 10 | - Use `URL.protocol` and `URL.host` to check if both URLs have the same protocol and host. 11 | 12 | ```js 13 | const isSameOrigin = (origin, destination) => 14 | origin.protocol === destination.protocol && origin.host === destination.host; 15 | ``` 16 | 17 | ```js 18 | const origin = new URL('https://www.30secondsofcode.org/about'); 19 | const destination = new URL('https://www.30secondsofcode.org/contact'); 20 | isSameOrigin(origin, destination); // true 21 | const other = new URL('https://developer.mozilla.org); 22 | isSameOrigin(origin, other); // false 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/isStream.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isStream 3 | tags: node,type,intermediate 4 | firstSeen: 2018-10-01T20:12:19+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given argument is a stream. 9 | 10 | - Check if the value is different from `null`. 11 | - Use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`. 12 | 13 | ```js 14 | const isStream = val => 15 | val !== null && typeof val === 'object' && typeof val.pipe === 'function'; 16 | ``` 17 | 18 | ```js 19 | const fs = require('fs'); 20 | 21 | isStream(fs.createReadStream('test.txt')); // true 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/isString.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isString 3 | tags: type,string,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given argument is a string. 9 | Only works for string primitives. 10 | 11 | - Use `typeof` to check if a value is classified as a string primitive. 12 | 13 | ```js 14 | const isString = val => typeof val === 'string'; 15 | ``` 16 | 17 | ```js 18 | isString('10'); // true 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/isSymbol.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isSymbol 3 | tags: type,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Checks if the given argument is a symbol. 9 | 10 | - Use `typeof` to check if a value is classified as a symbol primitive. 11 | 12 | ```js 13 | const isSymbol = val => typeof val === 'symbol'; 14 | ``` 15 | 16 | ```js 17 | isSymbol(Symbol('x')); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/isTravisCI.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isTravisCI 3 | tags: node,intermediate 4 | unlisted: true 5 | firstSeen: 2018-01-01T17:28:08+02:00 6 | lastUpdated: 2020-10-20T23:02:01+03:00 7 | --- 8 | 9 | Checks if the current environment is [Travis CI](https://travis-ci.org/). 10 | 11 | - Check if the current environment has the `TRAVIS` and `CI` environment variables ([reference](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables)). 12 | 13 | ```js 14 | const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; 15 | ``` 16 | 17 | ```js 18 | isTravisCI(); // true (if code is running on Travis CI) 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/isUndefined.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isUndefined 3 | tags: type,beginner 4 | firstSeen: 2018-01-16T16:50:21+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the specified value is `undefined`. 9 | 10 | - Use the strict equality operator to check if `val` is equal to `undefined`. 11 | 12 | ```js 13 | const isUndefined = val => val === undefined; 14 | ``` 15 | 16 | ```js 17 | isUndefined(undefined); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/isUpperCase.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isUpperCase 3 | tags: string,beginner 4 | firstSeen: 2018-01-06T11:16:05+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Checks if a string is upper case. 9 | 10 | - Convert the given string to upper case, using `String.prototype.toUpperCase()` and compare it to the original. 11 | 12 | ```js 13 | const isUpperCase = str => str === str.toUpperCase(); 14 | ``` 15 | 16 | ```js 17 | isUpperCase('ABC'); // true 18 | isUpperCase('A3@$'); // true 19 | isUpperCase('aB4'); // false 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/isValidJSON.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isValidJSON 3 | tags: type,intermediate 4 | firstSeen: 2017-12-31T14:53:01+02:00 5 | lastUpdated: 2020-10-18T13:49:49+03:00 6 | --- 7 | 8 | Checks if the provided string is a valid JSON. 9 | 10 | - Use `JSON.parse()` and a `try... catch` block to check if the provided string is a valid JSON. 11 | 12 | ```js 13 | const isValidJSON = str => { 14 | try { 15 | JSON.parse(str); 16 | return true; 17 | } catch (e) { 18 | return false; 19 | } 20 | }; 21 | ``` 22 | 23 | ```js 24 | isValidJSON('{"name":"Adam","age":20}'); // true 25 | isValidJSON('{"name":"Adam",age:"20"}'); // false 26 | isValidJSON(null); // true 27 | ``` 28 | -------------------------------------------------------------------------------- /snippets/isWeekday.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isWeekday 3 | tags: date,beginner 4 | firstSeen: 2019-07-19T12:12:09+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given date is a weekday. 9 | 10 | - Use `Date.prototype.getDay()` to check weekday by using a modulo operator (`%`). 11 | - Omit the argument, `d`, to use the current date as default. 12 | 13 | ```js 14 | const isWeekday = (d = new Date()) => d.getDay() % 6 !== 0; 15 | ``` 16 | 17 | ```js 18 | isWeekday(); // true (if current date is 2019-07-19) 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/isWeekend.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: isWeekend 3 | tags: date,beginner 4 | firstSeen: 2019-07-19T17:07:02+03:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Checks if the given date is a weekend. 9 | 10 | - Use `Date.prototype.getDay()` to check weekend by using a modulo operator (`%`). 11 | - Omit the argument, `d`, to use the current date as default. 12 | 13 | ```js 14 | const isWeekend = (d = new Date()) => d.getDay() % 6 === 0; 15 | ``` 16 | 17 | ```js 18 | isWeekend(); // 2018-10-19 (if current date is 2018-10-18) 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/kmToMiles.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: kmToMiles 3 | tags: math,beginner 4 | unlisted: true 5 | firstSeen: 2020-10-04T00:50:13+03:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Converts kilometers to miles. 10 | 11 | - Follow the conversion formula `mi = km * 0.621371`. 12 | 13 | ```js 14 | const kmToMiles = km => km * 0.621371; 15 | ``` 16 | 17 | ```js 18 | kmToMiles(8.1) // 5.0331051 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/last.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: last 3 | tags: array,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-20T23:02:01+03:00 6 | --- 7 | 8 | Returns the last element in an array. 9 | 10 | - Check if `arr` is truthy and has a `length` property. 11 | - Use `Array.prototype.length - 1` to compute the index of the last element of the given array and return it, otherwise return `undefined`. 12 | 13 | ```js 14 | const last = arr => (arr && arr.length ? arr[arr.length - 1] : undefined); 15 | ``` 16 | 17 | ```js 18 | last([1, 2, 3]); // 3 19 | last([]); // undefined 20 | last(null); // undefined 21 | last(undefined); // undefined 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/lcm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: lcm 3 | tags: math,algorithm,recursion,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-12-28T13:49:24+02:00 6 | --- 7 | 8 | Calculates the least common multiple of two or more numbers. 9 | 10 | - Use the greatest common divisor (GCD) formula and the fact that `lcm(x, y) = x * y / gcd(x, y)` to determine the least common multiple. 11 | - The GCD formula uses recursion. 12 | 13 | ```js 14 | const lcm = (...arr) => { 15 | const gcd = (x, y) => (!y ? x : gcd(y, x % y)); 16 | const _lcm = (x, y) => (x * y) / gcd(x, y); 17 | return [...arr].reduce((a, b) => _lcm(a, b)); 18 | }; 19 | ``` 20 | 21 | ```js 22 | lcm(12, 7); // 84 23 | lcm(...[1, 3, 4, 5]); // 60 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/listenOnce.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: listenOnce 3 | tags: browser,event,beginner 4 | firstSeen: 2020-06-01T16:58:52+03:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Adds an event listener to an element that will only run the callback the first time the event is triggered. 9 | 10 | - Use `EventTarget.addEventListener()` to add an event listener to an element. 11 | - Use `{ once: true }` as options to only run the given callback once. 12 | 13 | ```js 14 | const listenOnce = (el, evt, fn) => 15 | el.addEventListener(evt, fn, { once: true }); 16 | ``` 17 | 18 | ```js 19 | listenOnce( 20 | document.getElementById('my-id'), 21 | 'click', 22 | () => console.log('Hello world') 23 | ); // 'Hello world' will only be logged on the first click 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/logBase.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: logBase 3 | tags: math,beginner 4 | firstSeen: 2020-10-07T19:14:30+03:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Calculates the logarithm of the given number in the given base. 9 | 10 | - Use `Math.log()` to get the logarithm from the value and the base and divide them. 11 | 12 | ```js 13 | const logBase = (n, base) => Math.log(n) / Math.log(base); 14 | ``` 15 | 16 | ```js 17 | logBase(10, 10); // 1 18 | logBase(100, 10); // 2 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/mapConsecutive.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: mapConsecutive 3 | tags: array,intermediate 4 | firstSeen: 2021-08-08T05:00:00-04:00 5 | --- 6 | 7 | Maps each block of `n` consencutive elements using the given function, `fn`. 8 | 9 | - Use `Array.prototype.slice()` to get `arr` with `n` elements removed from the left. 10 | - Use `Array.prototype.map()` and `Array.prototype.slice()` to apply `fn` to each block of `n` consecutive elements in `arr`. 11 | 12 | ```js 13 | const mapConsecutive = (arr, n, fn) => 14 | arr.slice(n - 1).map((v, i) => fn(arr.slice(i, i + n))); 15 | ``` 16 | 17 | ```js 18 | mapConsecutive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3, x => x.join('-')); 19 | // ['1-2-3', '2-3-4', '3-4-5', '4-5-6', '5-6-7', '6-7-8', '7-8-9', '8-9-10']; 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/mapKeys.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: mapKeys 3 | tags: object,intermediate 4 | firstSeen: 2018-01-11T20:33:14+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Maps the keys of an object using the provided function, generating a new object. 9 | 10 | - Use `Object.keys()` to iterate over the object's keys. 11 | - Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`. 12 | 13 | ```js 14 | const mapKeys = (obj, fn) => 15 | Object.keys(obj).reduce((acc, k) => { 16 | acc[fn(obj[k], k, obj)] = obj[k]; 17 | return acc; 18 | }, {}); 19 | ``` 20 | 21 | ```js 22 | mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 } 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/mapNumRange.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: mapNumRange 3 | tags: math,beginner 4 | firstSeen: 2019-02-23T12:38:16+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Maps a number from one range to another range. 9 | 10 | - Return `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`. 11 | 12 | ```js 13 | const mapNumRange = (num, inMin, inMax, outMin, outMax) => 14 | ((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin; 15 | ``` 16 | 17 | ```js 18 | mapNumRange(5, 0, 10, 0, 100); // 50 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/mapObject.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: mapObject 3 | tags: array,object,intermediate 4 | firstSeen: 2017-12-18T12:11:58+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Maps the values of an array to an object using a function. 9 | 10 | - Use `Array.prototype.reduce()` to apply `fn` to each element in `arr` and combine the results into an object. 11 | - Use `el` as the key for each property and the result of `fn` as the value. 12 | 13 | ```js 14 | const mapObject = (arr, fn) => 15 | arr.reduce((acc, el, i) => { 16 | acc[el] = fn(el, i, arr); 17 | return acc; 18 | }, {}); 19 | ``` 20 | 21 | ```js 22 | mapObject([1, 2, 3], a => a * a); // { 1: 1, 2: 4, 3: 9 } 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/maxBy.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: maxBy 3 | tags: math,array,beginner 4 | firstSeen: 2018-01-11T12:25:54+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Returns the maximum value of an array, after mapping each element to a value using the provided function. 9 | 10 | - Use `Array.prototype.map()` to map each element to the value returned by `fn`. 11 | - Use `Math.max()` to get the maximum value. 12 | 13 | ```js 14 | const maxBy = (arr, fn) => 15 | Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); 16 | ``` 17 | 18 | ```js 19 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], x => x.n); // 8 20 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/maxDate.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: maxDate 3 | tags: date,intermediate 4 | firstSeen: 2018-09-29T13:38:20+03:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Returns the maximum of the given dates. 9 | 10 | - Use the ES6 spread syntax with `Math.max()` to find the maximum date value. 11 | - Use `new Date()` to convert it to a `Date` object. 12 | 13 | ```js 14 | const maxDate = (...dates) => new Date(Math.max(...dates)); 15 | ``` 16 | 17 | ```js 18 | const dates = [ 19 | new Date(2017, 4, 13), 20 | new Date(2018, 2, 12), 21 | new Date(2016, 0, 10), 22 | new Date(2016, 0, 9) 23 | ]; 24 | maxDate(...dates); // 2018-03-11T22:00:00.000Z 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/median.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: median 3 | tags: math,array,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:23:47+03:00 6 | --- 7 | 8 | Calculates the median of an array of numbers. 9 | 10 | - Find the middle of the array, use `Array.prototype.sort()` to sort the values. 11 | - Return the number at the midpoint if `Array.prototype.length` is odd, otherwise the average of the two middle numbers. 12 | 13 | ```js 14 | const median = arr => { 15 | const mid = Math.floor(arr.length / 2), 16 | nums = [...arr].sort((a, b) => a - b); 17 | return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; 18 | }; 19 | ``` 20 | 21 | ```js 22 | median([5, 6, 50, 1, -5]); // 5 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/midpoint.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: midpoint 3 | tags: math,beginner 4 | firstSeen: 2018-11-15T17:49:04+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Calculates the midpoint between two pairs of (x,y) points. 9 | 10 | - Destructure the array to get `x1`, `y1`, `x2` and `y2`. 11 | - Calculate the midpoint for each dimension by dividing the sum of the two endpoints by `2`. 12 | 13 | ```js 14 | const midpoint = ([x1, y1], [x2, y2]) => [(x1 + x2) / 2, (y1 + y2) / 2]; 15 | ``` 16 | 17 | ```js 18 | midpoint([2, 2], [4, 4]); // [3, 3] 19 | midpoint([4, 4], [6, 6]); // [5, 5] 20 | midpoint([1, 3], [2, 4]); // [1.5, 3.5] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/milesToKm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: milesToKm 3 | tags: math,beginner 4 | unlisted: true 5 | firstSeen: 2020-10-04T00:51:51+03:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Converts miles to kilometers. 10 | 11 | - Follow the conversion formula `km = mi * 1.609344`. 12 | 13 | ```js 14 | const milesToKm = miles => miles * 1.609344; 15 | ``` 16 | 17 | ```js 18 | milesToKm(5); // ~8.04672 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/minBy.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: minBy 3 | tags: math,array,beginner 4 | firstSeen: 2018-01-11T12:25:54+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Returns the minimum value of an array, after mapping each element to a value using the provided function. 9 | 10 | - Use `Array.prototype.map()` to map each element to the value returned by `fn`. 11 | - Use `Math.min()` to get the minimum value. 12 | 13 | ```js 14 | const minBy = (arr, fn) => 15 | Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); 16 | ``` 17 | 18 | ```js 19 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], x => x.n); // 2 20 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 2 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/minDate.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: minDate 3 | tags: date,intermediate 4 | firstSeen: 2018-09-29T13:38:20+03:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Returns the minimum of the given dates. 9 | 10 | - Use the ES6 spread syntax with `Math.min()` to find the minimum date value. 11 | - Use `new Date()` to convert it to a `Date` object. 12 | 13 | ```js 14 | const minDate = (...dates) => new Date(Math.min(...dates)); 15 | ``` 16 | 17 | ```js 18 | const dates = [ 19 | new Date(2017, 4, 13), 20 | new Date(2018, 2, 12), 21 | new Date(2016, 0, 10), 22 | new Date(2016, 0, 9) 23 | ]; 24 | minDate(...dates); // 2016-01-08T22:00:00.000Z 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/negate.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: negate 3 | tags: function,beginner 4 | firstSeen: 2017-12-24T08:28:52+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Negates a predicate function. 9 | 10 | - Take a predicate function and apply the not operator (`!`) to it with its arguments. 11 | 12 | ```js 13 | const negate = func => (...args) => !func(...args); 14 | ``` 15 | 16 | ```js 17 | [1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/nodeListToArray.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: nodeListToArray 3 | tags: browser,array,beginner 4 | firstSeen: 2018-05-06T18:11:21+03:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Converts a `NodeList` to an array. 9 | 10 | - Use spread operator (`...`) inside new array to convert a `NodeList` to an array. 11 | 12 | ```js 13 | const nodeListToArray = nodeList => [...nodeList]; 14 | ``` 15 | 16 | ```js 17 | nodeListToArray(document.childNodes); // [ , html ] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/none.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: none 3 | tags: array,beginner 4 | firstSeen: 2018-02-14T11:46:15+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Checks if the provided predicate function returns `false` for all elements in a collection. 9 | 10 | - Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`. 11 | - Omit the second argument, `fn`, to use `Boolean` as a default. 12 | 13 | ```js 14 | const none = (arr, fn = Boolean) => !arr.some(fn); 15 | ``` 16 | 17 | ```js 18 | none([0, 1, 3, 0], x => x == 2); // true 19 | none([0, 0, 0]); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/nor.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: nor 3 | tags: math,logic,beginner 4 | unlisted: true 5 | firstSeen: 2021-03-29T21:20:41+03:00 6 | lastUpdated: 2021-04-02T16:47:15+03:00 7 | --- 8 | 9 | Checks if none of the arguments are `true`. 10 | 11 | - Use the logical not (`!`) operator to return the inverse of the logical or (`||`) of the two given values. 12 | 13 | ```js 14 | const nor = (a, b) => !(a||b); 15 | ``` 16 | 17 | ```js 18 | nor(true, true); // false 19 | nor(true, false); // false 20 | nor(false, false); // true 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/not.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: not 3 | tags: math,logic,beginner 4 | unlisted: true 5 | firstSeen: 2020-05-13T11:28:26+03:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Returns the logical inverse of the given value. 10 | 11 | - Use the logical not (`!`) operator to return the inverse of the given value. 12 | 13 | ```js 14 | const not = a => !a; 15 | ``` 16 | 17 | ```js 18 | not(true); // false 19 | not(false); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/nthArg.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: nthArg 3 | tags: function,beginner 4 | firstSeen: 2018-01-23T21:27:37+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Creates a function that gets the argument at index `n`. 9 | 10 | - Use `Array.prototype.slice()` to get the desired argument at index `n`. 11 | - If `n` is negative, the nth argument from the end is returned. 12 | 13 | ```js 14 | const nthArg = n => (...args) => args.slice(n)[0]; 15 | ``` 16 | 17 | ```js 18 | const third = nthArg(2); 19 | third(1, 2, 3); // 3 20 | third(1, 2); // undefined 21 | const last = nthArg(-1); 22 | last(1, 2, 3, 4, 5); // 5 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/nthElement.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: nthElement 3 | tags: array,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Returns the nth element of an array. 9 | 10 | - Use `Array.prototype.slice()` to get an array containing the nth element at the first place. 11 | - If the index is out of bounds, return `undefined`. 12 | - Omit the second argument, `n`, to get the first element of the array. 13 | 14 | ```js 15 | const nthElement = (arr, n = 0) => 16 | (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0]; 17 | ``` 18 | 19 | ```js 20 | nthElement(['a', 'b', 'c'], 1); // 'b' 21 | nthElement(['a', 'b', 'b'], -3); // 'a' 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/nthRoot.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: nthRoot 3 | tags: math,beginner 4 | firstSeen: 2021-01-06T22:47:48+02:00 5 | lastUpdated: 2021-01-06T22:47:48+02:00 6 | --- 7 | 8 | Calculates the nth root of a given number. 9 | 10 | - Use `Math.pow()` to calculate `x` to the power of `1/n` which is equal to the nth root of `x`. 11 | 12 | ```js 13 | const nthRoot = (x, n) => Math.pow(x, 1 / n); 14 | ``` 15 | 16 | ```js 17 | nthRoot(32, 5); // 2 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/objectFromPairs.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: objectFromPairs 3 | tags: object,array,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Creates an object from the given key-value pairs. 9 | 10 | - Use `Array.prototype.reduce()` to create and combine key-value pairs. 11 | 12 | ```js 13 | const objectFromPairs = arr => 14 | arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); 15 | ``` 16 | 17 | ```js 18 | objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2} 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/objectToEntries.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: objectToEntries 3 | tags: object,array,beginner 4 | firstSeen: 2020-04-16T11:10:13+03:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Creates an array of key-value pair arrays from an object. 9 | 10 | - Use `Object.keys()` and `Array.prototype.map()` to iterate over the object's keys and produce an array with key-value pairs. 11 | 12 | ```js 13 | const objectToEntries = obj => Object.keys(obj).map(k => [k, obj[k]]); 14 | ``` 15 | 16 | ```js 17 | objectToEntries({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/objectToPairs.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: objectToPairs 3 | tags: object,array,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Creates an array of key-value pair arrays from an object. 9 | 10 | - Use `Object.entries()` to get an array of key-value pair arrays from the given object. 11 | 12 | ```js 13 | const objectToPairs = obj => Object.entries(obj); 14 | ``` 15 | 16 | ```js 17 | objectToPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/off.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: off 3 | tags: browser,event,intermediate 4 | firstSeen: 2018-01-05T14:33:48+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Removes an event listener from an element. 9 | 10 | - Use `EventTarget.removeEventListener()` to remove an event listener from an element. 11 | - Omit the fourth argument `opts` to use `false` or specify it based on the options used when the event listener was added. 12 | 13 | ```js 14 | const off = (el, evt, fn, opts = false) => 15 | el.removeEventListener(evt, fn, opts); 16 | ``` 17 | 18 | ```js 19 | const fn = () => console.log('!'); 20 | document.body.addEventListener('click', fn); 21 | off(document.body, 'click', fn); // no longer logs '!' upon clicking on the page 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/offset.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: offset 3 | tags: array,beginner 4 | firstSeen: 2018-04-10T19:07:50+03:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Moves the specified amount of elements to the end of the array. 9 | 10 | - Use `Array.prototype.slice()` twice to get the elements after the specified index and the elements before that. 11 | - Use the spread operator (`...`) to combine the two into one array. 12 | - If `offset` is negative, the elements will be moved from end to start. 13 | 14 | ```js 15 | const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)]; 16 | ``` 17 | 18 | ```js 19 | offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2] 20 | offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3] 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/omit.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: omit 3 | tags: object,intermediate 4 | firstSeen: 2018-01-19T13:14:46+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Omits the key-value pairs corresponding to the given keys from an object. 9 | 10 | - Use `Object.keys()`, `Array.prototype.filter()` and `Array.prototype.includes()` to remove the provided keys. 11 | - Use `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs. 12 | 13 | ```js 14 | const omit = (obj, arr) => 15 | Object.keys(obj) 16 | .filter(k => !arr.includes(k)) 17 | .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); 18 | ``` 19 | 20 | ```js 21 | omit({ a: 1, b: '2', c: 3 }, ['b']); // { 'a': 1, 'c': 3 } 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/onClickOutside.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: onClickOutside 3 | tags: browser,event,intermediate 4 | firstSeen: 2021-01-06T13:57:56+02:00 5 | lastUpdated: 2021-01-06T13:57:56+02:00 6 | --- 7 | 8 | Runs the callback whenever the user clicks outside of the specified element. 9 | 10 | - Use `EventTarget.addEventListener()` to listen for `'click'` events. 11 | - Use `Node.contains()` to check if `Event.target` is a descendant of `element` and run `callback` if not. 12 | 13 | ```js 14 | const onClickOutside = (element, callback) => { 15 | document.addEventListener('click', e => { 16 | if (!element.contains(e.target)) callback(); 17 | }); 18 | }; 19 | ``` 20 | 21 | ```js 22 | onClickOutside('#my-element', () => console.log('Hello')); 23 | // Will log 'Hello' whenever the user clicks outside of #my-element 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/or.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: or 3 | tags: math,logic,beginner 4 | unlisted: true 5 | firstSeen: 2020-05-13T11:35:41+03:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Checks if at least one of the arguments is `true`. 10 | 11 | - Use the logical or (`||`) operator on the two given values. 12 | 13 | ```js 14 | const or = (a, b) => a || b; 15 | ``` 16 | 17 | ```js 18 | or(true, true); // true 19 | or(true, false); // true 20 | or(false, false); // false 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/over.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: over 3 | tags: function,intermediate 4 | firstSeen: 2018-01-23T21:02:17+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Creates a function that invokes each provided function with the arguments it receives and returns the results. 9 | 10 | - Use `Array.prototype.map()` and `Function.prototype.apply()` to apply each function to the given arguments. 11 | 12 | ```js 13 | const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); 14 | ``` 15 | 16 | ```js 17 | const minMax = over(Math.min, Math.max); 18 | minMax(1, 2, 3, 4, 5); // [1, 5] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/overArgs.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: overArgs 3 | tags: function,intermediate 4 | firstSeen: 2018-01-28T14:54:16+02:00 5 | lastUpdated: 2020-10-21T21:54:53+03:00 6 | --- 7 | 8 | Creates a function that invokes the provided function with its arguments transformed. 9 | 10 | - Use `Array.prototype.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`. 11 | 12 | ```js 13 | const overArgs = (fn, transforms) => 14 | (...args) => fn(...args.map((val, i) => transforms[i](val))); 15 | ``` 16 | 17 | ```js 18 | const square = n => n * n; 19 | const double = n => n * 2; 20 | const fn = overArgs((x, y) => [x, y], [square, double]); 21 | fn(9, 3); // [81, 6] 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/pad.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: pad 3 | tags: string,beginner 4 | firstSeen: 2018-02-24T11:51:27+02:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Pads a string on both sides with the specified character, if it's shorter than the specified `length`. 9 | 10 | - Use `String.prototype.padStart()` and `String.prototype.padEnd()` to pad both sides of the given string. 11 | - Omit the third argument, `char`, to use the whitespace character as the default padding character. 12 | 13 | ```js 14 | const pad = (str, length, char = ' ') => 15 | str.padStart((str.length + length) / 2, char).padEnd(length, char); 16 | ``` 17 | 18 | ```js 19 | pad('cat', 8); // ' cat ' 20 | pad(String(42), 6, '0'); // '004200' 21 | pad('foobar', 3); // 'foobar' 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/padNumber.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: padNumber 3 | tags: string,math,beginner 4 | firstSeen: 2020-10-03T23:31:08+03:00 5 | lastUpdated: 2020-10-03T23:31:08+03:00 6 | --- 7 | 8 | Pads a given number to the specified length. 9 | 10 | - Use `String.prototype.padStart()` to pad the number to specified length, after converting it to a string. 11 | 12 | ```js 13 | const padNumber = (n, l) => `${n}`.padStart(l, '0'); 14 | ``` 15 | 16 | ```js 17 | padNumber(1234, 6); // '001234' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/palindrome.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: palindrome 3 | tags: string,intermediate 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Checks if the given string is a palindrome. 9 | 10 | - Normalize the string to `String.prototype.toLowerCase()` and use `String.prototype.replace()` to remove non-alphanumeric characters from it. 11 | - Use the spread operator (`...`) to split the normalized string into individual characters. 12 | - Use `Array.prototype.reverse()`, `String.prototype.join('')` and compare the result to the normalized string. 13 | 14 | ```js 15 | const palindrome = str => { 16 | const s = str.toLowerCase().replace(/[\W_]/g, ''); 17 | return s === [...s].reverse().join(''); 18 | }; 19 | ``` 20 | 21 | ```js 22 | palindrome('taco cat'); // true 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/partial.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: partial 3 | tags: function,intermediate 4 | firstSeen: 2018-01-24T14:40:16+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Creates a function that invokes `fn` with `partials` prepended to the arguments it receives. 9 | 10 | - Use the spread operator (`...`) to prepend `partials` to the list of arguments of `fn`. 11 | 12 | ```js 13 | const partial = (fn, ...partials) => (...args) => fn(...partials, ...args); 14 | ``` 15 | 16 | ```js 17 | const greet = (greeting, name) => greeting + ' ' + name + '!'; 18 | const greetHello = partial(greet, 'Hello'); 19 | greetHello('John'); // 'Hello John!' 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/partialRight.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: partialRight 3 | tags: function,intermediate 4 | firstSeen: 2018-01-24T14:40:16+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Creates a function that invokes `fn` with `partials` appended to the arguments it receives. 9 | 10 | - Use the spread operator (`...`) to append `partials` to the list of arguments of `fn`. 11 | 12 | ```js 13 | const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); 14 | ``` 15 | 16 | ```js 17 | const greet = (greeting, name) => greeting + ' ' + name + '!'; 18 | const greetJohn = partialRight(greet, 'John'); 19 | greetJohn('Hello'); // 'Hello John!' 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/percentile.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: percentile 3 | tags: math,intermediate 4 | firstSeen: 2017-12-13T12:50:16+02:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Calculates the percentage of numbers in the given array that are less or equal to the given value. 9 | 10 | - Use `Array.prototype.reduce()` to calculate how many numbers are below the value and how many are the same value and apply the percentile formula. 11 | 12 | ```js 13 | const percentile = (arr, val) => 14 | (100 * 15 | arr.reduce( 16 | (acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 17 | 0 18 | )) / 19 | arr.length; 20 | ``` 21 | 22 | ```js 23 | percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/pick.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: pick 3 | tags: object,intermediate 4 | firstSeen: 2017-12-13T23:51:34+02:00 5 | lastUpdated: 2020-10-18T14:58:09+03:00 6 | --- 7 | 8 | Picks the key-value pairs corresponding to the given keys from an object. 9 | 10 | - Use `Array.prototype.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object. 11 | 12 | ```js 13 | const pick = (obj, arr) => 14 | arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); 15 | ``` 16 | 17 | ```js 18 | pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 } 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/pipeFunctions.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: pipeFunctions 3 | tags: function,intermediate 4 | firstSeen: 2017-12-26T19:02:27+02:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Performs left-to-right function composition. 9 | 10 | - Use `Array.prototype.reduce()` with the spread operator (`...`) to perform left-to-right function composition. 11 | - The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. 12 | 13 | ```js 14 | const pipeFunctions = (...fns) => 15 | fns.reduce((f, g) => (...args) => g(f(...args))); 16 | ``` 17 | 18 | ```js 19 | const add5 = x => x + 5; 20 | const multiply = (x, y) => x * y; 21 | const multiplyAndAdd5 = pipeFunctions(multiply, add5); 22 | multiplyAndAdd5(5, 2); // 15 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/pluck.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: pluck 3 | tags: array,object,beginner 4 | firstSeen: 2020-10-18T01:19:37+03:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Converts an array of objects into an array of values corresponding to the specified `key`. 9 | 10 | - Use `Array.prototype.map()` to map the array of objects to the value of `key` for each one. 11 | 12 | ```js 13 | const pluck = (arr, key) => arr.map(i => i[key]); 14 | ``` 15 | 16 | ```js 17 | const simpsons = [ 18 | { name: 'lisa', age: 8 }, 19 | { name: 'homer', age: 36 }, 20 | { name: 'marge', age: 34 }, 21 | { name: 'bart', age: 10 } 22 | ]; 23 | pluck(simpsons, 'age'); // [8, 36, 34, 10] 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/powerset.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: powerset 3 | tags: math,algorithm,beginner 4 | firstSeen: 2017-12-07T14:41:33+02:00 5 | lastUpdated: 2021-09-27T15:27:07+02:00 6 | --- 7 | 8 | Returns the powerset of a given array of numbers. 9 | 10 | - Use `Array.prototype.reduce()` combined with `Array.prototype.map()` to iterate over elements and combine into an array containing all combinations. 11 | 12 | ```js 13 | const powerset = arr => 14 | arr.reduce((a, v) => a.concat(a.map(r => r.concat(v))), [[]]); 15 | ``` 16 | 17 | ```js 18 | powerset([1, 2]); // [[], [1], [2], [1, 2]] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/prefersDarkColorScheme.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: prefersDarkColorScheme 3 | tags: browser,intermediate 4 | firstSeen: 2020-05-04T12:50:35+03:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Checks if the user color scheme preference is `dark`. 9 | 10 | - Use `Window.matchMedia()` with the appropriate media query to check the user color scheme preference. 11 | 12 | ```js 13 | const prefersDarkColorScheme = () => 14 | window && 15 | window.matchMedia && 16 | window.matchMedia('(prefers-color-scheme: dark)').matches; 17 | ``` 18 | 19 | ```js 20 | prefersDarkColorScheme(); // true 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/prefersLightColorScheme.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: prefersLightColorScheme 3 | tags: browser,intermediate 4 | firstSeen: 2020-05-04T12:50:35+03:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Checks if the user color scheme preference is `light`. 9 | 10 | - Use `Window.matchMedia()` with the appropriate media query to check the user color scheme preference. 11 | 12 | ```js 13 | const prefersLightColorScheme = () => 14 | window && 15 | window.matchMedia && 16 | window.matchMedia('(prefers-color-scheme: light)').matches; 17 | ``` 18 | 19 | ```js 20 | prefersLightColorScheme(); // true 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/primeFactors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: primeFactors 3 | tags: math,algorithm,beginner 4 | firstSeen: 2020-12-28T13:11:01+02:00 5 | lastUpdated: 2020-12-28T13:11:01+02:00 6 | --- 7 | 8 | Finds the prime factors of a given number using the trial division algorithm. 9 | 10 | - Use a `while` loop to iterate over all possible prime factors, starting with `2`. 11 | - If the current factor, `f`, exactly divides `n`, add `f` to the factors array and divide `n` by `f`. Otherwise, increment `f` by one. 12 | 13 | ```js 14 | const primeFactors = n => { 15 | let a = [], 16 | f = 2; 17 | while (n > 1) { 18 | if (n % f === 0) { 19 | a.push(f); 20 | n /= f; 21 | } else { 22 | f++; 23 | } 24 | } 25 | return a; 26 | }; 27 | ``` 28 | 29 | ```js 30 | primeFactors(147); // [3, 7, 7] 31 | ``` 32 | -------------------------------------------------------------------------------- /snippets/prod.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: prod 3 | tags: math,array,intermediate 4 | firstSeen: 2020-10-15T21:56:51+03:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Calculates the product of two or more numbers/arrays. 9 | 10 | - Use `Array.prototype.reduce()` to multiply each value with an accumulator, initialized with a value of `1`. 11 | 12 | ```js 13 | const prod = (...arr) => [...arr].reduce((acc, val) => acc * val, 1); 14 | ``` 15 | 16 | ```js 17 | prod(1, 2, 3, 4); // 24 18 | prod(...[1, 2, 3, 4]); // 24 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/radsToDegrees.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: radsToDegrees 3 | tags: math,beginner 4 | firstSeen: 2018-02-14T12:24:50+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Converts an angle from radians to degrees. 9 | 10 | - Use `Math.PI` and the radian to degree formula to convert the angle from radians to degrees. 11 | 12 | ```js 13 | const radsToDegrees = rad => (rad * 180.0) / Math.PI; 14 | ``` 15 | 16 | ```js 17 | radsToDegrees(Math.PI / 2); // 90 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/randomBoolean.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: randomBoolean 3 | tags: math,random,beginner 4 | firstSeen: 2021-01-20T16:20:08+02:00 5 | lastUpdated: 2021-01-20T16:20:08+02:00 6 | --- 7 | 8 | Generates a random boolean value. 9 | 10 | - Use `Math.random()` to generate a random number and check if it is greater than or equal to `0.5`. 11 | 12 | ```js 13 | const randomBoolean = () => Math.random() >= 0.5; 14 | ``` 15 | 16 | ```js 17 | randomBoolean(); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/randomHexColorCode.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: randomHexColorCode 3 | tags: math,random,beginner 4 | firstSeen: 2017-12-24T14:39:21+02:00 5 | lastUpdated: 2021-01-08T00:23:44+02:00 6 | --- 7 | 8 | Generates a random hexadecimal color code. 9 | 10 | - Use `Math.random()` to generate a random 24-bit (6 * 4bits) hexadecimal number. 11 | - Use bit shifting and then convert it to an hexadecimal string using `Number.prototype.toString(16)`. 12 | 13 | ```js 14 | const randomHexColorCode = () => { 15 | let n = (Math.random() * 0xfffff * 1000000).toString(16); 16 | return '#' + n.slice(0, 6); 17 | }; 18 | ``` 19 | 20 | ```js 21 | randomHexColorCode(); // '#e34155' 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/randomIntArrayInRange.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: randomIntArrayInRange 3 | tags: math,random,intermediate 4 | firstSeen: 2018-01-15T13:25:18+02:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Generates an array of `n` random integers in the specified range. 9 | 10 | - Use `Array.from()` to create an empty array of the specific length. 11 | - Use `Math.random()` to generate random numbers and map them to the desired range, using `Math.floor()` to make them integers. 12 | 13 | ```js 14 | const randomIntArrayInRange = (min, max, n = 1) => 15 | Array.from( 16 | { length: n }, 17 | () => Math.floor(Math.random() * (max - min + 1)) + min 18 | ); 19 | ``` 20 | 21 | ```js 22 | randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ] 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/randomIntegerInRange.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: randomIntegerInRange 3 | tags: math,random,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Generates a random integer in the specified range. 9 | 10 | - Use `Math.random()` to generate a random number and map it to the desired range. 11 | - Use `Math.floor()` to make it an integer. 12 | 13 | ```js 14 | const randomIntegerInRange = (min, max) => 15 | Math.floor(Math.random() * (max - min + 1)) + min; 16 | ``` 17 | 18 | ```js 19 | randomIntegerInRange(0, 5); // 2 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/randomNumberInRange.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: randomNumberInRange 3 | tags: math,random,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Generates a random number in the specified range. 9 | 10 | - Use `Math.random()` to generate a random value, map it to the desired range using multiplication. 11 | 12 | ```js 13 | const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; 14 | ``` 15 | 16 | ```js 17 | randomNumberInRange(2, 10); // 6.0211363285087005 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/rangeGenerator.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: rangeGenerator 3 | tags: function,generator,advanced 4 | firstSeen: 2020-10-11T17:05:55+03:00 5 | lastUpdated: 2020-10-11T17:05:55+03:00 6 | --- 7 | 8 | Creates a generator, that generates all values in the given range using the given step. 9 | 10 | - Use a `while` loop to iterate from `start` to `end`, using `yield` to return each value and then incrementing by `step`. 11 | - Omit the third argument, `step`, to use a default value of `1`. 12 | 13 | ```js 14 | const rangeGenerator = function* (start, end, step = 1) { 15 | let i = start; 16 | while (i < end) { 17 | yield i; 18 | i += step; 19 | } 20 | }; 21 | ``` 22 | 23 | ```js 24 | for (let i of rangeGenerator(6, 10)) console.log(i); 25 | // Logs 6, 7, 8, 9 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/rearg.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: rearg 3 | tags: function,intermediate 4 | firstSeen: 2018-01-28T15:04:21+02:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Creates a function that invokes the provided function with its arguments arranged according to the specified indexes. 9 | 10 | - Use `Array.prototype.map()` to reorder arguments based on `indexes`. 11 | - Use the spread operator (`...`) to pass the transformed arguments to `fn`. 12 | 13 | ```js 14 | const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i])); 15 | ``` 16 | 17 | ```js 18 | var rearged = rearg( 19 | function(a, b, c) { 20 | return [a, b, c]; 21 | }, 22 | [2, 0, 1] 23 | ); 24 | rearged('b', 'c', 'a'); // ['a', 'b', 'c'] 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/redirect.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: redirect 3 | tags: browser,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-20T11:46:23+03:00 6 | --- 7 | 8 | Redirects to a specified URL. 9 | 10 | - Use `Window.location.href` or `Window.location.replace()` to redirect to `url`. 11 | - Pass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`). 12 | 13 | ```js 14 | const redirect = (url, asLink = true) => 15 | asLink ? (window.location.href = url) : window.location.replace(url); 16 | ``` 17 | 18 | ```js 19 | redirect('https://google.com'); 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/reduceSuccessive.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: reduceSuccessive 3 | tags: array,intermediate 4 | firstSeen: 2018-01-24T16:38:08+02:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values. 9 | 10 | - Use `Array.prototype.reduce()` to apply the given function to the given array, storing each new result. 11 | 12 | ```js 13 | const reduceSuccessive = (arr, fn, acc) => 14 | arr.reduce( 15 | (res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), 16 | [acc] 17 | ); 18 | ``` 19 | 20 | ```js 21 | reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); 22 | // [0, 1, 3, 6, 10, 15, 21] 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/reject.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: reject 3 | tags: array,beginner 4 | firstSeen: 2018-04-27T03:17:15+03:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Filters an array's values based on a predicate function, returning only values for which the predicate function returns `false`. 9 | 10 | - Use `Array.prototype.filter()` in combination with the predicate function, `pred`, to return only the values for which it returns `false`. 11 | 12 | ```js 13 | const reject = (pred, array) => array.filter((...args) => !pred(...args)); 14 | ``` 15 | 16 | ```js 17 | reject(x => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5] 18 | reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); 19 | // ['Pear', 'Kiwi'] 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/removeAccents.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: removeAccents 3 | tags: string,beginner 4 | firstSeen: 2020-10-04T02:23:40+03:00 5 | lastUpdated: 2020-10-22T20:24:04+03:00 6 | --- 7 | 8 | Removes accents from strings. 9 | 10 | - Use `String.prototype.normalize()` to convert the string to a normalized Unicode format. 11 | - Use `String.prototype.replace()` to replace diacritical marks in the given Unicode range by empty strings. 12 | 13 | ```js 14 | const removeAccents = str => 15 | str.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); 16 | ``` 17 | 18 | ```js 19 | removeAccents('Antoine de Saint-Exupéry'); // 'Antoine de Saint-Exupery' 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/removeClass.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: removeClass 3 | tags: browser,beginner 4 | firstSeen: 2020-12-30T19:21:15+02:00 5 | lastUpdated: 2020-12-30T19:21:15+02:00 6 | --- 7 | 8 | Removes a class from an HTML element. 9 | 10 | - Use `Element.classList` and `DOMTokenList.remove()` to remove the specified class from the element. 11 | 12 | ```js 13 | const removeClass = (el, className) => el.classList.remove(className); 14 | ``` 15 | 16 | ```js 17 | removeClass(document.querySelector('p.special'), 'special'); 18 | // The paragraph will not have the 'special' class anymore 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/removeElement.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: removeElement 3 | tags: browser,beginner 4 | firstSeen: 2021-01-07T00:20:34+02:00 5 | lastUpdated: 2021-01-07T00:20:34+02:00 6 | --- 7 | 8 | Removes an element from the DOM. 9 | 10 | - Use `Element.parentNode` to get the given element's parent node. 11 | - Use `Element.removeChild()` to remove the given element from its parent node. 12 | 13 | ```js 14 | const removeElement = el => el.parentNode.removeChild(el); 15 | ``` 16 | 17 | ```js 18 | removeElement(document.querySelector('#my-element')); 19 | // Removes #my-element from the DOM 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/removeNonASCII.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: removeNonASCII 3 | tags: string,regexp,intermediate 4 | firstSeen: 2018-01-26T14:00:54+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Removes non-printable ASCII characters. 9 | 10 | - Use `String.prototype.replace()` with a regular expression to remove non-printable ASCII characters. 11 | 12 | ```js 13 | const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); 14 | ``` 15 | 16 | ```js 17 | removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/removeWhitespace.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: removeWhitespace 3 | tags: string,regexp,beginner 4 | firstSeen: 2020-10-13T09:37:17+03:00 5 | lastUpdated: 2020-11-03T21:46:13+02:00 6 | --- 7 | 8 | Returns a string with whitespaces removed. 9 | 10 | - Use `String.prototype.replace()` with a regular expression to replace all occurrences of whitespace characters with an empty string. 11 | 12 | ```js 13 | const removeWhitespace = str => str.replace(/\s+/g, ''); 14 | ``` 15 | 16 | ```js 17 | removeWhitespace('Lorem ipsum.\n Dolor sit amet. '); 18 | // 'Loremipsum.Dolorsitamet.' 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/requireUncached.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: requireUncached 3 | tags: node,advanced 4 | firstSeen: 2020-08-07T15:49:39+03:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Loads a module after removing it from the cache (if exists). 9 | 10 | - Use `delete` to remove the module from the cache (if exists). 11 | - Use `require()` to load the module again. 12 | 13 | ```js 14 | const requireUncached = module => { 15 | delete require.cache[require.resolve(module)]; 16 | return require(module); 17 | }; 18 | ``` 19 | 20 | ```js 21 | const fs = requireUncached('fs'); // 'fs' will be loaded fresh every time 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/reverseNumber.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: reverseNumber 3 | tags: math,string,beginner 4 | firstSeen: 2020-07-17T16:41:28+03:00 5 | lastUpdated: 2020-09-18T21:19:23+03:00 6 | --- 7 | 8 | Reverses a number. 9 | 10 | - Use `Object.prototype.toString()` to convert `n` to a string. 11 | - Use `String.prototype.split('')`, `Array.prototype.reverse()` and `String.prototype.join('')` to get the reversed value of `n` as a string. 12 | - Use `parseFloat()` to convert the string to a number and `Math.sign()` to preserve its sign. 13 | 14 | ```js 15 | const reverseNumber = n => 16 | parseFloat(`${n}`.split('').reverse().join('')) * Math.sign(n); 17 | ``` 18 | 19 | ```js 20 | reverseNumber(981); // 189 21 | reverseNumber(-500); // -5 22 | reverseNumber(73.6); // 6.37 23 | reverseNumber(-5.23); // -32.5 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/reverseString.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: reverseString 3 | tags: string,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-18T14:58:09+03:00 6 | --- 7 | 8 | Reverses a string. 9 | 10 | - Use the spread operator (`...`) and `Array.prototype.reverse()` to reverse the order of the characters in the string. 11 | - Combine characters to get a string using `String.prototype.join('')`. 12 | 13 | ```js 14 | const reverseString = str => [...str].reverse().join(''); 15 | ``` 16 | 17 | ```js 18 | reverseString('foobar'); // 'raboof' 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/round.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: round 3 | tags: math,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Rounds a number to a specified amount of digits. 9 | 10 | - Use `Math.round()` and template literals to round the number to the specified number of digits. 11 | - Omit the second argument, `decimals`, to round to an integer. 12 | 13 | ```js 14 | const round = (n, decimals = 0) => 15 | Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); 16 | ``` 17 | 18 | ```js 19 | round(1.005, 2); // 1.01 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/runPromisesInSeries.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: runPromisesInSeries 3 | tags: function,promise,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Runs an array of promises in series. 9 | 10 | - Use `Array.prototype.reduce()` to create a promise chain, where each promise returns the next promise when resolved. 11 | 12 | ```js 13 | const runPromisesInSeries = ps => 14 | ps.reduce((p, next) => p.then(next), Promise.resolve()); 15 | ``` 16 | 17 | ```js 18 | const delay = d => new Promise(r => setTimeout(r, d)); 19 | runPromisesInSeries([() => delay(1000), () => delay(2000)]); 20 | // Executes each promise sequentially, taking a total of 3 seconds to complete 21 | ``` 22 | -------------------------------------------------------------------------------- /snippets/sample.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: sample 3 | tags: array,string,random,beginner 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Gets a random element from an array. 9 | 10 | - Use `Math.random()` to generate a random number. 11 | - Multiply it by `Array.prototype.length` and round it off to the nearest whole number using `Math.floor()`. 12 | - This method also works with strings. 13 | 14 | ```js 15 | const sample = arr => arr[Math.floor(Math.random() * arr.length)]; 16 | ``` 17 | 18 | ```js 19 | sample([3, 7, 9, 11]); // 9 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/scrollToTop.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: scrollToTop 3 | tags: browser,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Smooth-scrolls to the top of the page. 9 | 10 | - Get distance from top using `Document.documentElement` or `Document.body` and `Element.scrollTop`. 11 | - Scroll by a fraction of the distance from the top. 12 | - Use `Window.requestAnimationFrame()` to animate the scrolling. 13 | 14 | ```js 15 | const scrollToTop = () => { 16 | const c = document.documentElement.scrollTop || document.body.scrollTop; 17 | if (c > 0) { 18 | window.requestAnimationFrame(scrollToTop); 19 | window.scrollTo(0, c - c / 8); 20 | } 21 | }; 22 | ``` 23 | 24 | ```js 25 | scrollToTop(); // Smooth-scrolls to the top of the page 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/sdbm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: sdbm 3 | tags: math,intermediate 4 | firstSeen: 2017-12-27T17:12:34+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Hashes the input string into a whole number. 9 | 10 | - Use `String.prototype.split('')` and `Array.prototype.reduce()` to create a hash of the input string, utilizing bit shifting. 11 | 12 | ```js 13 | const sdbm = str => { 14 | let arr = str.split(''); 15 | return arr.reduce( 16 | (hashCode, currentVal) => 17 | (hashCode = 18 | currentVal.charCodeAt(0) + 19 | (hashCode << 6) + 20 | (hashCode << 16) - 21 | hashCode), 22 | 0 23 | ); 24 | }; 25 | ``` 26 | 27 | ```js 28 | sdbm('name'); // -3521204949 29 | ``` 30 | -------------------------------------------------------------------------------- /snippets/serializeCookie.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: serializeCookie 3 | tags: browser,string,intermediate 4 | firstSeen: 2018-01-13T14:19:21+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Serializes a cookie name-value pair into a Set-Cookie header string. 9 | 10 | - Use template literals and `encodeURIComponent()` to create the appropriate string. 11 | 12 | ```js 13 | const serializeCookie = (name, val) => 14 | `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; 15 | ``` 16 | 17 | ```js 18 | serializeCookie('foo', 'bar'); // 'foo=bar' 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/setStyle.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: setStyle 3 | tags: browser,beginner 4 | firstSeen: 2017-12-29T00:08:17+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Sets the value of a CSS rule for the specified HTML element. 9 | 10 | - Use `ElementCSSInlineStyle.style` to set the value of the CSS `rule` for the specified element to `val`. 11 | 12 | ```js 13 | const setStyle = (el, rule, val) => (el.style[rule] = val); 14 | ``` 15 | 16 | ```js 17 | setStyle(document.querySelector('p'), 'font-size', '20px'); 18 | // The first

    element on the page will have a font-size of 20px 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/shallowClone.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: shallowClone 3 | tags: object,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Creates a shallow clone of an object. 9 | 10 | - Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original. 11 | 12 | ```js 13 | const shallowClone = obj => Object.assign({}, obj); 14 | ``` 15 | 16 | ```js 17 | const a = { x: true, y: 1 }; 18 | const b = shallowClone(a); // a !== b 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/show.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: show 3 | tags: browser,css,beginner 4 | firstSeen: 2017-12-28T23:33:21+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Shows all the elements specified. 9 | 10 | - Use the spread operator (`...`) and `Array.prototype.forEach()` to clear the `display` property for each element specified. 11 | 12 | ```js 13 | const show = (...el) => [...el].forEach(e => (e.style.display = '')); 14 | ``` 15 | 16 | ```js 17 | show(...document.querySelectorAll('img')); 18 | // Shows all elements on the page 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/shuffle.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: shuffle 3 | tags: array,random,algorithm,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2021-02-20T21:17:38+02:00 6 | --- 7 | 8 | Randomizes the order of the values of an array, returning a new array. 9 | 10 | - Use the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Fisher_and_Yates'_original_method) to reorder the elements of the array. 11 | 12 | ```js 13 | const shuffle = ([...arr]) => { 14 | let m = arr.length; 15 | while (m) { 16 | const i = Math.floor(Math.random() * m--); 17 | [arr[m], arr[i]] = [arr[i], arr[m]]; 18 | } 19 | return arr; 20 | }; 21 | ``` 22 | 23 | ```js 24 | const foo = [1, 2, 3]; 25 | shuffle(foo); // [2, 3, 1], foo = [1, 2, 3] 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/similarity.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: similarity 3 | tags: array,math,beginner 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Returns an array of elements that appear in both arrays. 9 | 10 | - Use `Array.prototype.includes()` to determine values that are not part of `values`. 11 | - Use `Array.prototype.filter()` to remove them. 12 | 13 | ```js 14 | const similarity = (arr, values) => arr.filter(v => values.includes(v)); 15 | ``` 16 | 17 | ```js 18 | similarity([1, 2, 3], [1, 2, 4]); // [1, 2] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/sleep.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: sleep 3 | tags: function,promise,intermediate 4 | firstSeen: 2017-12-13T22:40:56+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Delays the execution of an asynchronous function. 9 | 10 | - Delay executing part of an `async` function, by putting it to sleep, returning a `new Promise()`. 11 | 12 | ```js 13 | const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); 14 | ``` 15 | 16 | ```js 17 | async function sleepyWork() { 18 | console.log("I'm going to sleep for 1 second."); 19 | await sleep(1000); 20 | console.log('I woke up after 1 second.'); 21 | } 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/slugify.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: slugify 3 | tags: string,regexp,intermediate 4 | firstSeen: 2020-10-04T09:45:43+03:00 5 | lastUpdated: 2020-10-04T10:36:38+03:00 6 | --- 7 | 8 | Converts a string to a URL-friendly slug. 9 | 10 | - Use `String.prototype.toLowerCase()` and `String.prototype.trim()` to normalize the string. 11 | - Use `String.prototype.replace()` to replace spaces, dashes and underscores with `-` and remove special characters. 12 | 13 | ```js 14 | const slugify = str => 15 | str 16 | .toLowerCase() 17 | .trim() 18 | .replace(/[^\w\s-]/g, '') 19 | .replace(/[\s_-]+/g, '-') 20 | .replace(/^-+|-+$/g, ''); 21 | ``` 22 | 23 | ```js 24 | slugify('Hello World!'); // 'hello-world' 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/smoothScroll.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: smoothScroll 3 | tags: browser,css,intermediate 4 | firstSeen: 2018-03-02T18:22:51+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Smoothly scrolls the element on which it's called into the visible area of the browser window. 9 | 10 | - Use `Element.scrollIntoView()` to scroll the element. 11 | - Use `{ behavior: 'smooth' }` to scroll smoothly. 12 | 13 | ```js 14 | const smoothScroll = element => 15 | document.querySelector(element).scrollIntoView({ 16 | behavior: 'smooth' 17 | }); 18 | ``` 19 | 20 | ```js 21 | smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar 22 | smoothScroll('.fooBar'); 23 | // scrolls smoothly to the first element with a class of fooBar 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/sortCharactersInString.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: sortCharactersInString 3 | tags: string,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Alphabetically sorts the characters in a string. 9 | 10 | - Use the spread operator (`...`), `Array.prototype.sort()` and `String.prototype.localeCompare()` to sort the characters in `str`. 11 | - Recombine using `String.prototype.join('')`. 12 | 13 | ```js 14 | const sortCharactersInString = str => 15 | [...str].sort((a, b) => a.localeCompare(b)).join(''); 16 | ``` 17 | 18 | ```js 19 | sortCharactersInString('cabbage'); // 'aabbceg' 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/splitLines.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: splitLines 3 | tags: string,regexp,beginner 4 | firstSeen: 2017-12-29T12:58:58+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Splits a multiline string into an array of lines. 9 | 10 | - Use `String.prototype.split()` and a regular expression to match line breaks and create an array. 11 | 12 | ```js 13 | const splitLines = str => str.split(/\r?\n/); 14 | ``` 15 | 16 | ```js 17 | splitLines('This\nis a\nmultiline\nstring.\n'); 18 | // ['This', 'is a', 'multiline', 'string.' , ''] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/spreadOver.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: spreadOver 3 | tags: function,intermediate 4 | firstSeen: 2017-12-22T04:33:57+02:00 5 | lastUpdated: 2021-06-13T13:50:25+03:00 6 | --- 7 | 8 | Takes a variadic function and returns a function that accepts an array of arguments. 9 | 10 | - Use a closure and the spread operator (`...`) to map the array of arguments to the inputs of the function. 11 | 12 | ```js 13 | const spreadOver = fn => argsArr => fn(...argsArr); 14 | ``` 15 | 16 | ```js 17 | const arrayMax = spreadOver(Math.max); 18 | arrayMax([1, 2, 3]); // 3 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/stripHTMLTags.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: stripHTMLTags 3 | tags: string,regexp,beginner 4 | firstSeen: 2018-01-26T14:17:29+02:00 5 | lastUpdated: 2020-09-15T16:28:04+03:00 6 | --- 7 | 8 | Removes HTML/XML tags from string. 9 | 10 | - Use a regular expression to remove HTML/XML tags from a string. 11 | 12 | ```js 13 | const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); 14 | ``` 15 | 16 | ```js 17 | stripHTMLTags('

    lorem ipsum

    '); // 'lorem ipsum' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/subSet.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: subSet 3 | tags: array,intermediate 4 | firstSeen: 2020-10-11T11:53:08+03:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Checks if the first iterable is a subset of the second one, excluding duplicate values. 9 | 10 | - Use the `new Set()` constructor to create a new `Set` object from each iterable. 11 | - Use `Array.prototype.every()` and `Set.prototype.has()` to check that each value in the first iterable is contained in the second one. 12 | 13 | ```js 14 | const subSet = (a, b) => { 15 | const sA = new Set(a), sB = new Set(b); 16 | return [...sA].every(v => sB.has(v)); 17 | }; 18 | ``` 19 | 20 | ```js 21 | subSet(new Set([1, 2]), new Set([1, 2, 3, 4])); // true 22 | subSet(new Set([1, 5]), new Set([1, 2, 3, 4])); // false 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/sum.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: sum 3 | tags: math,array,beginner 4 | firstSeen: 2017-12-29T13:29:49+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Calculates the sum of two or more numbers/arrays. 9 | 10 | - Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`. 11 | 12 | ```js 13 | const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); 14 | ``` 15 | 16 | ```js 17 | sum(1, 2, 3, 4); // 10 18 | sum(...[1, 2, 3, 4]); // 10 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/sumBy.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: sumBy 3 | tags: math,array,intermediate 4 | firstSeen: 2018-01-11T12:25:54+02:00 5 | lastUpdated: 2020-11-03T22:11:18+02:00 6 | --- 7 | 8 | Calculates the sum of an array, after mapping each element to a value using the provided function. 9 | 10 | - Use `Array.prototype.map()` to map each element to the value returned by `fn`. 11 | - Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`. 12 | 13 | ```js 14 | const sumBy = (arr, fn) => 15 | arr 16 | .map(typeof fn === 'function' ? fn : val => val[fn]) 17 | .reduce((acc, val) => acc + val, 0); 18 | ``` 19 | 20 | ```js 21 | sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], x => x.n); // 20 22 | sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/sumN.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: sumN 3 | tags: math,beginner 4 | firstSeen: 2020-10-08T16:52:55+03:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Sums all the numbers between `1` and `n`. 9 | 10 | - Use the formula `(n * (n + 1)) / 2` to get the sum of all the numbers between 1 and `n`. 11 | 12 | ```js 13 | const sumN = n => (n * (n + 1)) / 2; 14 | ``` 15 | 16 | ```js 17 | sumN(100); // 5050 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/superSet.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: superSet 3 | tags: array,intermediate 4 | firstSeen: 2020-10-11T11:53:19+03:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Checks if the first iterable is a superset of the second one, excluding duplicate values. 9 | 10 | - Use the `new Set()` constructor to create a new `Set` object from each iterable. 11 | - Use `Array.prototype.every()` and `Set.prototype.has()` to check that each value in the second iterable is contained in the first one. 12 | 13 | ```js 14 | const superSet = (a, b) => { 15 | const sA = new Set(a), sB = new Set(b); 16 | return [...sB].every(v => sA.has(v)); 17 | }; 18 | ``` 19 | 20 | ```js 21 | superSet(new Set([1, 2, 3, 4]), new Set([1, 2])); // true 22 | superSet(new Set([1, 2, 3, 4]), new Set([1, 5])); // false 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/supportsTouchEvents.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: supportsTouchEvents 3 | tags: browser,beginner 4 | firstSeen: 2020-05-04T12:57:23+03:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Checks if touch events are supported. 9 | 10 | - Check if `'ontouchstart'` exists in `window`. 11 | 12 | ```js 13 | const supportsTouchEvents = () => 14 | window && 'ontouchstart' in window; 15 | ``` 16 | 17 | ```js 18 | supportsTouchEvents(); // true 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/symbolizeKeys.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: symbolizeKeys 3 | tags: object,advanced 4 | firstSeen: 2021-08-01T05:00:00-04:00 5 | --- 6 | 7 | Creates a new object, converting each key to a `Symbol`. 8 | 9 | - Use `Object.keys()` to get the keys of `obj`. 10 | - Use `Array.prototype.reduce()` and `Symbol()` to create a new object where each key is converted to a `Symbol`. 11 | 12 | ```js 13 | const symbolizeKeys = obj => 14 | Object.keys(obj).reduce( 15 | (acc, key) => ({ ...acc, [Symbol(key)]: obj[key] }), 16 | {} 17 | ); 18 | ``` 19 | 20 | ```js 21 | symbolizeKeys({ id: 10, name: 'apple' }); 22 | // { [Symbol(id)]: 10, [Symbol(name)]: 'apple' } 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/symmetricDifferenceWith.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: symmetricDifferenceWith 3 | tags: array,intermediate 4 | firstSeen: 2018-01-24T11:59:02+02:00 5 | lastUpdated: 2020-10-18T14:58:09+03:00 6 | --- 7 | 8 | Returns the symmetric difference between two arrays, using a provided function as a comparator. 9 | 10 | - Use `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values. 11 | 12 | ```js 13 | const symmetricDifferenceWith = (arr, val, comp) => [ 14 | ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1), 15 | ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1) 16 | ]; 17 | ``` 18 | 19 | ```js 20 | symmetricDifferenceWith( 21 | [1, 1.2, 1.5, 3, 0], 22 | [1.9, 3, 0, 3.9], 23 | (a, b) => Math.round(a) === Math.round(b) 24 | ); // [1, 1.2, 3.9] 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/tail.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: tail 3 | tags: array,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Returns all elements in an array except for the first one. 9 | 10 | - Return `Array.prototype.slice(1)` if `Array.prototype.length` is more than `1`, otherwise, return the whole array. 11 | 12 | ```js 13 | const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); 14 | ``` 15 | 16 | ```js 17 | tail([1, 2, 3]); // [2, 3] 18 | tail([1]); // [1] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/take.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: take 3 | tags: array,beginner 4 | firstSeen: 2017-12-14T11:35:14+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Creates an array with `n` elements removed from the beginning. 9 | 10 | - Use `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the beginning. 11 | 12 | ```js 13 | const take = (arr, n = 1) => arr.slice(0, n); 14 | ``` 15 | 16 | ```js 17 | take([1, 2, 3], 5); // [1, 2, 3] 18 | take([1, 2, 3], 0); // [] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/takeRight.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: takeRight 3 | tags: array,intermediate 4 | firstSeen: 2017-12-15T02:00:10+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Creates an array with `n` elements removed from the end. 9 | 10 | - Use `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the end. 11 | 12 | ```js 13 | const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); 14 | ``` 15 | 16 | ```js 17 | takeRight([1, 2, 3], 2); // [ 2, 3 ] 18 | takeRight([1, 2, 3]); // [3] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/timeTaken.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: timeTaken 3 | tags: function,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Measures the time it takes for a function to execute. 9 | 10 | - Use `Console.time()` and `Console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute. 11 | 12 | ```js 13 | const timeTaken = callback => { 14 | console.time('timeTaken'); 15 | const r = callback(); 16 | console.timeEnd('timeTaken'); 17 | return r; 18 | }; 19 | ``` 20 | 21 | ```js 22 | timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/times.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: times 3 | tags: function,intermediate 4 | firstSeen: 2018-01-24T13:50:49+02:00 5 | lastUpdated: 2020-10-20T11:21:07+03:00 6 | --- 7 | 8 | Iterates over a callback `n` times 9 | 10 | - Use `Function.prototype.call()` to call `fn` `n` times or until it returns `false`. 11 | - Omit the last argument, `context`, to use an `undefined` object (or the global object in non-strict mode). 12 | 13 | ```js 14 | const times = (n, fn, context = undefined) => { 15 | let i = 0; 16 | while (fn.call(context, i) !== false && ++i < n) {} 17 | }; 18 | ``` 19 | 20 | ```js 21 | var output = ''; 22 | times(5, i => (output += i)); 23 | console.log(output); // 01234 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/toCharArray.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: toCharArray 3 | tags: string,beginner 4 | firstSeen: 2020-10-08T15:17:22+03:00 5 | lastUpdated: 2020-10-08T15:17:22+03:00 6 | --- 7 | 8 | Converts a string to an array of characters. 9 | 10 | - Use the spread operator (`...`) to convert the string into an array of characters. 11 | 12 | ```js 13 | const toCharArray = s => [...s]; 14 | ``` 15 | 16 | ```js 17 | toCharArray('hello'); // ['h', 'e', 'l', 'l', 'o'] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/toDecimalMark.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: toDecimalMark 3 | tags: math,beginner 4 | firstSeen: 2017-12-21T16:29:51+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Converts a number to a decimal mark formatted string. 9 | 10 | - Use `Number.prototype.toLocaleString()` to convert the number to decimal mark format. 11 | 12 | ```js 13 | const toDecimalMark = num => num.toLocaleString('en-US'); 14 | ``` 15 | 16 | ```js 17 | toDecimalMark(12305030388.9087); // '12,305,030,388.909' 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/toHSLArray.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: toHSLArray 3 | tags: string,browser,regexp,beginner 4 | firstSeen: 2020-10-16T21:46:29+03:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Converts an `hsl()` color string to an array of values. 9 | 10 | - Use `String.prototype.match()` to get an array of 3 string with the numeric values. 11 | - Use `Array.prototype.map()` in combination with `Number` to convert them into an array of numeric values. 12 | 13 | ```js 14 | const toHSLArray = hslStr => hslStr.match(/\d+/g).map(Number); 15 | ``` 16 | 17 | ```js 18 | toHSLArray('hsl(50, 10%, 10%)'); // [50, 10, 10] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/toRGBArray.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: toRGBArray 3 | tags: string,browser,regexp,beginner 4 | firstSeen: 2020-10-14T20:36:18+03:00 5 | lastUpdated: 2021-06-13T13:50:25+03:00 6 | --- 7 | 8 | Converts an `rgb()` color string to an array of values. 9 | 10 | - Use `String.prototype.match()` to get an array of 3 string with the numeric values. 11 | - Use `Array.prototype.map()` in combination with `Number` to convert them into an array of numeric values. 12 | 13 | ```js 14 | const toRGBArray = rgbStr => rgbStr.match(/\d+/g).map(Number); 15 | ``` 16 | 17 | ```js 18 | toRGBArray('rgb(255, 12, 0)'); // [255, 12, 0] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/toSafeInteger.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: toSafeInteger 3 | tags: math,beginner 4 | firstSeen: 2018-01-08T17:12:46+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Converts a value to a safe integer. 9 | 10 | - Use `Math.max()` and `Math.min()` to find the closest safe value. 11 | - Use `Math.round()` to convert to an integer. 12 | 13 | ```js 14 | const toSafeInteger = num => 15 | Math.round( 16 | Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER) 17 | ); 18 | ``` 19 | 20 | ```js 21 | toSafeInteger('3.2'); // 3 22 | toSafeInteger(Infinity); // 9007199254740991 23 | ``` 24 | -------------------------------------------------------------------------------- /snippets/toggleClass.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: toggleClass 3 | tags: browser,beginner 4 | firstSeen: 2017-12-28T23:46:33+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Toggles a class for an HTML element. 9 | 10 | - Use `Element.classList` and `DOMTokenList.toggle()` to toggle the specified class for the element. 11 | 12 | ```js 13 | const toggleClass = (el, className) => el.classList.toggle(className); 14 | ``` 15 | 16 | ```js 17 | toggleClass(document.querySelector('p.special'), 'special'); 18 | // The paragraph will not have the 'special' class anymore 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/tomorrow.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: tomorrow 3 | tags: date,intermediate 4 | firstSeen: 2017-12-26T18:56:24+02:00 5 | lastUpdated: 2020-10-22T20:24:30+03:00 6 | --- 7 | 8 | Results in a string representation of tomorrow's date. 9 | 10 | - Use `new Date()` to get the current date. 11 | - Increment it by one using `Date.prototype.getDate()` and set the value to the result using `Date.prototype.setDate()`. 12 | - Use `Date.prototype.toISOString()` to return a string in `yyyy-mm-dd` format. 13 | 14 | ```js 15 | const tomorrow = () => { 16 | let d = new Date(); 17 | d.setDate(d.getDate() + 1); 18 | return d.toISOString().split('T')[0]; 19 | }; 20 | ``` 21 | 22 | ```js 23 | tomorrow(); // 2018-10-19 (if current date is 2018-10-18) 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/transform.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: transform 3 | tags: object,intermediate 4 | firstSeen: 2018-01-12T13:55:49+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Applies a function against an accumulator and each key in the object (from left to right). 9 | 10 | - Use `Object.keys()` to iterate over each key in the object. 11 | - Use `Array.prototype.reduce()` to apply the specified function against the given accumulator. 12 | 13 | ```js 14 | const transform = (obj, fn, acc) => 15 | Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); 16 | ``` 17 | 18 | ```js 19 | transform( 20 | { a: 1, b: 2, c: 1 }, 21 | (r, v, k) => { 22 | (r[v] || (r[v] = [])).push(k); 23 | return r; 24 | }, 25 | {} 26 | ); // { '1': ['a', 'c'], '2': ['b'] } 27 | ``` 28 | -------------------------------------------------------------------------------- /snippets/truncateString.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: truncateString 3 | tags: string,beginner 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-21T21:17:45+03:00 6 | --- 7 | 8 | Truncates a string up to a specified length. 9 | 10 | - Determine if `String.prototype.length` is greater than `num`. 11 | - Return the string truncated to the desired length, with `'...'` appended to the end or the original string. 12 | 13 | ```js 14 | const truncateString = (str, num) => 15 | str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; 16 | ``` 17 | 18 | ```js 19 | truncateString('boomerang', 7); // 'boom...' 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/truthCheckCollection.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: truthCheckCollection 3 | tags: object,logic,array,intermediate 4 | firstSeen: 2017-12-18T13:05:21+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Checks if the predicate function is truthy for all elements of a collection. 9 | 10 | - Use `Array.prototype.every()` to check if each passed object has the specified property and if it returns a truthy value. 11 | 12 | ```js 13 | const truthCheckCollection = (collection, pre) => 14 | collection.every(obj => obj[pre]); 15 | ``` 16 | 17 | ```js 18 | truthCheckCollection( 19 | [ 20 | { user: 'Tinky-Winky', sex: 'male' }, 21 | { user: 'Dipsy', sex: 'male' }, 22 | ], 23 | 'sex' 24 | ); // true 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/unary.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: unary 3 | tags: function,beginner 4 | firstSeen: 2018-01-24T13:22:32+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Creates a function that accepts up to one argument, ignoring any additional arguments. 9 | 10 | - Call the provided function, `fn`, with just the first argument supplied. 11 | 12 | ```js 13 | const unary = fn => val => fn(val); 14 | ``` 15 | 16 | ```js 17 | ['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/union.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: union 3 | tags: array,beginner 4 | firstSeen: 2017-12-17T16:41:31+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Returns every element that exists in any of the two arrays at least once. 9 | 10 | - Create a `new Set()` with all values of `a` and `b` and convert it to an array. 11 | 12 | ```js 13 | const union = (a, b) => Array.from(new Set([...a, ...b])); 14 | ``` 15 | 16 | ```js 17 | union([1, 2, 3], [4, 3, 2]); // [1, 2, 3, 4] 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/unionWith.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: unionWith 3 | tags: array,intermediate 4 | firstSeen: 2018-01-24T12:19:41+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Returns every element that exists in any of the two arrays at least once, using a provided comparator function. 9 | 10 | - Create a `new Set()` with all values of `a` and values in `b` for which the comparator finds no matches in `a`, using `Array.prototype.findIndex()`. 11 | 12 | ```js 13 | const unionWith = (a, b, comp) => 14 | Array.from( 15 | new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]) 16 | ); 17 | ``` 18 | 19 | ```js 20 | unionWith( 21 | [1, 1.2, 1.5, 3, 0], 22 | [1.9, 3, 0, 3.9], 23 | (a, b) => Math.round(a) === Math.round(b) 24 | ); 25 | // [1, 1.2, 1.5, 3, 0, 3.9] 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/uniqueElements.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: uniqueElements 3 | tags: array,beginner 4 | firstSeen: 2018-01-17T19:02:49+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Finds all unique values in an array. 9 | 10 | - Create a `new Set()` from the given array to discard duplicated values. 11 | - Use the spread operator (`...`) to convert it back to an array. 12 | 13 | ```js 14 | const uniqueElements = arr => [...new Set(arr)]; 15 | ``` 16 | 17 | ```js 18 | uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/untildify.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: untildify 3 | tags: node,string,beginner 4 | firstSeen: 2018-01-01T17:43:18+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Converts a tilde path to an absolute path. 9 | 10 | - Use `String.prototype.replace()` with a regular expression and `os.homedir()` to replace the `~` in the start of the path with the home directory. 11 | 12 | ```js 13 | const untildify = str => 14 | str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); 15 | ``` 16 | 17 | ```js 18 | untildify('~/node'); // '/Users/aUser/node' 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/validateNumber.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: validateNumber 3 | tags: math,intermediate 4 | firstSeen: 2017-12-17T17:55:51+02:00 5 | lastUpdated: 2020-10-22T20:23:26+03:00 6 | --- 7 | 8 | Checks if the given value is a number. 9 | 10 | - Use `parseFloat()` to try to convert `n` to a number. 11 | - Use `!Number.isNaN()` to check if `num` is a number. 12 | - Use `Number.isFinite()` to check if `num` is finite. 13 | - Use `Number()` and the loose equality operator (`==`) to check if the coercion holds. 14 | 15 | ```js 16 | const validateNumber = n => { 17 | const num = parseFloat(n); 18 | return !Number.isNaN(num) && Number.isFinite(num) && Number(n) == n; 19 | } 20 | ``` 21 | 22 | ```js 23 | validateNumber('10'); // true 24 | validateNumber('a'); // false 25 | ``` 26 | -------------------------------------------------------------------------------- /snippets/vectorDistance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: vectorDistance 3 | tags: math,algorithm,beginner 4 | firstSeen: 2019-02-23T19:13:48+02:00 5 | lastUpdated: 2020-12-28T13:49:24+02:00 6 | --- 7 | 8 | Calculates the distance between two vectors. 9 | 10 | - Use `Array.prototype.reduce()`, `Math.pow()` and `Math.sqrt()` to calculate the Euclidean distance between two vectors. 11 | 12 | ```js 13 | const vectorDistance = (x, y) => 14 | Math.sqrt(x.reduce((acc, val, i) => acc + Math.pow(val - y[i], 2), 0)); 15 | ``` 16 | 17 | ```js 18 | vectorDistance([10, 0, 5], [20, 0, 10]); // 11.180339887498949 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/when.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: when 3 | tags: function,logic,beginner 4 | firstSeen: 2018-04-19T03:45:32+03:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Returns a function that takes one argument and runs a callback if it's truthy or returns it if falsy. 9 | 10 | - Return a function expecting a single value, `x`, that returns the appropriate value based on `pred`. 11 | 12 | ```js 13 | const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); 14 | ``` 15 | 16 | ```js 17 | const doubleEvenNumbers = when(x => x % 2 === 0, x => x * 2); 18 | doubleEvenNumbers(2); // 4 19 | doubleEvenNumbers(1); // 1 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/without.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: without 3 | tags: array,beginner 4 | firstSeen: 2017-12-15T09:35:30+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Filters out the elements of an array that have one of the specified values. 9 | 10 | - Use `Array.prototype.includes()` to find values to exclude. 11 | - Use `Array.prototype.filter()` to create an array excluding them. 12 | 13 | ```js 14 | const without = (arr, ...args) => arr.filter(v => !args.includes(v)); 15 | ``` 16 | 17 | ```js 18 | without([2, 1, 2, 3], 1, 2); // [3] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/words.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: words 3 | tags: string,regexp,intermediate 4 | firstSeen: 2017-12-21T14:50:57+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Converts a given string into an array of words. 9 | 10 | - Use `String.prototype.split()` with a supplied `pattern` (defaults to non-alpha as a regexp) to convert to an array of strings. 11 | - Use `Array.prototype.filter()` to remove any empty strings. 12 | - Omit the second argument, `pattern`, to use the default regexp. 13 | 14 | ```js 15 | const words = (str, pattern = /[^a-zA-Z-]+/) => 16 | str.split(pattern).filter(Boolean); 17 | ``` 18 | 19 | ```js 20 | words('I love javaScript!!'); // ['I', 'love', 'javaScript'] 21 | words('python, javaScript & coffee'); // ['python', 'javaScript', 'coffee'] 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/xProd.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: xProd 3 | tags: array,math,intermediate 4 | firstSeen: 2018-01-24T15:55:03+02:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Creates a new array out of the two supplied by creating each possible pair from the arrays. 9 | 10 | - Use `Array.prototype.reduce()`, `Array.prototype.map()` and `Array.prototype.concat()` to produce every possible pair from the elements of the two arrays. 11 | 12 | ```js 13 | const xProd = (a, b) => 14 | a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []); 15 | ``` 16 | 17 | ```js 18 | xProd([1, 2], ['a', 'b']); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] 19 | ``` 20 | -------------------------------------------------------------------------------- /snippets/xor.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: xor 3 | tags: math,logic,beginner 4 | unlisted: true 5 | firstSeen: 2020-10-05T21:19:21+03:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Checks if only one of the arguments is `true`. 10 | 11 | - Use the logical or (`||`), and (`&&`) and not (`!`) operators on the two given values to create the logical xor. 12 | 13 | ```js 14 | const xor = (a, b) => (( a || b ) && !( a && b )); 15 | ``` 16 | 17 | ```js 18 | xor(true, true); // false 19 | xor(true, false); // true 20 | xor(false, true); // true 21 | xor(false, false); // false 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/yesNo.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: yesNo 3 | tags: string,regexp,intermediate 4 | unlisted: true 5 | firstSeen: 2017-12-30T18:35:54+02:00 6 | lastUpdated: 2021-01-04T13:04:15+02:00 7 | --- 8 | 9 | Returns `true` if the string is `y`/`yes` or `false` if the string is `n`/`no`. 10 | 11 | - Use `RegExp.prototype.test()` to check if the string evaluates to `y/yes` or `n/no`. 12 | - Omit the second argument, `def` to set the default answer as `no`. 13 | 14 | ```js 15 | const yesNo = (val, def = false) => 16 | /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; 17 | ``` 18 | 19 | ```js 20 | yesNo('Y'); // true 21 | yesNo('yes'); // true 22 | yesNo('No'); // false 23 | yesNo('Foo', true); // true 24 | ``` 25 | -------------------------------------------------------------------------------- /snippets/yesterday.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: yesterday 3 | tags: date,intermediate 4 | firstSeen: 2019-07-19T10:57:21+03:00 5 | lastUpdated: 2020-10-22T20:24:44+03:00 6 | --- 7 | 8 | Results in a string representation of yesterday's date. 9 | 10 | - Use `new Date()` to get the current date. 11 | - Decrement it by one using `Date.prototype.getDate()` and set the value to the result using `Date.prototype.setDate()`. 12 | - Use `Date.prototype.toISOString()` to return a string in `yyyy-mm-dd` format. 13 | 14 | ```js 15 | const yesterday = () => { 16 | let d = new Date(); 17 | d.setDate(d.getDate() - 1); 18 | return d.toISOString().split('T')[0]; 19 | }; 20 | ``` 21 | 22 | ```js 23 | yesterday(); // 2018-10-17 (if current date is 2018-10-18) 24 | ``` 25 | --------------------------------------------------------------------------------