30 seconds of code

Snippet List

Click on a snippet card to view the snippet or a tag name to view all snippets in that category.

Adapter

ary

Creates a function that accepts up to n arguments, ignoring any additional arguments.

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

collectInto

Changes a function that accepts an array into a variadic function.

flip

Flip takes a function as an argument, then makes the first argument the last.

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.

pipeAsyncFunctions

Performs left-to-right function composition for asynchronous functions.

pipeFunctions

Performs left-to-right function composition.

rearg

Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.

spreadOver

Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.

unary

Creates a function that accepts up to one argument, ignoring any additional arguments.

Array

all

Returns true if the provided predicate function returns true for all elements in a collection, false otherwise.

allEqual

Check if all elements in an array are equal.

any

Returns true if the provided predicate function returns true for at least one element in a collection, false otherwise.

arrayToCSV

Converts a 2D array to a comma-separated values (CSV) string.

bifurcate

Splits values into two groups. If an element in filter is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.

bifurcateBy

Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.

chunk

Chunks an array into smaller arrays of a specified size.

compact

Removes falsy values from an array.

countBy

Groups the elements of an array based on the given function and returns the count of elements in each group.

countOccurrences

Counts the occurrences of a value in an array.

deepFlatten

Deep flattens an array.

difference

Returns the difference between two arrays.

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.

drop

Returns a new array with n elements removed from the left.

dropRight

Returns a new array with n elements removed from the right.

dropRightWhile

Removes elements from the end of an array until the passed function returns true. Returns the remaining elements in the array.

dropWhile

Removes elements in an array until the passed function returns true. Returns the remaining elements in the array.

everyNth

Returns every nth element in an array.

filterFalsy

Filters out the falsy values in an array.

filterNonUnique

Filters out the non-unique values in an array.

filterNonUniqueBy

Filters out the non-unique values in an array, based on a provided comparator function.

findLast

Returns the last element for which the provided function returns a truthy value.

findLastIndex

Returns the index of the last element for which the provided function returns a truthy value.

flatten

Flattens an array up to the specified depth.

forEachRight

Executes a provided function once for each array element, starting from the array's last element.

groupBy

Groups the elements of an array based on the given function.

head

Returns the head of a list.

includesAll

Returns true if all the elements ιν values are included in arr, false otherwise.

includesAny

Returns true if at least one element of values is included in arr , false otherwise.

indexOfAll

Returns all indices of val in an array. If val never occurs, returns [].

initial

Returns all the elements of an array except the last one.

initialize2DArray

Initializes a 2D array of given width and height and value.

initializeArrayWithRange

Initializes an array containing the numbers in the specified range where start and end are inclusive with their common difference step.

initializeArrayWithRangeRight

Initializes an array containing the numbers in the specified range (in reverse) where start and end are inclusive with their common difference step.

initializeArrayWithValues

Initializes and fills an array with the specified values.

initializeNDArray

Create a n-dimensional array with given value.

intersection

Returns a list of elements that exist in both arrays.

intersectionBy

Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.

intersectionWith

Returns a list of elements that exist in both arrays, using a provided comparator function.

isSorted

Returns 1 if the array is sorted in ascending order, -1 if it is sorted in descending order or 0 if it is not sorted.

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 specified.

last

Returns the last element in an array.

longestItem

Takes any number of iterable objects or objects with a length property and returns the longest one. If multiple objects have the same length, the first one will be returned. Returns undefined if no arguments are provided.

mapObject

Maps the values of an array to an object using a function, where the key-value pairs consist of the stringified value as the key and the mapped value.

maxN

Returns the n maximum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array (sorted in descending order).

minN

Returns the n minimum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array (sorted in ascending order).

none

Returns true if the provided predicate function returns false for all elements in a collection, false otherwise.

nthElement

Returns the nth element of an array.

offset

Moves the specified amount of elements to the end of the array.

partition

Groups the elements into two arrays, depending on the provided function's truthiness for each element.

permutations

⚠️ WARNING: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations.

Generates all permutations of an array's elements (contains duplicates).

pull

Mutates the original array to filter out the values specified.

pullAtIndex

Mutates the original array to filter out the values at the specified indexes.

pullAtValue

Mutates the original array to filter out the values specified. Returns the removed elements.

pullBy

Mutates the original array to filter out the values specified, based on a given iterator function.

reducedFilter

Filter an array of objects based on a condition while also filtering out unspecified keys.

reduceSuccessive

Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.

reduceWhich

Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.

reject

Filters an array's values based on a predicate function, returning only values for which the predicate function returns true.

remove

Removes elements from an array for which the given function returns false.

sample

Returns a random element from an array.

sampleSize

Gets n random elements at unique keys from array up to the size of array.

shank

Has the same functionality as Array.prototype.splice(), but returning a new array instead of mutating the original array.

shuffle

Randomizes the order of the values of an array, returning a new array.

similarity

Returns an array of elements that appear in both arrays.

sortedIndex

Returns the lowest index at which value should be inserted into array in order to maintain its sort order.

sortedIndexBy

Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.

sortedLastIndex

Returns the highest index at which value should be inserted into array in order to maintain its sort order.

sortedLastIndexBy

Returns the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.

stableSort

Performs stable sorting of an array, preserving the initial indexes of items when their values are the same. Does not mutate the original array, but returns a new array instead.

symmetricDifference

Returns the symmetric difference between two arrays, without filtering out duplicate values.

symmetricDifferenceBy

Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.

symmetricDifferenceWith

Returns the symmetric difference between two arrays, using a provided function as a comparator.

tail

Returns all elements in an array except for the first one.

take

Returns an array with n elements removed from the beginning.

takeRight

Returns an array with n elements removed from the end.

takeRightWhile

Removes elements from the end of an array until the passed function returns true. Returns the removed elements.

takeWhile

Removes elements in an array until the passed function returns true. Returns the removed elements.

toHash

Reduces a given Array-like into a value hash (keyed data store).

union

Returns every element that exists in any of the two arrays once.

unionBy

Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.

unionWith

Returns every element that exists in any of the two arrays once, using a provided comparator function.

uniqueElements

Returns all unique values of an array.

uniqueElementsBy

Returns all unique values of an array, based on a provided comparator function.

uniqueElementsByRight

Returns all unique values of an array, based on a provided comparator function, starting from the right.

uniqueSymmetricDifference

Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.

without

Filters out the elements of an array, that have one of the specified values.

xProd

Creates a new array out of the two supplied by creating each possible pair from the arrays.

zip

Creates an array of elements, grouped based on the position in the original arrays.

zipObject

Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.

zipWith

Creates an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined.

Browser

arrayToHtmlList

Converts the given array elements into <li> tags and appends them to the list of the given id.

bottomVisible

Returns true if the bottom of the page is visible, false otherwise.

counter

Creates a counter with the specified range, step and duration for the specified selector.

createElement

Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.

createEventHub

Creates a pub/sub (publish–subscribe) event hub with emit, on, and off methods.

currentURL

Returns the current URL.

detectDeviceType

Detects whether the website is being opened in a mobile device or a desktop/laptop.

elementContains

Returns true if the parent element contains the child element, false otherwise.

elementIsVisibleInViewport

Returns true if the element specified is visible in the viewport, false otherwise.

formToObject

Encode a set of form elements as an object.

getImages

Fetches all images from within an element and puts them into an array

getScrollPosition

Returns the scroll position of the current page.

getStyle

Returns the value of a CSS rule for the specified element.

hasClass

Returns true if the element has the specified class, false otherwise.

hide

Hides all the elements specified.

httpsRedirect

Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.

insertAfter

Inserts an HTML string after the end of the specified element.

insertBefore

Inserts an HTML string before the start of the specified element.

isBrowserTabFocused

Returns true if the browser tab of the page is focused, false otherwise.

nodeListToArray

Converts a NodeList to an array.

observeMutations

Returns a new MutationObserver and runs the provided callback for each mutation on the specified element.

off

Removes an event listener from an element.

on

Adds an event listener to an element with the ability to use event delegation.

onUserInputChange

Run the callback whenever the user input type changes (mouse or touch). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops).

prefix

Returns the prefixed version (if necessary) of a CSS property that the browser supports.

recordAnimationFrames

Invokes the provided callback on each animation frame.

redirect

Redirects to a specified URL.

runAsync

Runs a function in a separate thread by using a Web Worker, allowing long running functions to not block the UI.

scrollToTop

Smooth-scrolls to the top of the page.

serializeForm

Encode a set of form elements as a query string.

setStyle

Sets the value of a CSS rule for the specified element.

show

Shows all the elements specified.

smoothScroll

Smoothly scrolls the element on which it's called into the visible area of the browser window.

toggleClass

Toggle a class for an element.

triggerEvent

Triggers a specific event on a given element, optionally passing custom data.

UUIDGeneratorBrowser

Generates a UUID in a browser.

Date

dayOfYear

Gets the day of the year from a Date object.

formatDuration

Returns the human readable format of the given number of milliseconds.

getColonTimeFromDate

Returns a string of the form HH:MM:SS from a Date object.

getDaysDiffBetweenDates

Returns the difference (in days) between two dates.

getMeridiemSuffixOfInteger

Converts an integer to a suffixed string, adding am or pm based on its value.

isAfterDate

Check if a date is after another date.

isBeforeDate

Check if a date is before another date.

isSameDate

Check if a date is the same as another date.

isWeekday

Results in a boolean representation of a specific date.

isWeekend

Results in a boolean representation of a specific date.

maxDate

Returns the maximum of the given dates.

minDate

Returns the minimum of the given dates.

tomorrow

Results in a string representation of tomorrow's date.

yesterday

Results in a string representation of yesterday's date.

Function

attempt

Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.

bind

Creates a function that invokes fn with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.

bindKey

Creates a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.

chainAsync

Chains asynchronous functions.

checkProp

Given a predicate function and a prop string, this curried function will then take an object to inspect by calling the property and passing it to the predicate.

compose

Performs right-to-left function composition.

composeRight

Performs left-to-right function composition.

converge

Accepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function.

curry

Curries a function.

debounce

Creates a debounced function that delays invoking the provided function until at least ms milliseconds have elapsed since the last time it was invoked.

defer

Defers invoking a function until the current call stack has cleared.

delay

Invokes the provided function after wait milliseconds.

functionName

Logs the name of a function.

hz

Returns the number of times a function executed per second. hz is the unit for hertz, the unit of frequency defined as one cycle per second.

memoize

Returns the memoized (cached) function.

negate

Negates a predicate function.

once

Ensures a function is called only once.

partial

Creates a function that invokes fn with partials prepended to the arguments it receives.

partialRight

Creates a function that invokes fn with partials appended to the arguments it receives.

runPromisesInSeries

Runs an array of promises in series.

sleep

Delays the execution of an asynchronous function.

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

uncurry

Uncurries a function up to depth n.

unfold

Builds an array, using an iterator function and an initial seed value.

when

Tests a value, x, against a predicate function. If true, return fn(x). Else, return x.

Math

approximatelyEqual

Checks if two numbers are approximately equal to each other.

average

Returns the average of two or more numbers.

averageBy

Returns the average of an array, after mapping each element to a value using the provided function.

binomialCoefficient

Evaluates the binomial coefficient of two integers n and k.

clampNumber

Clamps num within the inclusive range specified by the boundary values a and b.

degreesToRads

Converts an angle from degrees to radians.

digitize

Converts a number to an array of digits.

distance

Returns the distance between two points.

elo

Computes the new ratings between two or more opponents using the Elo rating system. It takes an array of pre-ratings and returns an array containing post-ratings. The array should be ordered from best performer to worst performer (winner -> loser).

factorial

Calculates the factorial of a number.

fibonacci

Generates an array, containing the Fibonacci sequence, up until the nth term.

gcd

Calculates the greatest common divisor between two or more numbers/arrays.

geometricProgression

Initializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.

hammingDistance

Calculates the Hamming distance between two values.

inRange

Checks if the given number falls within the given range.

isDivisible

Checks if the first numeric argument is divisible by the second one.

isEven

Returns true if the given number is even, false otherwise.

isNegativeZero

Checks if the given value is equal to negative zero (-0).

isOdd

Returns true if the given number is odd, false otherwise.

isPrime

Checks if the provided integer is a prime number.

lcm

Returns the least common multiple of two or more numbers.

luhnCheck

Implementation of the Luhn Algorithm used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.

mapNumRange

Maps a number from one range to another range.

maxBy

Returns the maximum value of an array, after mapping each element to a value using the provided function.

median

Returns the median of an array of numbers.

midpoint

Calculates the midpoint between two pairs of (x,y) points.

minBy

Returns the minimum value of an array, after mapping each element to a value using the provided function.

percentile

Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.

powerset

Returns the powerset of a given array of numbers.

primes

Generates primes up to a given number, using the Sieve of Eratosthenes.

radsToDegrees

Converts an angle from radians to degrees.

randomIntArrayInRange

Returns an array of n random integers in the specified range.

randomIntegerInRange

Returns a random integer in the specified range.

randomNumberInRange

Returns a random number in the specified range.

round

Rounds a number to a specified amount of digits.

sdbm

Hashes the input string into a whole number.

standardDeviation

Returns the standard deviation of an array of numbers.

sum

Returns the sum of two or more numbers/arrays.

sumBy

Returns the sum of an array, after mapping each element to a value using the provided function.

sumPower

Returns the sum of the powers of all the numbers from start to end (both inclusive).

toSafeInteger

Converts a value to a safe integer.

vectorDistance

Returns the distance between two vectors.

Node

atob

Decodes a string of data which has been encoded using base-64 encoding.

btoa

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.

colorize

Add special characters to text to print in color in the console (combined with console.log()).

createDirIfNotExists

Creates a directory, if it does not exist.

hasFlags

Check if the current process's arguments contain the specified flags.

isDuplexStream

Checks if the given argument is a duplex (readable and writable) stream.

isReadableStream

Checks if the given argument is a readable stream.

isStream

Checks if the given argument is a stream.

isWritableStream

Checks if the given argument is a writable stream.

JSONToFile

Writes a JSON object to a file.

readFileLines

Returns an array of lines from the specified file.

untildify

Converts a tilde path to an absolute path.

UUIDGeneratorNode

Generates a UUID in Node.JS.

Object

bindAll

Binds methods of an object to the object itself, overwriting the existing method.

deepClone

Creates a deep clone of an object.

deepFreeze

Deep freezes an object.

deepGet

Returns the target value in a nested JSON object, based on the keys array.

deepMapKeys

Deep maps an object's keys.

defaults

Assigns default values for all properties in an object that are undefined.

dig

Returns the target value in a nested JSON object, based on the given key.

equals

Performs a deep comparison between two values to determine if they are equivalent.

findKey

Returns the first key that satisfies the provided testing function. Otherwise undefined is returned.

findLastKey

Returns the last key that satisfies the provided testing function. Otherwise undefined is returned.

flattenObject

Flatten an object with the paths for keys.

forOwn

Iterates over all own properties of an object, running a callback for each one.

forOwnRight

Iterates over all own properties of an object in reverse, running a callback for each one.

functions

Returns an array of function property names from own (and optionally inherited) enumerable properties of an object.

get

Retrieve a set of properties indicated by the given selectors from an object.

hasKey

Returns true if the target value exists in a JSON object, false otherwise.

Check if keys is non-empty and use Array.prototype.every() to sequentially check its keys to internal depth of the object, obj. Use Object.prototype.hasOwnProperty() to check if obj does not have the current key or is not an object, stop propagation and return false. Otherwise assign the key's value to obj to use on the next iteration.

invertKeyValues

Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.

lowercaseKeys

Creates a new object from the specified object, where all the keys are in lowercase.

mapKeys

Creates an object with keys generated by running the provided function for each key and the same values as the provided object.

mapValues

Creates an object with the same keys as the provided object and values generated by running the provided function for each value.

matches

Compares two objects to determine if the first one contains equivalent property values to the second one.

matchesWith

Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.

merge

Creates a new object from the combination of two or more objects.

nest

Given a flat array of objects linked to one another, it will nest them recursively. Useful for nesting comments, such as the ones on reddit.com.

objectFromPairs

Creates an object from the given key-value pairs.

objectToPairs

Creates an array of key-value pair arrays from an object.

omit

Omits the key-value pairs corresponding to the given keys from an object.

omitBy

Creates an object composed of the properties the given function returns falsy for. The function is invoked with two arguments: (value, key).

orderBy

Returns a sorted array of objects ordered by properties and orders.

pick

Picks the key-value pairs corresponding to the given keys from an object.

pickBy

Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key).

renameKeys

Replaces the names of multiple object keys with the values provided.

shallowClone

Creates a shallow clone of an object.

size

Get size of arrays, objects or strings.

transform

Applies a function against an accumulator and each key in the object (from left to right).

truthCheckCollection

Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).

unflattenObject

Unflatten an object with the paths for keys.

String

byteSize

Returns the length of a string in bytes.

capitalize

Capitalizes the first letter of a string.

capitalizeEveryWord

Capitalizes the first letter of every word in a string.

compactWhitespace

Returns a string with whitespaces compacted.

CSVToArray

Converts a comma-separated values (CSV) string to a 2D array.

CSVToJSON

Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.

decapitalize

Decapitalizes the first letter of a string.

escapeHTML

Escapes a string for use in HTML.

escapeRegExp

Escapes a string to use in a regular expression.

fromCamelCase

Converts a string from camelcase.

indentString

Indents each line in the provided string.

isAbsoluteURL

Returns true if the given string is an absolute URL, false otherwise.

isAnagram

Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).

isLowerCase

Checks if a string is lower case.

isUpperCase

Checks if a string is upper case.

mapString

Creates a new string with the results of calling a provided function on every character in the calling string.

mask

Replaces all but the last num of characters with the specified mask character.

pad

Pads a string on both sides with the specified character, if it's shorter than the specified length.

palindrome

Returns true if the given string is a palindrome, false otherwise.

pluralize

Returns the singular or plural form of the word based on the input number. If the first argument is an object, it will use a closure by returning a function that can auto-pluralize words that don't simply end in s if the supplied dictionary contains the word.

removeNonASCII

Removes non-printable ASCII characters.

reverseString

Reverses a string.

sortCharactersInString

Alphabetically sorts the characters in a string.

splitLines

Splits a multiline string into an array of lines.

stringPermutations

⚠️ WARNING: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.

Generates all permutations of a string (contains duplicates).

stripHTMLTags

Removes HTML/XML tags from string.

toCamelCase

Converts a string to camelcase.

toKebabCase

Converts a string to kebab case.

toSnakeCase

Converts a string to snake case.

toTitleCase

Converts a string to title case.

truncateString

Truncates a string up to a specified length.

unescapeHTML

Unescapes escaped HTML characters.

URLJoin

Joins all given URL segments together, then normalizes the resulting URL.

words

Converts a given string into an array of words.

Type

getType

Returns the native type of a value.

is

Checks if the provided value is of the specified type.

isArrayLike

Checks if the provided argument is array-like (i.e. is iterable).

isBoolean

Checks if the given argument is a native boolean element.

isEmpty

Returns true if the a value is an empty object, collection, has no enumerable properties or is any type that is not considered a collection.

isFunction

Checks if the given argument is a function.

isNil

Returns true if the specified value is null or undefined, false otherwise.

isNull

Returns true if the specified value is null, false otherwise.

isNumber

Checks if the given argument is a number.

isObject

Returns a boolean determining if the passed value is an object or not.

isObjectLike

Checks if a value is object-like.

isPlainObject

Checks if the provided value is an object created by the Object constructor.

isPrimitive

Returns a boolean determining if the passed value is primitive or not.

isString

Checks if the given argument is a string. Only works for string primitives.

isSymbol

Checks if the given argument is a symbol.

isUndefined

Returns true if the specified value is undefined, false otherwise.

isValidJSON

Checks if the provided string is a valid JSON.

Utility

castArray

Casts the provided value as an array if it's not one.

cloneRegExp

Clones a regular expression.

coalesce

Returns the first non-null/undefined argument.

coalesceFactory

Returns a customized coalesce function that returns the first argument that returns true from the provided argument validation function.

extendHex

Extends a 3-digit color code to a 6-digit color code.

getURLParameters

Returns an object containing the parameters of the current URL.

hexToRGB

Converts a color code to a rgb() or rgba() string if alpha value is provided.

httpGet

Makes a GET request to the passed URL.

httpPost

Makes a POST request to the passed URL.

isBrowser

Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.

mostPerformant

Returns the index of the function in an array of functions which executed the fastest.

nthArg

Creates a function that gets the argument at index n. If n is negative, the nth argument from the end is returned.

objectToQueryString

Returns a query string generated from the key-value pairs of the given object.

parseCookie

Parse an HTTP Cookie header string and return an object of all cookie name-value pairs.

prettyBytes

Converts a number in bytes to a human-readable string.

randomHexColorCode

Generates a random hexadecimal color code.

RGBToHex

Converts the values of RGB components to a color code.

serializeCookie

Serialize a cookie name-value pair into a Set-Cookie header string.

timeTaken

Measures the time taken by a function to execute.

toCurrency

Take a number and return specified currency formatting.

toDecimalMark

toOrdinalSuffix

Adds an ordinal suffix to a number.

validateNumber

Returns true if the given value is a number, false otherwise.

yesNo

Returns true if the string is y/yes or false if the string is n/no.

Archived snippets

binarySearch

Use recursion. Similar to Array.prototype.indexOf() that finds the index of a value within an array. The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or Array.prototype.indexOf().

celsiusToFahrenheit

Celsius to Fahrenheit temperature conversion.

cleanObj

Removes any properties except the ones specified from a JSON object.

collatz

Applies the Collatz algorithm.

countVowels

Retuns number of vowels in provided string.

factors

Returns the array of factors of the given num. If the second argument is set to true returns only the prime factors of num. If num is 1 or 0 returns an empty array. If num is less than 0 returns all the factors of -int together with their additive inverses.

Use Array.from(), Array.prototype.map() and Array.prototype.filter() to find all the factors of num. If given num is negative, use Array.prototype.reduce() to add the additive inverses to the array. Return all results if primes is false, else determine and return only the prime factors using isPrime and Array.prototype.filter(). Omit the second argument, primes, to return prime and non-prime factors by default.

fahrenheitToCelsius

Fahrenheit to Celsius temperature conversion.

fibonacciCountUntilNum

Returns the number of fibonnacci numbers up to num(0 and num inclusive).

fibonacciUntilNum

Generates an array, containing the Fibonacci sequence, up until the nth term.

howManyTimes

Returns the number of times num can be divided by divisor (integer or fractional) without getting a fractional answer. Works for both negative and positive integers.

httpDelete

Makes a DELETE request to the passed URL.

httpPut

Makes a PUT request to the passed URL.

isArmstrongNumber

Checks if the given number is an Armstrong number or not.

isSimilar

Determines if the pattern matches with str.

JSONToDate

Converts a JSON object to a date.

kmphToMph

Convert kilometers/hour to miles/hour.

mphToKmph

Convert miles/hour to kilometers/hour.

pipeLog

Logs a value and returns it.

quickSort

QuickSort an Array (ascending sort by default).

removeVowels

Returns all the vowels in a str replaced by repl.

solveRPN

Solves the given mathematical expression in reverse polish notation. Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- +,-,*,/,^,** (^&** are the exponential symbols and are same). This snippet does not supports any unary operators.

speechSynthesis

Performs speech synthesis (experimental).

Use SpeechSynthesisUtterance.voice and window.speechSynthesis.getVoices() to convert a message to speech. Use window.speechSynthesis.speak() to play the message.

squareSum

Squares each number in an array and then sums the results together.


Beginner snippets

Snippets aimed towards individuals at the start of their web developer journey.

Glossary

A handy glossary of web development terminology.

About

A few word about us, our goals and our projects.