Home

Awesome

build Coverage Status License

js-utils

This repository contains a set of simple, standalone JavaScript utility functions that I've used throughout the years in various projects. It's meant to provide useful tools that developers can easily modify and adapt for their own needs. The focus is on offering individual functions that can be changed as needed, rather than providing a full library.

The utilities are organized into packages based on their functionality. Each package contains a set of functions that are related to a specific area of development, such as arrays, strings, objects, functions, etc.

Table of Contents

Array

NameDescription
chunkCreates an array of elements split into groups the length of size specified.
compactCreates an array with all falsy values removed. 'false', 'null', '0', '""', 'undefined', and 'NaN' are falsy.
diffReturns an array with only the unique values from the first array, by excluding all values from the second array using strict equality for comparisons.
dropCreates a slice of array with n elements dropped from the beginning.
dropRightCreates a slice of array with n elements dropped from the end.
dropRightWhileCreates a slice of array excluding elements dropped from the end, until predicate returns falsy.
dropWhileCreates a slice of array excluding elements dropped from the beginning, until predicate returns falsy.
groupByCreates an object composed of keys generated from the results of running each element of array through iteratee.
intersectCreates an array of unique values that are included in all given arrays.
insertInserts one or more elements to array at specific index.
moveMove an array element to a different position.
partitionCreates an array of elements split into two groups (arrays) depending on the result of a predicated function invoked for each iteration.
pluckRetrieves the value of a specified property from all elements in an array.
removeRemoves one or more elements from an array at the specified index(es).
shuffleReturns a new array with its elements' order randomized, using the Fisher-Yates (aka Knuth) Shuffle algorithm.
tailGets all but the first element of array.
takeCreates a slice of array with n items taken from the beginning.
takeRightCreates a slice of array with n items taken from the end.
takeRightWhileCreates a slice of array with elements taken from the end, until predicate returns falsy.
takeWhileCreates a slice of array with elements taken from the beginning, until predicate returns falsy.
sortSorts an array of primitive values.
sortBySorts an array of objects by a property.
uniqCreates a duplicate-free version of an array, using SameValueZero for equality comparisons.
uniqByCreates a dupliate free array by accepting an iteratee which is invoked for each element in array.
zipCreates an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on.

String

NameDescription
camelCaseConverts a string to camel case, eg 'theQuickBrownFoxJumpsOverTheLazyDog'.
capitalizeCapitalizes the first character of a string (Optionally, converts the rest of the string to lower case).
classnamesCreates a string by conditionally joining classNames together.
collapseWhitespaceConverts all adjacent whitespace characters to a single space.
deburrDeburrs a string by converting latin-1 supplementary letters to basic latin letters and removing combining diacritical marks.
escapeHTMLConverts the characters &, <, >, " and ' in a string to their corresponding HTML entities.
escapeRegExpEscapes RegExp special characters in a string.
kebabCaseConverts a string to kebab case, eg 'the-quick-brown-fox-jumps-over-the-lazy-dog'.
linesReturns an array with the lines of a a string.
numberFormatFormats a number based on the number of decimal points, the decimal separator and the thousands separator.
pascalCaseConverts a string to pascal case, eg 'TheQuickBrownFoxJumpsOverTheLazyDog'.
randomStringGenerates a pseudo-random string of specific length allowing a set of characters specified by chars.
removePrefixRemoves substring (prefix) from start of a string.
removeSuffixRemoves substring (suffix) from end of a string.
snakeCaseConverts a string to snake case, eg 'the_quick_brown_fox_jumps_over_the_lazy_dog'.
squashRemoves all spaces from a string; optionally removes any escape sequences such as \t, \n, \f, \r and \v.
stripReturns a new string with all occurrences of arguments passed removed.
stripHTMLReturns a new string with all HTML tags removed.
stripPunctuationReturns a new string with all of punctuation removed.
substringAfterReturns a substring after a specific sequence of character(s).
substringBeforeReturns a substring before a specific sequence of character(s).
supplantPerforms variable substitution in a string.
truncateTruncates a string based on character count.
unescapeHTMLConverts the HTML entities &amp;, &lt;, &gt;, &quot;, &#34 and &#39; in a string to their corresponding characters.
wordsSplits string into an array of its words.

Object

NameDescription
getGets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
omitCreates an object composed of the own enumerable (not inherited) property paths of object that are not omitted.
pickCreates an object composed of the picked object properties.
pickByCreates an object composed of the object enumerable properties that predicate returns truthy for.
trueTypeOfDetermines the true type of a value using Object.prototype.toString.call().

Function

NameDescription
afterCreates a function that invokes fn once it's called n or more times.
aryCreates a function that accepts up to n arguments, ignoring any additional arguments.
beforeCreates a function that invokes fn while it’s called less than n times.
composePerforms right-to-left function composition.
curryReturns a curried equivalent of the provided function.
debounceReturns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for 'n' milliseconds.
flipCreates a function that invokes the original function with its parameters reversed.
negateCreates a function that negates the result of the predicate fn.
onceEnsure a given functionality only runs once.
partialCreates a new function that invokes the provided function with partials prepended to the arguments it receives.
partialRightCreates a new function that invokes the provided function with partials appended to the arguments it receives.
pipePerforms left-to-right function composition.
throttleLimits the number of times a function can be called in a given period.
unaryCreates a function that accepts up to one argument, ignoring any additional arguments.

Is

NameDescription
isArrayChecks if a value is an array.
isArrayLikeChecks if a value is array-like.
isArrayLikeObjectChecks if a value is array-like and object as well.
isBooleanChecks if a value is boolean.
isDateChecks if a value is a date object.
isElementChecks if a value is a DOM element.
isEmailValidates a string as email address.
isEmptyChecks if a value is an empty object, collection, map, or set.
isEvenChecks if a value is even.
isFalseChecks if a value is false (strict equality).
isFalsyChecks if a value is falsy.
isFiniteNumChecks if a value is a finite number.
isFlatArrayChecks if a value is a flat array.
isFunctionChecks if a value is a function.
isHexadecimalChecks if a value matches a hexadecimal regular expression.
isHexColorChecks if a value matches a hexadecimal color regular expression.
isIntegerChecks if a value is an integer number.
isIterableChecks if a value is an iterable.
isMapChecks if a value is classified as a Map object.
isNaNDetermines whether the passed value is NaN and its type is Number.
isNullChecks if a value is null.
isNullishChecks if a value is null or undefined.
isNumberChecks if a value is a number.
isObjectChecks if a value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), new String('')).
isObjectLikeChecks if a value is object-like. A value is object-like if it's not null and has a typeof result of "object".
isOddChecks if a value is odd.
isPlainObjectChecks if a value is a plain object. An object is considered to be plain if it's created by {}, new Object(), or Object.create(null).
isPrimitiveChecks if a value is a primitive data type.
isPromiseCheck if a value is a native ES2015 Promise.
isRegexpChecks if a value is a regular expression.
isSafeIntegerChecks if an integer number is in the safe range i.e., it is correctly represented by JavaScript (where all numbers, including integer numbers, are technically floating point number).
isSetChecks if a value is classified as a Set object.
isStringChecks if a value is a string.
isSymbolChecks if a value is classified as a Symbol primitive.
isTrueChecks if a value is true (strict equality).
isTruthyChecks if a value is truthy.
isUndefinedChecks if a value is undefined.
isWeakMapChecks if a value is classified as a WeakMap object.
isWeakSetChecks if a value is classified as a WeakSet object.

Math

NameDescription
averageCalculates the average of a set of numbers.
clampClamps number within the inclusive lower and upper bounds.
degreesToRadiansConverts degrees to radians.
inRangeChecks if a number is between min and max including.
lerpTakes a normalized value within a range of values and converts it to a numerical value that the normalized value points to.
normalizeTakes a value within a range of values and converts that value to a number from 0 to 1 that indicates where it lies in that range.
maxReturns the largest of zero or more numbers.
minReturns the smallest of zero or more numbers.
radiansToDegreesConverts radians to degrees.
randomDistReturns a weighted random number (that tends to the center) of a range of numbers based on the number of the iterations set.
randomIntReturns a pseudo-random integer number between a min (inclusive) and a max (inclusive) value.
randomRangeReturns a pseudo-random number between a min (inclusive) and a max (exclusive) value.
roundToNearestRounds a number to the nearest multiple of a value provided.
roundToPlacesRounds a number to a number of desired places.

DOM

NameDescription
convertImageToBase64Converts an image's content to Data URI scheme.
cookieCreate, read and delete cookies.
highResolutionCanvasProcesses an HTMLCanvasElement by downsampling on the canvas to ensure that the drawn visuals do not look blurry on high-DPI screens.
mediaQueryDetermines if the document matches a media query string.
preloadImagesAsynchronously load images to browser so that can be cached.
whichAnimationEndDetects the supported property name for the "animationend" event.
whichTransitionEndDetects the supported property name for the "transitionend" event.

Development

Installation

Clone repo

git clone https://github.com/georapbox/js-utils.git

Install dev dependencies

npm install

Test

npm test
npm run test:watch # Run tests in watch mode

Generate documentation

Generates markdown documentation for a single file and prints it to stdout.

npm run docs <path-to-file>

License

The MIT License (MIT)