Snippets
JavaScript snippets
Small, self-contained JavaScript functions. Each one shows the implementation, a short explanation of how it works and an example call.
- accumulate Creates an array of partial sums. Use Array.prototype.reduce(), initialized with an empty array accumulator to …
- addClass Adds a class to an HTML element. Use Element.classList and DOMTokenList.add() to add the specified class to …
- addDaysToDate Calculates the date of n days from the given date, returning its string representation. Use new Date() to …
- addEventListenerAll Attaches an event listener to all the provided targets. Use Array.prototype.forEach() and …
- addMinutesToDate Calculates the date of n minutes from the given date, returning its string representation. Use new Date() to …
- addMultipleListeners Adds multiple event listeners with the same handler to an element. Use Array.prototype.forEach() and …
- addStyles Adds the provided styles to the given element. Use Object.assign() and ElementCSSInlineStyle.style to merge …
- addWeekDays Calculates the date after adding the given number of business days. Use Array.from() to construct an array …
- all Checks if the provided predicate function returns true for all elements in a collection. Use …
- allEqual Checks if all elements in an array are equal. Use Array.prototype.every() to check if all the elements of the …
- allEqualBy Checks if all elements in an array are equal, based on the provided mapping function. Apply fn to the first …
- allUnique Checks if all elements in an array are unique. Create a new Set from the mapped values to keep only unique …
- allUniqueBy Checks if all elements in an array are unique, based on the provided mapping function. Use …
- and Checks if both arguments are true. Use the logical and (&&) operator on the two given values. const …
- any Checks if the provided predicate function returns true for at least one element in a collection. Use …
- aperture Creates an array of n-tuples of consecutive elements. Use Array.prototype.slice() and Array.prototype.map() to …
- approximatelyEqual Checks if two numbers are approximately equal to each other. Use Math.abs() to compare the absolute difference …
- arithmeticProgression Creates an array of numbers in the arithmetic progression, starting with the given positive integer and up to …
- arrayToCSV Converts a 2D array to a comma-separated values (CSV) string. Use Array.prototype.map() and …
- arrayToHTMLList Converts the given array elements into <li> tags and appends them to the list of the given id. Use …
- ary Creates a function that accepts up to n arguments, ignoring any additional arguments. Call the provided …
- assertValidKeys Validates all keys in an object match the given keys. Use Object.keys() to get the keys of the given object, …
- atob Decodes a string of data which has been encoded using base-64 encoding. Create a Buffer for the given string …
- attempt Attempts to invoke a function with the provided arguments, returning either the result or the caught error …
- average Calculates the average of two or more numbers. Use Array.prototype.reduce() to add each value to an …
- averageBy Calculates the average of an array, after mapping each element to a value using the provided function. Use …
- bifurcate Splits values into two groups, based on the result of the given filter array. Use Array.prototype.reduce() and …
- bifurcateBy Splits values into two groups, based on the result of the given filtering function. Use …
- binary Creates a function that accepts up to two arguments, ignoring any additional arguments. Call the provided …
- binarySearch Finds the index of a given element in a sorted array using the binary search algorithm. Declare the left and …
- bind Creates a function that invokes fn with a given context, optionally prepending any additional supplied …
- bindAll Binds methods of an object to the object itself, overwriting the existing method. Use …
- bindKey Creates a function that invokes the method at a given key of an object, optionally prepending any additional …
- binomialCoefficient Calculates the number of ways to choose k items from n items without repetition and without order. Use …
- both Checks if both of the given functions return true for a given set of arguments. Use the logical and …
- bottomVisible Checks if the bottom of the page is visible. Use scrollY, scrollHeight and clientHeight to determine if the …
- btoa Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated …
- bubbleSort Sorts an array of numbers, using the bubble sort algorithm. Declare a variable, swapped, that indicates if any …
- bucketSort Sorts an array of numbers, using the bucket sort algorithm. Use Math.min(), Math.max() and the spread operator …
- byteSize Returns the length of a string in bytes. Convert a given string to a Blob Object. Use Blob.size to get the …
- caesarCipher Encrypts or decrypts a given string using the Caesar cipher. Use the modulo (%) operator and the ternary …
- call Given a key and a set of arguments, call them when given a context. Use a closure to call key with args for …
- capitalize Capitalizes the first letter of a string. Use array destructuring and String.prototype.toUpperCase() to …
- capitalizeEveryWord Capitalizes the first letter of every word in a string. Use String.prototype.replace() to match the first …
- cartesianProduct Calculates the cartesian product of two arrays. Use Array.prototype.reduce(), Array.prototype.map() and the …
- castArray Casts the provided value as an array if it’s not one. Use Array.prototype.isArray() to determine if val …
- celsiusToFahrenheit Converts Celsius to Fahrenheit. Follow the conversion formula F = 1.8 * C + 32. const celsiusToFahrenheit = …
- chainAsync Chains asynchronous functions. Loop through an array of functions containing asynchronous events, calling next …
- changeLightness Changes the lightness value of an hsl() color string. Use String.prototype.match() to get an array of 3 …
- checkProp Creates a function that will invoke a predicate function for the specified property on a given object. Return …
- chunk Chunks an array into smaller arrays of a specified size. Use Array.from() to create a new array, that fits the …
- chunkify Chunks an iterable into smaller arrays of a specified size. Use a for...of loop over the given iterable, using …
- chunkIntoN Chunks an array into n smaller arrays. Use Math.ceil() and Array.prototype.length to get the size of each …
- clampNumber Clamps num within the inclusive range specified by the boundary values a and b. If num falls within the range, …
- cloneRegExp Clones a regular expression. Use new RegExp(), RegExp.prototype.source and RegExp.prototype.flags to clone the …
- coalesce Returns the first defined, non-null argument. Use Array.prototype.find() and Array.prototype.includes() to …
- coalesceFactory Customizes a coalesce function that returns the first argument which is true based on the given validator. Use …
- collectInto Changes a function that accepts an array into a variadic function. Given a function, return a closure that …
- colorize Adds special characters to text to print in color in the console (combined with console.log()). Use template …
- combine Combines two arrays of objects, using the specified key to match objects. Use Array.prototype.reduce() with an …
- compact Removes falsy values from an array. Use Array.prototype.filter() to filter out falsy values (false, null, 0, …
- compactObject Deeply removes all falsy values from an object or array. Use recursion. Initialize the iterable data, using …
- compactWhitespace Compacts whitespaces in a string. Use String.prototype.replace() with a regular expression to replace all …
- complement Returns a function that is the logical complement of the given function, fn. Use the logical not (!) operator …
- compose Performs right-to-left function composition. Use Array.prototype.reduce() to perform right-to-left function …
- composeRight Performs left-to-right function composition. Use Array.prototype.reduce() to perform left-to-right function …
- containsWhitespace Checks if the given string contains any whitespace characters. Use RegExp.prototype.test() with an appropriate …
- converge Accepts a converging function and a list of branching functions and returns a function that applies each …
- copySign Returns the absolute value of the first number, but the sign of the second. Use Math.sign() to check if the …
- copyToClipboard Copies a string to the clipboard. Only works as a result of user action (i.e. inside a click event listener). …
- countBy Groups the elements of an array based on the given function and returns the count of elements in each group. …
- counter Creates a counter with the specified range, step and duration for the specified selector. Check if step has …
- countOccurrences Counts the occurrences of a value in an array. Use Array.prototype.reduce() to increment a counter each time …
- countSubstrings Counts the occurrences of a substring in a given string. Use Array.prototype.indexOf() to look for searchValue …
- countWeekDaysBetween Counts the weekdays between two dates. Use Array.from() to construct an array with length equal to the number …
- createDirIfNotExists Creates a directory, if it does not exist. Use fs.existsSync() to check if the directory exists, …
- createElement Creates an element from a string (without appending it to the document). If the given string contains multiple …
- createEventHub Creates a pub/sub (publish–subscribe) event hub with emit, on, and off methods. Use Object.create(null) to …
- CSVToArray Converts a comma-separated values (CSV) string to a 2D array. Use Array.prototype.slice() and …
- CSVToJSON Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used …
- currentURL Returns the current URL. Use Window.location.href to get the current URL. const currentURL = () => …
- curry Curries a function. Use recursion. If the number of provided arguments (args) is sufficient, call the passed …
- cycleGenerator Creates a generator, looping over the given array indefinitely. Use a non-terminating while loop, that will …
- dateRangeGenerator Creates a generator, that generates all dates in the given range using the given step. Use a while loop to …
- dayName Gets the name of the weekday from a Date object. Use Date.prototype.toLocaleDateString() with the { weekday: …
- dayOfYear Gets the day of the year (number in the range 1-366) from a Date object. Use new Date() and …
- daysAgo Calculates the date of n days ago from today as a string representation. Use new Date() to get the current …
- daysFromNow Calculates the date of n days from today as a string representation. Use new Date() to get the current date, …
- daysInMonth Gets the number of days in the given month of the specified year. Use the new Date() constructor to create a …
- debounce Creates a debounced function that delays invoking the provided function until at least ms milliseconds have …
- debouncePromise Creates a debounced function that returns a promise, but delays invoking the provided function until at least …
- decapitalize Decapitalizes the first letter of a string. Use array destructuring and String.prototype.toLowerCase() to …
- deepClone Creates a deep clone of an object. Clones primitives, arrays and objects, excluding class instances. Use …
- deepFlatten Deep flattens an array. Use recursion. Use Array.prototype.concat() with an empty array ([]) and the spread …
- deepFreeze Deep freezes an object. Use Object.keys() to get all the properties of the passed object, …
- deepGet Gets the target value in a nested JSON object, based on the keys array. Compare the keys you want in the …
- deepMapKeys Deep maps an object’s keys. Creates an object with the same values as the provided object and keys …
- deepMerge Deeply merges two objects, using a function to handle keys present in both. Use Object.keys() to get the keys …
- defaults Assigns default values for all properties in an object that are undefined. Use Object.assign() to create a new …
- defer Defers invoking a function until the current call stack has cleared. Use setTimeout() with a timeout of 1 ms …
- degreesToRads Converts an angle from degrees to radians. Use Math.PI and the degree to radian formula to convert the angle …
- delay Invokes the provided function after ms milliseconds. Use setTimeout() to delay execution of fn. Use the spread …
- detectDeviceType Detects whether the page is being viewed on a mobile device or a desktop. Use a regular expression to test the …
- detectLanguage Detects the preferred language of the current user. Use NavigationLanguage.language or the first …
- difference Calculates the difference between two arrays, without filtering duplicate values. Create a Set from b to get …
- differenceBy Returns the difference between two arrays, after applying the provided function to each array element of both. …
- differenceWith Filters out all values from an array for which the comparator function does not return true. Use …
- dig Gets the target value in a nested JSON object, based on the given key. Use the in operator to check if target …
- digitize Converts a number to an array of digits, removing its sign if necessary. Use Math.abs() to strip the …
- distance Calculates the distance between two points. Use Math.hypot() to calculate the Euclidean distance between two …
- divmod Returns an array consisting of the quotient and remainder of the given numbers. Use Math.floor() to get the …
- drop Creates a new array with n elements removed from the left. Use Array.prototype.slice() to remove the specified …
- dropRight Creates a new array with n elements removed from the right. Use Array.prototype.slice() to remove the …
- dropRightWhile Removes elements from the end of an array until the passed function returns true. Returns the remaining …
- dropWhile Removes elements in an array until the passed function returns true. Returns the remaining elements in the …
- either Checks if at least one function returns true for a given set of arguments. Use the logical or (||) operator on …
- elementContains Checks if the parent element contains the child element. Check that parent is not the same element as child. …
- elementIsFocused Checks if the given element is focused. Use Document.activeElement to determine if the given element is …
- elementIsVisibleInViewport Checks if the element specified is visible in the viewport. Use Element.getBoundingClientRect() and the …
- equals Performs a deep comparison between two values to determine if they are equivalent. Check if the two values are …
- escapeHTML Escapes a string for use in HTML. Use String.prototype.replace() with a regexp that matches the characters …
- escapeRegExp Escapes a string to use in a regular expression. Use String.prototype.replace() to escape special characters. …
- euclideanDistance Calculates the distance between two points in any number of dimensions. Use Object.keys() and …
- everyNth Returns every nth element in an array. Use Array.prototype.filter() to create a new array that contains every …
- expandTabs Convert tabs to spaces, where each tab corresponds to count spaces. Use String.prototype.replace() with a …
- extendHex Extends a 3-digit color code to a 6-digit color code. Use Array.prototype.map(), String.prototype.split() and …
- factorial Calculates the factorial of a number. Use recursion. If n is less than or equal to 1, return 1. Otherwise, …
- fahrenheitToCelsius Converts Fahrenheit to Celsius. Follow the conversion formula C = (F - 32) * 5/9. const fahrenheitToCelsius = …
- fibonacci Generates an array, containing the Fibonacci sequence, up until the nth term. Use Array.from() to create an …
- filterNonUnique Creates an array with the non-unique values filtered out. Use new Set() and the spread operator (...) to …
- filterNonUniqueBy Creates an array with the non-unique values filtered out, based on a provided comparator function. Use …
- filterUnique Creates an array with the unique values filtered out. Use new Set() and the spread operator (...) to create an …
- filterUniqueBy Creates an array with the unique values filtered out, based on a provided comparator function. Use …
- findClosestAnchor Finds the anchor node closest to the given node, if any. Use a for loop and Node.parentNode to traverse the …
- findClosestMatchingNode Finds the closest matching node starting at the given node. Use a for loop and Node.parentNode to traverse the …
- findFirstN Finds the first n elements for which the provided function returns a truthy value. Use a for..in loop to …
- findKey Finds the first key that satisfies the provided testing function. Otherwise undefined is returned. Use …
- findKeys Finds all the keys in the provided object that match the given value. Use Object.keys(obj) to get all the …
- findLast Finds the last element for which the provided function returns a truthy value. Use Array.prototype.filter() to …
- findLastIndex Finds the index of the last element for which the provided function returns a truthy value. Use …
- findLastKey Finds the last key that satisfies the provided testing function. Otherwise undefined is returned. Use …
- findLastN Finds the last n elements for which the provided function returns a truthy value. Use a for loop to execute …
- flatten Flattens an array up to the specified depth. Use recursion, decrementing depth by 1 for each level of depth. …
- flattenObject Flattens an object with the paths for keys. Use recursion. Use Object.keys(obj) combined with …
- flip Takes a function as an argument, then makes the first argument the last. Use argument destructuring and a …
- forEachRight Executes a provided function once for each array element, starting from the array’s last element. Use …
- formatDuration Returns the human-readable format of the given number of milliseconds. Divide ms with the appropriate values …
- formatNumber Formats a number using the local number format order. Use Number.prototype.toLocaleString() to convert a …
- formatSeconds Returns the ISO format of the given number of seconds. Divide s with the appropriate values to obtain the …
- formToObject Encodes a set of form elements as an object. Use the FormData constructor to convert the HTML form to FormData …
- forOwn Iterates over all own properties of an object, running a callback for each one. Use Object.keys(obj) to get …
- forOwnRight Iterates over all own properties of an object in reverse, running a callback for each one. Use …
- frequencies Creates an object with the unique values of an array as keys and their frequencies as the values. Use …
- fromCamelCase Converts a string from camelcase. Use String.prototype.replace() to break the string into words and add a …
- fromTimestamp Creates a Date object from a Unix timestamp. Convert the timestamp to milliseconds by multiplying with 1000. …
- frozenSet Creates a frozen Set object. Use the new Set() constructor to create a new Set object from iterable. Set the …
- fullscreen Opens or closes an element in fullscreen mode. Use Document.querySelector() and Element.requestFullscreen() to …
- functionName Logs the name of a function. Use console.debug() and the name property of the passed function to log the …
- functions Gets an array of function property names from own (and optionally inherited) enumerable properties of an …
- gcd Calculates the greatest common divisor between two or more numbers/arrays. The inner _gcd function uses …
- generateItems Generates an array with the given amount of items, using the given function. Use Array.from() to create an …
- generatorToArray Converts the output of a generator function to an array. Use the spread operator (...) to convert the output …
- geometricProgression Initializes an array containing the numbers in the specified range where start and end are inclusive and the …
- get Retrieves a set of properties indicated by the given selectors from an object. Use Array.prototype.map() for …
- getAncestors Returns all the ancestors of an element from the document root to the given element. Use Node.parentNode and a …
- getBaseURL Gets the current URL without any parameters or fragment identifiers. Use String.prototype.replace() with an …
- getColonTimeFromDate Returns a string of the form HH:MM:SS from a Date object. Use Date.prototype.toTimeString() and …
- getDaysDiffBetweenDates Calculates the difference (in days) between two dates. Subtract the two Date objects and divide by the number …
- getElementsBiggerThanViewport Returns an array of HTML elements whose width is larger than that of the viewport’s. Use …
- getHoursDiffBetweenDates Calculates the difference (in hours) between two dates. Subtract the two Date objects and divide by the number …
- getImages Fetches all images from within an element and puts them into an array. Use Element.getElementsByTagName() to …
- getMeridiemSuffixOfInteger Converts an integer to a suffixed string, adding am or pm based on its value. Use the modulo operator (%) and …
- getMinutesDiffBetweenDates Calculates the difference (in minutes) between two dates. Subtract the two Date objects and divide by the …
- getMonthsDiffBetweenDates Calculates the difference (in months) between two dates. Use Date.prototype.getFullYear() and …
- getParentsUntil Finds all the ancestors of an element up until the element matched by the specified selector. Use …
- getProtocol Gets the protocol being used on the current page. Use Window.location.protocol to get the protocol (http: or …
- getScrollPosition Returns the scroll position of the current page. Use Window.pageXOffset and Window.pageYOffset if they are …
- getSecondsDiffBetweenDates Calculates the difference (in seconds) between two dates. Subtract the two Date objects and divide by the …
- getSelectedText Gets the currently selected text. Use Window.getSelection() and Selection.toString() to get the currently …
- getSiblings Returns an array containing all the siblings of the given element. Use Node.parentNode and Node.childNodes to …
- getStyle Retrieves the value of a CSS rule for the specified element. Use Window.getComputedStyle() to get the value of …
- getTimestamp Gets the Unix timestamp from a Date object. Use Date.prototype.getTime() to get the timestamp in milliseconds …
- getType Returns the native type of a value. Return 'undefined' or 'null' if the value is undefined or null. Otherwise, …
- getURLParameters Creates an object containing the parameters of the current URL. Use String.prototype.match() with an …
- getVerticalOffset Finds the distance from a given element to the top of the document. Use a while loop and …
- groupBy Groups the elements of an array based on the given function. Use Array.prototype.map() to map the values of …
- hammingDistance Calculates the Hamming distance between two values. Use the XOR operator (^) to find the bit difference …
- hasClass Checks if the given element has the specified class. Use Element.classList and DOMTokenList.contains() to …
- hasDuplicates Checks if there are duplicate values in a flat array. Use Set() to get the unique values in the array. Use …
- hasFlags Checks if the current process’s arguments contain the specified flags. Use Array.prototype.every() and …
- hashBrowser Creates a hash for a value using the SHA-256 algorithm. Returns a promise. Use the SubtleCrypto API to create …
- hashNode Creates a hash for a value using the SHA-256 algorithm. Returns a promise. Use crypto.createHash() to create a …
- hasKey Checks if the target value exists in a JSON object. Check if keys is non-empty and use Array.prototype.every() …
- hasMany Checks if an array has more than one value matching the given function. Use Array.prototype.filter() in …
- hasOne Checks if an array has only one value matching the given function. Use Array.prototype.filter() in combination …
- haveSameContents Checks if two arrays contain the same elements regardless of order. Use a for...of loop over a Set created …
- head Returns the head of an array. Check if arr is truthy and has a length property. Use arr[0] if possible to …
- heapsort Sorts an array of numbers, using the heapsort algorithm. Use recursion. Use the spread operator (...) to clone …
- hexToRGB Converts a color code to an rgb() or rgba() string if alpha value is provided. Use bitwise right-shift …
- hide Hides all the elements specified. Use NodeList.prototype.forEach() to apply display: none to each element …
- HSBToRGB Converts a HSB color tuple to RGB format. Use the HSB to RGB conversion formula to convert to the appropriate …
- HSLToRGB Converts a HSL color tuple to RGB format. Use the HSL to RGB conversion formula to convert to the appropriate …
- httpDelete Makes a DELETE request to the passed URL. Use the XMLHttpRequest web API to make a DELETE request to the given …
- httpGet Makes a GET request to the passed URL. Use the XMLHttpRequest web API to make a GET request to the given url. …
- httpPost Makes a POST request to the passed URL. Use the XMLHttpRequest web API to make a POST request to the given …
- httpPut Makes a PUT request to the passed URL. Use XMLHttpRequest web api to make a PUT request to the given url. Set …
- httpsRedirect Redirects the page to HTTPS if it’s currently in HTTP. Use location.protocol to get the protocol …
- hz Measures the number of times a function is executed per second (hz/hertz). Use performance.now() to get the …
- includesAll Checks if all the elements in values are included in arr. Use Array.prototype.every() and …
- includesAny Checks if at least one element of values is included in arr. Use Array.prototype.some() and …
- indentString Indents each line in the provided string. Use String.prototype.replace() and a regular expression to add the …
- indexBy Creates an object from an array, using a function to map each value to a key. Use Array.prototype.reduce() to …
- indexOfAll Finds all indexes of val in an array. If val never occurs, returns an empty array. Use …
- indexOfSubstrings Finds all the indexes of a substring in a given string. Use Array.prototype.indexOf() to look for searchValue …
- indexOn Creates an object from an array, using the specified key and excluding it from each value. Use …
- initial Returns all the elements of an array except the last one. Use Array.prototype.slice(0, -1) to return all but …
- initialize2DArray Initializes a 2D array of given width and height and value. Use Array.from() and Array.prototype.map() to …
- initializeArrayWithRange Initializes an array containing the numbers in the specified range where start and end are inclusive with …
- initializeArrayWithRangeRight Initializes an array containing the numbers in the specified range (in reverse) where start and end are …
- initializeArrayWithValues Initializes and fills an array with the specified values. Use Array.from() to create an array of the desired …
- initializeNDArray Create a n-dimensional array with given value. Use recursion. Use Array.from(), Array.prototype.map() to …
- injectCSS Injects the given CSS code into the current document Use Document.createElement() to create a new style …
- inRange Checks if the given number falls within the given range. Use arithmetic comparison to check if the given …
- insertAfter Inserts an HTML string after the end of the specified element. Use Element.insertAdjacentHTML() with a …
- insertAt Mutates the original array to insert the given values after the specified index. Use Array.prototype.splice() …
- insertBefore Inserts an HTML string before the start of the specified element. Use Element.insertAdjacentHTML() with a …
- insertionSort Sorts an array of numbers, using the insertion sort algorithm. Use Array.prototype.reduce() to iterate over …
- intersection Returns the elements that exist in both arrays, filtering duplicate values. Create a Set from b, then use …
- intersectionBy Returns the elements that exist in both arrays, after applying the provided function to each array element of …
- intersectionWith Returns the elements that exist in both arrays, using a provided comparator function. Use …
- invertKeyValues Inverts the key-value pairs of an object, without mutating it. Use Object.keys() and Array.prototype.reduce() …
- is Checks if the provided value is of the specified type. Ensure the value is not undefined or null using …
- isAbsoluteURL Checks if the given string is an absolute URL. Use RegExp.prototype.test() to test if the string is an …
- isAfterDate Checks if a date is after another date. Use the greater than operator (>) to check if the first date comes …
- isAlpha Checks if a string contains only alpha characters. Use RegExp.prototype.test() to check if the given string …
- isAlphaNumeric Checks if a string contains only alphanumeric characters. Use RegExp.prototype.test() to check if the input …
- isAnagram Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special …
- isArrayLike Checks if the provided argument is array-like (i.e. is iterable). Check if the provided argument is not null …
- isAsyncFunction Checks if the given argument is an async function. Use Object.prototype.toString() and …
- isBeforeDate Checks if a date is before another date. Use the less than operator (<) to check if the first date comes …
- isBetweenDates Checks if a date is between two other dates. Use the greater than (>) and less than (<) operators to …
- isBoolean Checks if the given argument is a native boolean element. Use typeof to check if a value is classified as a …
- isBrowser Determines if the current runtime environment is a browser so that front-end modules can run on the server …
- isBrowserTabFocused Checks if the browser tab of the page is focused. Use the Document.hidden property, introduced by the Page …
- isContainedIn Checks if the elements of the first array are contained in the second one regardless of order. Use a for...of …
- isDateValid Checks if a valid date object can be created from the given values. Use the spread operator (...) to pass the …
- isDeepFrozen Checks if an object is deeply frozen. Use recursion. Use Object.isFrozen() on the given object. Use …
- isDisjoint Checks if the two iterables are disjointed (have no common values). Use the new Set() constructor to create a …
- isDivisible Checks if the first numeric argument is divisible by the second one. Use the modulo operator (%) to check if …
- isDuplexStream Checks if the given argument is a duplex (readable and writable) stream. Check if the value is different from …
- isEmpty Checks if the a value is an empty object/collection, has no enumerable properties or is any type that is not …
- isEven Checks if the given number is even. Checks whether a number is odd or even using the modulo (%) operator. …
- isFunction Checks if the given argument is a function. Use typeof to check if a value is classified as a function …
- isGeneratorFunction Checks if the given argument is a generator function. Use Object.prototype.toString() and …
- isISOString Checks if the given string is valid in the simplified extended ISO format (ISO 8601). Use new Date() to create …
- isLeapYear Checks if the given year is a leap year. Use new Date(), setting the date to February 29th of the given year. …
- isLocalStorageEnabled Checks if localStorage is enabled. Use a try...catch block to return true if all operations complete …
- isLowerCase Checks if a string is lower case. Convert the given string to lower case, using String.prototype.toLowerCase() …
- isNegativeZero Checks if the given value is equal to negative zero (-0). Check whether a passed value is equal to 0 and if 1 …
- isNil Checks if the specified value is null or undefined. Use the strict equality operator to check if the value of …
- isNode Determines if the current runtime environment is Node.js. Use the process global object that provides …
- isNull Checks if the specified value is null. Use the strict equality operator to check if the value of val is equal …
- isNumber Checks if the given argument is a number. Use typeof to check if a value is classified as a number primitive. …
- isObject Checks if the passed value is an object or not. Uses the Object constructor to create an object wrapper for …
- isObjectLike Checks if a value is object-like. Check if the provided value is not null and its typeof is equal to 'object'. …
- isOdd Checks if the given number is odd. Check whether a number is odd or even using the modulo (%) operator. Return …
- isPlainObject Checks if the provided value is an object created by the Object constructor. Check if the provided value is …
- isPowerOfTen Checks if the given number is a power of 10. Use Math.log10() and the modulo operator (%) to determine if n is …
- isPowerOfTwo Checks if the given number is a power of 2. Use the bitwise binary AND operator (&) to determine if n is a …
- isPrime Checks if the provided integer is a prime number. Check numbers from 2 to the square root of the given number. …
- isPrimitive Checks if the passed value is primitive or not. Create an object from val and compare it with val to determine …
- isPromiseLike Checks if an object looks like a Promise. Check if the object is not null, its typeof matches either object or …
- isReadableStream Checks if the given argument is a readable stream. Check if the value is different from null. Use typeof to …
- isSameDate Checks if a date is the same as another date. Use Date.prototype.toISOString() and strict equality checking …
- isSameOrigin Checks if two URLs are on the same origin. Use URL.protocol and URL.host to check if both URLs have the same …
- isSessionStorageEnabled Checks if sessionStorage is enabled. Use a try...catch block to return true if all operations complete …
- isSorted Checks if a numeric array is sorted. Calculate the ordering direction for the first pair of adjacent array …
- isStream Checks if the given argument is a stream. Check if the value is different from null. Use typeof to check if …
- isString Checks if the given argument is a string. Only works for string primitives. Use typeof to check if a value is …
- isSymbol Checks if the given argument is a symbol. Use typeof to check if a value is classified as a symbol primitive. …
- isTravisCI Checks if the current environment is Travis CI. Check if the current environment has the TRAVIS and CI …
- isUndefined Checks if the specified value is undefined. Use the strict equality operator to check if val is equal to …
- isUpperCase Checks if a string is upper case. Convert the given string to upper case, using String.prototype.toUpperCase() …
- isValidJSON Checks if the provided string is a valid JSON. Use JSON.parse() and a try... catch block to check if the …
- isWeekday Checks if the given date is a weekday. Use Date.prototype.getDay() to check weekday by using a modulo operator …
- isWeekend Checks if the given date is a weekend. Use Date.prototype.getDay() to check weekend by using a modulo operator …
- isWritableStream Checks if the given argument is a writable stream. Check if the value is different from null. Use typeof to …
- join Joins all elements of an array into a string and returns this string. Uses a separator and an end separator. …
- JSONtoCSV Converts an array of objects to a comma-separated values (CSV) string that contains only the columns …
- JSONToFile Writes a JSON object to a file. Use fs.writeFileSync(), template literals and JSON.stringify() to write a json …
- juxt Takes several functions as argument and returns a function that is the juxtaposition of those functions. Use …
- kMeans Groups the given data into k clusters, using the k-means clustering algorithm. Use Array.from() and …
- kmToMiles Converts kilometers to miles. Follow the conversion formula mi = km * 0.621371. const kmToMiles = km => km …
- kNearestNeighbors Classifies a data point relative to a labelled data set, using the k-nearest neighbors algorithm. Use …
- last Returns the last element in an array. Check if arr is truthy and has a length property. Use …
- lastDateOfMonth Returns the string representation of the last date in the given date’s month. Use …
- lcm Calculates the least common multiple of two or more numbers. Use the greatest common divisor (GCD) formula and …
- levenshteinDistance Calculates the difference between two strings, using the Levenshtein distance algorithm. If either of the two …
- linearSearch Finds the first index of a given element in an array using the linear search algorithm. Use a for...in loop to …
- listenOnce Adds an event listener to an element that will only run the callback the first time the event is triggered. …
- logBase Calculates the logarithm of the given number in the given base. Use Math.log() to get the logarithm from the …
- longestItem Takes any number of iterable objects or objects with a length property and returns the longest one. Use …
- lowercaseKeys Creates a new object from the specified object, where all the keys are in lowercase. Use Object.keys() and …
- luhnCheck Implementation of the Luhn Algorithm used to validate a variety of identification numbers, such as credit card …
- mapConsecutive Maps each block of n consencutive elements using the given function, fn. Use Array.prototype.slice() to get …
- mapKeys Maps the keys of an object using the provided function, generating a new object. Use Object.keys() to iterate …
- mapNumRange Maps a number from one range to another range. Return num mapped between outMin-outMax from inMin-inMax. const …
- mapObject Maps the values of an array to an object using a function. Use Array.prototype.reduce() to apply fn to each …
- mapString Creates a new string with the results of calling a provided function on every character in the given string. …
- mapValues Maps the values of an object using the provided function, generating a new object with the same keys. Use …
- mask Replaces all but the last num of characters with the specified mask character. Use String.prototype.slice() to …
- matches Compares two objects to determine if the first one contains equivalent property values to the second one. Use …
- matchesWith Compares two objects to determine if the first one contains equivalent property values to the second one, …
- maxBy Returns the maximum value of an array, after mapping each element to a value using the provided function. Use …
- maxDate Returns the maximum of the given dates. Use the ES6 spread syntax with Math.max() to find the maximum date …
- maxN Returns the n maximum elements from the provided array. Use Array.prototype.sort() combined with the spread …
- median Calculates the median of an array of numbers. Find the middle of the array, use Array.prototype.sort() to sort …
- memoize Returns the memoized (cached) function. Create an empty cache by instantiating a new Map object. Return a …
- merge Creates a new object from the combination of two or more objects. Use Array.prototype.reduce() combined with …
- mergeSort Sorts an array of numbers, using the merge sort algorithm. Use recursion. If the length of the array is less …
- mergeSortedArrays Merges two sorted arrays into one. Use the spread operator (...) to clone both of the given arrays. Use …
- midpoint Calculates the midpoint between two pairs of (x,y) points. Destructure the array to get x1, y1, x2 and y2. …
- milesToKm Converts miles to kilometers. Follow the conversion formula km = mi * 1.609344. const milesToKm = miles => …
- minBy Returns the minimum value of an array, after mapping each element to a value using the provided function. Use …
- minDate Returns the minimum of the given dates. Use the ES6 spread syntax with Math.min() to find the minimum date …
- minN Returns the n minimum elements from the provided array. Use Array.prototype.sort() combined with the spread …
- mostFrequent Returns the most frequent element in an array. Use Array.prototype.reduce() to map unique values to an …
- mostPerformant Returns the index of the function in an array of functions which executed the fastest. Use …
- negate Negates a predicate function. Take a predicate function and apply the not operator (!) to it with its …
- nest Nests recursively objects linked to one another in a flat array. Use recursion. Use Array.prototype.filter() …
- nodeListToArray Converts a NodeList to an array. Use spread operator (...) inside new array to convert a NodeList to an array. …
- none Checks if the provided predicate function returns false for all elements in a collection. Use …
- nor Checks if none of the arguments are true. Use the logical not (!) operator to return the inverse of the …
- normalizeLineEndings Normalizes line endings in a string. Use String.prototype.replace() and a regular expression to match and …
- not Returns the logical inverse of the given value. Use the logical not (!) operator to return the inverse of the …
- nthArg Creates a function that gets the argument at index n. Use Array.prototype.slice() to get the desired argument …
- nthElement Returns the nth element of an array. Use Array.prototype.slice() to get an array containing the nth element at …
- nthRoot Calculates the nth root of a given number. Use Math.pow() to calculate x to the power of 1/n which is equal to …
- objectFromPairs Creates an object from the given key-value pairs. Use Array.prototype.reduce() to create and combine key-value …
- objectToEntries Creates an array of key-value pair arrays from an object. Use Object.keys() and Array.prototype.map() to …
- objectToPairs Creates an array of key-value pair arrays from an object. Use Object.entries() to get an array of key-value …
- objectToQueryString Generates a query string from the key-value pairs of the given object. Use Array.prototype.reduce() on …
- observeMutations Creates a new MutationObserver and runs the provided callback for each mutation on the specified element. Use …
- off Removes an event listener from an element. Use EventTarget.removeEventListener() to remove an event listener …
- offset Moves the specified amount of elements to the end of the array. Use Array.prototype.slice() twice to get the …
- omit Omits the key-value pairs corresponding to the given keys from an object. Use Object.keys(), …
- omitBy Omits the key-value pairs corresponding to the keys of the object for which the given function returns falsy. …
- on Adds an event listener to an element with the ability to use event delegation. Use …
- once Ensures a function is called only once. Utilizing a closure, use a flag, called, and set it to true once the …
- onClickOutside Runs the callback whenever the user clicks outside of the specified element. Use …
- onScrollStop Runs the callback whenever the user has stopped scrolling. Use EventTarget.addEventListener() to listen for …
- onUserInputChange Runs the callback whenever the user input type changes (mouse or touch). Use two event listeners. Assume mouse …
- or Checks if at least one of the arguments is true. Use the logical or (||) operator on the two given values. …
- orderBy Sorts an array of objects, ordered by properties and orders. Uses Array.prototype.sort(), …
- orderWith Sorts an array of objects, ordered by a property, based on the array of orders provided. Use …
- over Creates a function that invokes each provided function with the arguments it receives and returns the results. …
- overArgs Creates a function that invokes the provided function with its arguments transformed. Use …
- pad Pads a string on both sides with the specified character, if it’s shorter than the specified length. Use …
- padNumber Pads a given number to the specified length. Use String.prototype.padStart() to pad the number to specified …
- palindrome Checks if the given string is a palindrome. Normalize the string to String.prototype.toLowerCase() and use …
- parseCookie Parses an HTTP Cookie header string, returning an object of all cookie name-value pairs. Use …
- partial Creates a function that invokes fn with partials prepended to the arguments it receives. Use the spread …
- partialRight Creates a function that invokes fn with partials appended to the arguments it receives. Use the spread …
- partition Groups the elements into two arrays, depending on the provided function’s truthiness for each element. …
- partitionBy Applies fn to each value in arr, splitting it each time the provided function returns a new value. Use …
- percentile Calculates the percentage of numbers in the given array that are less or equal to the given value. Use …
- permutations Generates all permutations of an array’s elements (contains duplicates). Use recursion. For each element …
- pick Picks the key-value pairs corresponding to the given keys from an object. Use Array.prototype.reduce() to …
- pickBy Creates an object composed of the properties the given function returns truthy for. Use Object.keys(obj) and …
- pipeAsyncFunctions Performs left-to-right function composition for asynchronous functions. Use Array.prototype.reduce() and the …
- pipeFunctions Performs left-to-right function composition. Use Array.prototype.reduce() with the spread operator (...) to …
- pluck Converts an array of objects into an array of values corresponding to the specified key. Use …
- pluralize Returns the singular or plural form of the word based on the input number, using an optional dictionary if …
- powerset Returns the powerset of a given array of numbers. Use Array.prototype.reduce() combined with …
- prefersDarkColorScheme Checks if the user color scheme preference is dark. Use Window.matchMedia() with the appropriate media query …
- prefersLightColorScheme Checks if the user color scheme preference is light. Use Window.matchMedia() with the appropriate media query …
- prefix Prefixes a CSS property based on the current browser. Use Array.prototype.findIndex() on an array of vendor …
- prettyBytes Converts a number in bytes to a human-readable string. Use an array dictionary of units to be accessed based …
- primeFactors Finds the prime factors of a given number using the trial division algorithm. Use a while loop to iterate over …
- primes Generates primes up to a given number, using the Sieve of Eratosthenes. Generate an array from 2 to the given …
- prod Calculates the product of two or more numbers/arrays. Use Array.prototype.reduce() to multiply each value with …
- promisify Converts an asynchronous function to return a promise. Use currying to return a function returning a Promise …
- pull Mutates the original array to filter out the values specified. Use Array.prototype.filter() and …
- pullAtIndex Mutates the original array to filter out the values at the specified indexes. Returns the removed elements. …
- pullAtValue Mutates the original array to filter out the values specified. Returns the removed elements. Use …
- pullBy Mutates the original array to filter out the values specified, based on a given iterator function. Check if …
- quarterOfYear Returns the quarter and year to which the supplied date belongs to. Use Date.prototype.getMonth() to get the …
- queryStringToObject Generates an object from the given query string or URL. Use String.prototype.split() to get the params from …
- quickSort Sorts an array of numbers, using the quicksort algorithm. Use recursion. Use the spread operator (...) to …
- radsToDegrees Converts an angle from radians to degrees. Use Math.PI and the radian to degree formula to convert the angle …
- randomAlphaNumeric Generates a random string with the specified length. Use Array.from() to create a new array with the specified …
- randomBoolean Generates a random boolean value. Use Math.random() to generate a random number and check if it is greater …
- randomHexColorCode Generates a random hexadecimal color code. Use Math.random() to generate a random 24-bit (6 * 4bits) …
- randomIntArrayInRange Generates an array of n random integers in the specified range. Use Array.from() to create an empty array of …
- randomIntegerInRange Generates a random integer in the specified range. Use Math.random() to generate a random number and map it to …
- randomNumberInRange Generates a random number in the specified range. Use Math.random() to generate a random value, map it to the …
- rangeGenerator Creates a generator, that generates all values in the given range using the given step. Use a while loop to …
- readFileLines Returns an array of lines from the specified file. Use fs.readFileSync() to create a Buffer from a file. …
- rearg Creates a function that invokes the provided function with its arguments arranged according to the specified …
- recordAnimationFrames Invokes the provided callback on each animation frame. Use recursion. Provided that running is true, continue …
- redirect Redirects to a specified URL. Use Window.location.href or Window.location.replace() to redirect to url. Pass a …
- reducedFilter Filters an array of objects based on a condition while also filtering out unspecified keys. Use …
- reduceSuccessive Applies a function against an accumulator and each element in the array (from left to right), returning an …
- reduceWhich Returns the minimum/maximum value of an array, after applying the provided function to set the comparing rule. …
- reject Filters an array’s values based on a predicate function, returning only values for which the predicate …
- remove Mutates an array by removing elements for which the given function returns false. Use Array.prototype.filter() …
- removeAccents Removes accents from strings. Use String.prototype.normalize() to convert the string to a normalized Unicode …
- removeClass Removes a class from an HTML element. Use Element.classList and DOMTokenList.remove() to remove the specified …
- removeElement Removes an element from the DOM. Use Element.parentNode to get the given element’s parent node. Use …
- removeEventListenerAll Detaches an event listener from all the provided targets. Use Array.prototype.forEach() and …
- removeNonASCII Removes non-printable ASCII characters. Use String.prototype.replace() with a regular expression to remove …
- removeWhitespace Returns a string with whitespaces removed. Use String.prototype.replace() with a regular expression to replace …
- renameKeys Replaces the names of multiple object keys with the values provided. Use Object.keys() in combination with …
- renderElement Renders the given DOM tree in the specified DOM element. Destructure the first argument into type and props, …
- repeatGenerator Creates a generator, repeating the given value indefinitely. Use a non-terminating while loop, that will yield …
- replaceLast Replaces the last occurence of a pattern in a string. Use typeof to determine if pattern is a string or a …
- requireUncached Loads a module after removing it from the cache (if exists). Use delete to remove the module from the cache …
- reverseNumber Reverses a number. Use Object.prototype.toString() to convert n to a string. Use String.prototype.split(''), …
- reverseString Reverses a string. Use the spread operator (...) and Array.prototype.reverse() to reverse the order of the …
- RGBToHex Converts the values of RGB components to a hexadecimal color code. Convert given RGB parameters to hexadecimal …
- RGBToHSB Converts a RGB color tuple to HSB format. Use the RGB to HSB conversion formula to convert to the appropriate …
- RGBToHSL Converts a RGB color tuple to HSL format. Use the RGB to HSL conversion formula to convert to the appropriate …
- round Rounds a number to a specified amount of digits. Use Math.round() and template literals to round the number to …
- runAsync Runs a function in a separate thread by using a Web Worker, allowing long running functions to not block the …
- runPromisesInSeries Runs an array of promises in series. Use Array.prototype.reduce() to create a promise chain, where each …
- sample Gets a random element from an array. Use Math.random() to generate a random number. Multiply it by …
- sampleSize Gets n random elements at unique keys from an array up to the size of the array. Shuffle the array using the …
- scrollToTop Smooth-scrolls to the top of the page. Get distance from top using Document.documentElement or Document.body …
- sdbm Hashes the input string into a whole number. Use String.prototype.split('') and Array.prototype.reduce() to …
- selectionSort Sorts an array of numbers, using the selection sort algorithm. Use the spread operator (...) to clone the …
- serializeCookie Serializes a cookie name-value pair into a Set-Cookie header string. Use template literals and …
- serializeForm Encodes a set of form elements as a query string. Use the FormData constructor to convert the HTML form to …
- setStyle Sets the value of a CSS rule for the specified HTML element. Use ElementCSSInlineStyle.style to set the value …
- shallowClone Creates a shallow clone of an object. Use Object.assign() and an empty object ({}) to create a shallow clone …
- shank Has the same functionality as Array.prototype.splice(), but returning a new array instead of mutating the …
- show Shows all the elements specified. Use the spread operator (...) and Array.prototype.forEach() to clear the …
- shuffle Randomizes the order of the values of an array, returning a new array. Use the Fisher-Yates algorithm to …
- similarity Returns an array of elements that appear in both arrays. Use Array.prototype.includes() to determine values …
- size Gets the size of an array, object or string. Get type of val (array, object or string). Use …
- sleep Delays the execution of an asynchronous function. Delay executing part of an async function, by putting it to …
- slugify Converts a string to a URL-friendly slug. Use String.prototype.toLowerCase() and String.prototype.trim() to …
- smoothScroll Smoothly scrolls the element on which it’s called into the visible area of the browser window. Use …
- sortCharactersInString Alphabetically sorts the characters in a string. Use the spread operator (...), Array.prototype.sort() and …
- sortedIndex Finds the lowest index at which a value should be inserted into an array in order to maintain its sorting …
- sortedIndexBy Finds the lowest index at which a value should be inserted into an array in order to maintain its sorting …
- sortedLastIndex Finds the highest index at which a value should be inserted into an array in order to maintain its sort order. …
- sortedLastIndexBy Finds the highest index at which a value should be inserted into an array in order to maintain its sort order, …
- splitLines Splits a multiline string into an array of lines. Use String.prototype.split() and a regular expression to …
- spreadOver Takes a variadic function and returns a function that accepts an array of arguments. Use a closure and the …
- stableSort Performs stable sorting of an array, preserving the initial indexes of items when their values are the same. …
- standardDeviation Calculates the standard deviation of an array of numbers. Use Array.prototype.reduce() to calculate the mean, …
- stringifyCircularJSON Serializes a JSON object containing circular references into a JSON format. Create a new WeakSet() to store …
- stringPermutations Generates all permutations of a string (contains duplicates). Use recursion. For each letter in the given …
- stripHTMLTags Removes HTML/XML tags from string. Use a regular expression to remove HTML/XML tags from a string. const …
- subSet Checks if the first iterable is a subset of the second one, excluding duplicate values. Use the new Set() …
- sum Calculates the sum of two or more numbers/arrays. Use Array.prototype.reduce() to add each value to an …
- sumBy Calculates the sum of an array, after mapping each element to a value using the provided function. Use …
- sumN Sums all the numbers between 1 and n. Use the formula (n * (n + 1)) / 2 to get the sum of all the numbers …
- sumPower Calculates the sum of the powers of all the numbers from start to end (both inclusive). Use …
- superSet Checks if the first iterable is a superset of the second one, excluding duplicate values. Use the new Set() …
- supportsTouchEvents Checks if touch events are supported. Check if 'ontouchstart' exists in window. const supportsTouchEvents = () …
- swapCase Creates a string with uppercase characters converted to lowercase and vice versa. Use the spread operator …
- symbolizeKeys Creates a new object, converting each key to a Symbol. Use Object.keys() to get the keys of obj. Use …
- symmetricDifference Returns the symmetric difference between two arrays, without filtering out duplicate values. Create a new …
- symmetricDifferenceBy Returns the symmetric difference between two arrays, after applying the provided function to each array …
- symmetricDifferenceWith Returns the symmetric difference between two arrays, using a provided function as a comparator. Use …
- tail Returns all elements in an array except for the first one. Return Array.prototype.slice(1) if …
- take Creates an array with n elements removed from the beginning. Use Array.prototype.slice() to create a slice of …
- takeRight Creates an array with n elements removed from the end. Use Array.prototype.slice() to create a slice of the …
- takeRightUntil Removes elements from the end of an array until the passed function returns true. Returns the removed …
- takeRightWhile Removes elements from the end of an array until the passed function returns false. Returns the removed …
- takeUntil Removes elements in an array until the passed function returns true. Returns the removed elements. Loop …
- takeWhile Removes elements in an array until the passed function returns false. Returns the removed elements. Loop …
- throttle Creates a throttled function that only invokes the provided function at most once per every wait milliseconds …
- times Iterates over a callback n times Use Function.prototype.call() to call fn n times or until it returns false. …
- timeTaken Measures the time it takes for a function to execute. Use Console.time() and Console.timeEnd() to measure the …
- toCamelCase Converts a string to camelcase. Use String.prototype.match() to break the string into words using an …
- toCharArray Converts a string to an array of characters. Use the spread operator (...) to convert the string into an array …
- toCurrency Takes a number and returns it in the specified currency formatting. Use Intl.NumberFormat to enable country / …
- toDecimalMark Converts a number to a decimal mark formatted string. Use Number.prototype.toLocaleString() to convert the …
- toggleClass Toggles a class for an HTML element. Use Element.classList and DOMTokenList.toggle() to toggle the specified …
- toHash Reduces a given array-like into a value hash (keyed data store). Given an iterable object or array-like …
- toHSLArray Converts an hsl() color string to an array of values. Use String.prototype.match() to get an array of 3 string …
- toHSLObject Converts an hsl() color string to an object with the values of each color. Use String.prototype.match() to get …
- toISOStringWithTimezone Converts a date to extended ISO format (ISO 8601), including timezone offset. Use …
- toKebabCase Converts a string to kebab case. Use String.prototype.match() to break the string into words using an …
- tomorrow Results in a string representation of tomorrow’s date. Use new Date() to get the current date. Increment …
- toOrdinalSuffix Takes a number and returns it as a string with the correct ordinal indicator suffix. Use the modulo operator …
- toPairs Creates an array of key-value pair arrays from an object or other iterable. Check if Symbol.iterator is …
- toRGBArray Converts an rgb() color string to an array of values. Use String.prototype.match() to get an array of 3 string …
- toRGBObject Converts an rgb() color string to an object with the values of each color. Use String.prototype.match() to get …
- toRomanNumeral Converts an integer to its roman numeral representation. Accepts value between 1 and 3999 (both inclusive). …
- toSafeInteger Converts a value to a safe integer. Use Math.max() and Math.min() to find the closest safe value. Use …
- toSnakeCase Converts a string to snake case. Use String.prototype.match() to break the string into words using an …
- toTitleCase Converts a string to title case. Use String.prototype.match() to break the string into words using an …
- transform Applies a function against an accumulator and each key in the object (from left to right). Use Object.keys() …
- triggerEvent Triggers a specific event on a given element, optionally passing custom data. Use new CustomEvent() to create …
- truncateString Truncates a string up to a specified length. Determine if String.prototype.length is greater than num. Return …
- truncateStringAtWhitespace Truncates a string up to specified length, respecting whitespace when possible. Determine if …
- truthCheckCollection Checks if the predicate function is truthy for all elements of a collection. Use Array.prototype.every() to …
- unary Creates a function that accepts up to one argument, ignoring any additional arguments. Call the provided …
- uncurry Uncurries a function up to depth n. Return a variadic function. Use Array.prototype.reduce() on the provided …
- unescapeHTML Unescapes escaped HTML characters. Use String.prototype.replace() with a regexp that matches the characters …
- unflattenObject Unflatten an object with the paths for keys. Use nested Array.prototype.reduce() to convert the flat path to a …
- unfold Builds an array, using an iterator function and an initial seed value. Use a while loop and …
- union Returns every element that exists in any of the two arrays at least once. Create a new Set() with all values …
- unionBy Returns every element that exists in any of the two arrays at least once, after applying the provided function …
- unionWith Returns every element that exists in any of the two arrays at least once, using a provided comparator …
- uniqueElements Finds all unique values in an array. Create a new Set() from the given array to discard duplicated values. Use …
- uniqueElementsBy Finds all unique values of an array, based on a provided comparator function. Use Array.prototype.reduce() and …
- uniqueElementsByRight Finds all unique values of an array, based on a provided comparator function, starting from the right. Use …
- uniqueSymmetricDifference Returns the unique symmetric difference between two arrays, not containing duplicate values from either array. …
- untildify Converts a tilde path to an absolute path. Use String.prototype.replace() with a regular expression and …
- unzip Creates an array of arrays, ungrouping the elements in an array produced by zip. Use Math.max(), …
- unzipWith Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided …
- URLJoin Joins all given URL segments together, then normalizes the resulting URL. Use String.prototype.join('/') to …
- UUIDGeneratorBrowser Generates a UUID in a browser. Use Crypto.getRandomValues() to generate a UUID, compliant with RFC4122 version …
- UUIDGeneratorNode Generates a UUID in Node.JS. Use crypto.randomBytes() to generate a UUID, compliant with RFC4122 version 4. …
- validateNumber Checks if the given value is a number. Use parseFloat() to try to convert n to a number. Use !Number.isNaN() …
- vectorAngle Calculates the angle (theta) between two vectors. Use Array.prototype.reduce(), Math.pow() and Math.sqrt() to …
- vectorDistance Calculates the distance between two vectors. Use Array.prototype.reduce(), Math.pow() and Math.sqrt() to …
- walkThrough Creates a generator, that walks through all the keys of a given object. Use recursion. Define a generator …
- weekOfYear Returns the zero-indexed week of the year that a date corresponds to. Use new Date() and …
- weightedAverage Calculates the weighted average of two or more numbers. Use Array.prototype.reduce() to create the weighted …
- weightedSample Gets a random element from an array, using the provided weights as the probabilities for each element. Use …
- when Returns a function that takes one argument and runs a callback if it’s truthy or returns it if falsy. …
- without Filters out the elements of an array that have one of the specified values. Use Array.prototype.includes() to …
- words Converts a given string into an array of words. Use String.prototype.split() with a supplied pattern (defaults …
- wordWrap Wraps a string to a given number of characters using a string break character. Use String.prototype.replace() …
- xor Checks if only one of the arguments is true. Use the logical or (||), and (&&) and not (!) operators …
- xProd Creates a new array out of the two supplied by creating each possible pair from the arrays. Use …
- yesNo Returns true if the string is y/yes or false if the string is n/no. Use RegExp.prototype.test() to check if …
- yesterday Results in a string representation of yesterday’s date. Use new Date() to get the current date. …
- zip Creates an array of elements, grouped based on their position in the original arrays. Use Math.max(), …
- zipObject Associates properties to values, given array of valid property identifiers and an array of values. Use …
- zipWith Creates an array of elements, grouped based on the position in the original arrays and using a function to …
No snippet matches that filter.