Skip to content

georapbox/js-utils

Repository files navigation

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

Name Description
chunk Creates an array of elements split into groups the length of size specified.
compact Creates an array with all falsy values removed. 'false', 'null', '0', '""', 'undefined', and 'NaN' are falsy.
diff Returns an array with only the unique values from the first array, by excluding all values from the second array using strict equality for comparisons.
drop Creates a slice of array with n elements dropped from the beginning.
dropRight Creates a slice of array with n elements dropped from the end.
dropRightWhile Creates a slice of array excluding elements dropped from the end, until predicate returns falsy.
dropWhile Creates a slice of array excluding elements dropped from the beginning, until predicate returns falsy.
groupBy Creates an object composed of keys generated from the results of running each element of array through iteratee.
intersect Creates an array of unique values that are included in all given arrays.
insert Inserts one or more elements to array at specific index.
move Move an array element to a different position.
partition Creates an array of elements split into two groups (arrays) depending on the result of a predicated function invoked for each iteration.
pluck Retrieves the value of a specified property from all elements in an array.
remove Removes one or more elements from an array at the specified index(es).
shuffle Returns a new array with its elements' order randomized, using the Fisher-Yates (aka Knuth) Shuffle algorithm.
tail Gets all but the first element of array.
take Creates a slice of array with n items taken from the beginning.
takeRight Creates a slice of array with n items taken from the end.
takeRightWhile Creates a slice of array with elements taken from the end, until predicate returns falsy.
takeWhile Creates a slice of array with elements taken from the beginning, until predicate returns falsy.
sort Sorts an array of primitive values.
sortBy Sorts an array of objects by a property.
uniq Creates a duplicate-free version of an array, using SameValueZero for equality comparisons.
uniqBy Creates a dupliate free array by accepting an iteratee which is invoked for each element in array.
zip Creates 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

Name Description
camelCase Converts a string to camel case, eg 'theQuickBrownFoxJumpsOverTheLazyDog'.
capitalize Capitalizes the first character of a string (Optionally, converts the rest of the string to lower case).
classnames Creates a string by conditionally joining classNames together.
collapseWhitespace Converts all adjacent whitespace characters to a single space.
deburr Deburrs a string by converting latin-1 supplementary letters to basic latin letters and removing combining diacritical marks.
escapeHTML Converts the characters &, <, >, " and ' in a string to their corresponding HTML entities.
escapeRegExp Escapes RegExp special characters in a string.
kebabCase Converts a string to kebab case, eg 'the-quick-brown-fox-jumps-over-the-lazy-dog'.
lines Returns an array with the lines of a a string.
numberFormat Formats a number based on the number of decimal points, the decimal separator and the thousands separator.
pascalCase Converts a string to pascal case, eg 'TheQuickBrownFoxJumpsOverTheLazyDog'.
randomString Generates a pseudo-random string of specific length allowing a set of characters specified by chars.
removePrefix Removes substring (prefix) from start of a string.
removeSuffix Removes substring (suffix) from end of a string.
snakeCase Converts a string to snake case, eg 'the_quick_brown_fox_jumps_over_the_lazy_dog'.
squash Removes all spaces from a string; optionally removes any escape sequences such as \t, \n, \f, \r and \v.
strip Returns a new string with all occurrences of arguments passed removed.
stripHTML Returns a new string with all HTML tags removed.
stripPunctuation Returns a new string with all of punctuation removed.
substringAfter Returns a substring after a specific sequence of character(s).
substringBefore Returns a substring before a specific sequence of character(s).
supplant Performs variable substitution in a string.
truncate Truncates a string based on character count.
unescapeHTML Converts the HTML entities &amp;, &lt;, &gt;, &quot;, &#34 and &#39; in a string to their corresponding characters.
words Splits string into an array of its words.

Object

Name Description
get Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
omit Creates an object composed of the own enumerable (not inherited) property paths of object that are not omitted.
pick Creates an object composed of the picked object properties.
pickBy Creates an object composed of the object enumerable properties that predicate returns truthy for.
trueTypeOf Determines the true type of a value using Object.prototype.toString.call().

Function

Name Description
after Creates a function that invokes fn once it's called n or more times.
ary Creates a function that accepts up to n arguments, ignoring any additional arguments.
before Creates a function that invokes fn while it’s called less than n times.
compose Performs right-to-left function composition.
curry Returns a curried equivalent of the provided function.
debounce Returns 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.
flip Creates a function that invokes the original function with its parameters reversed.
negate Creates a function that negates the result of the predicate fn.
once Ensure a given functionality only runs once.
partial Creates a new function that invokes the provided function with partials prepended to the arguments it receives.
partialRight Creates a new function that invokes the provided function with partials appended to the arguments it receives.
pipe Performs left-to-right function composition.
throttle Limits the number of times a function can be called in a given period.
unary Creates a function that accepts up to one argument, ignoring any additional arguments.

Is

Name Description
isArray Checks if a value is an array.
isArrayLike Checks if a value is array-like.
isArrayLikeObject Checks if a value is array-like and object as well.
isBoolean Checks if a value is boolean.
isDate Checks if a value is a date object.
isElement Checks if a value is a DOM element.
isEmail Validates a string as email address.
isEmpty Checks if a value is an empty object, collection, map, or set.
isEven Checks if a value is even.
isFalse Checks if a value is false (strict equality).
isFalsy Checks if a value is falsy.
isFiniteNum Checks if a value is a finite number.
isFlatArray Checks if a value is a flat array.
isFunction Checks if a value is a function.
isHexadecimal Checks if a value matches a hexadecimal regular expression.
isHexColor Checks if a value matches a hexadecimal color regular expression.
isInteger Checks if a value is an integer number.
isIterable Checks if a value is an iterable.
isMap Checks if a value is classified as a Map object.
isNaN Determines whether the passed value is NaN and its type is Number.
isNull Checks if a value is null.
isNullish Checks if a value is null or undefined.
isNumber Checks if a value is a number.
isObject Checks if a value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), new String('')).
isObjectLike Checks if a value is object-like. A value is object-like if it's not null and has a typeof result of "object".
isOdd Checks if a value is odd.
isPlainObject Checks 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).
isPrimitive Checks if a value is a primitive data type.
isPromise Check if a value is a native ES2015 Promise.
isRegexp Checks if a value is a regular expression.
isSafeInteger Checks 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).
isSet Checks if a value is classified as a Set object.
isString Checks if a value is a string.
isSymbol Checks if a value is classified as a Symbol primitive.
isTrue Checks if a value is true (strict equality).
isTruthy Checks if a value is truthy.
isUndefined Checks if a value is undefined.
isWeakMap Checks if a value is classified as a WeakMap object.
isWeakSet Checks if a value is classified as a WeakSet object.

Math

Name Description
average Calculates the average of a set of numbers.
clamp Clamps number within the inclusive lower and upper bounds.
degreesToRadians Converts degrees to radians.
inRange Checks if a number is between min and max including.
lerp Takes a normalized value within a range of values and converts it to a numerical value that the normalized value points to.
normalize Takes 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.
max Returns the largest of zero or more numbers.
min Returns the smallest of zero or more numbers.
radiansToDegrees Converts radians to degrees.
randomDist Returns a weighted random number (that tends to the center) of a range of numbers based on the number of the iterations set.
randomInt Returns a pseudo-random integer number between a min (inclusive) and a max (inclusive) value.
randomRange Returns a pseudo-random number between a min (inclusive) and a max (exclusive) value.
roundToNearest Rounds a number to the nearest multiple of a value provided.
roundToPlaces Rounds a number to a number of desired places.

DOM

Name Description
convertImageToBase64 Converts an image's content to Data URI scheme.
cookie Create, read and delete cookies.
highResolutionCanvas Processes an HTMLCanvasElement by downsampling on the canvas to ensure that the drawn visuals do not look blurry on high-DPI screens.
mediaQuery Determines if the document matches a media query string.
preloadImages Asynchronously load images to browser so that can be cached.
whichAnimationEnd Detects the supported property name for the "animationend" event.
whichTransitionEnd Detects 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)

Releases

No releases published

Packages

No packages published