js-utils
A collection of dependency-free JavaScript utility functions.
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. |
fill | Fills elements of array with value from start up to end (not including end). |
find | Returns a value in the array, if an element in the array satisfies the provided testing function. |
findIndex | Returns the index of the first element of a collection that passes the callback check. |
findLastIndex | Returns the index of the first element of a collection that passes the callback check, iterating from right to left. |
flat | Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. |
fromPairs | Creates an object composed from key-value pairs. |
groupBy | Creates an object composed of keys generated from the results of running each element of array through iteratee . |
includes | Determines whether an array includes a certain element. |
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. |
reverse | Reverses an array (not in place). The first array element becomes the last and the last becomes the first. |
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 | Removes duplicate primitive values from an array. |
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. |
contains | Determines whether one string may be found within another string, returning true or false as appropriate. |
deburr | Deburrs a string by converting latin-1 supplementary letters to basic latin letters and removing combining diacritical marks. |
endsWith | Determines whether a string ends with the characters of another string, returning true or false as appropriate. |
escapeHTML | Escapes a HTML 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. |
pad | Pad subjectString on both sides to the given len , with optional chars defaulting to a space. |
padLeft | Pad subjectString on left side to the given len , with optional chars defaulting to a space. |
padRight | Pad subjectString on right side to the given len , with optional chars defaulting to a space. |
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. |
repeat | Constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. |
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 . |
startsWith | Returns true if string begins with substring (prefix). |
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 | supplant() does variable substitution on a string. It scans through the string looking for expressions enclosed in {{ }} braces. If an expression is found, use it as a key on the object, and if the key has a string value or number value, it is substituted for the bracket expression and it repeats. |
trim | Removes whitespace from both ends of a string. |
trimLeft | Removes whitespace from the left end of a string. |
trimRight | Removes whitespace from the right end of a string. |
truncate | Truncates a string based on character count. |
unescapeHTML | Unescapes a HTML string. |
urlSearchParams | Factory to access the URL search parameters. |
words | Splits string into an array of its words. |
wrapHTML | Wraps a string with a HTML tag with attributes if specified. |
Object
Name | Description |
---|---|
deepClone | Creates a deep clone of a given value. |
extend | Merge the contents of two or more objects together into the first object. |
forIn | Iterates over own and inherited enumerable properties of an object, executing the callback for each property. The callback is invoked with three arguments (value, key, object) |
forOwn | Iterates over own enumerable properties of an object, executing the callback for each property. The callback is invoked with three arguments (value, key, object) |
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. |
schemaValidate | Validates a plain object against a provided schema object. |
Function
Name | Description |
---|---|
after | Creates a function that invokes func 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 func 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 func . |
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 |
---|---|
captureMouse | Captures the mouse position on a specific HTML element. |
captureTouch | Captures the touch position on a specific HTML element. |
cookie | Create, read and delete cookies. |
preloadImages | Asynchronously load images to browser so that can be cached. |
isEventSupported | Checks if an event is supported in a browser environment. |
mediaQuery | Determines if the document matches a media query string. |
scroll | Easing based scrolling to a specified y point inside page. |
whichAnimationEnd | Detects the supported property name for the "animationend" event. |
whichTransitionEnd | Detects the supported property name for the "transitionend" event. |
HTML5 Canvas
Name | Description |
---|---|
convertImageToBase64 | Converts an image's content to Data URI scheme. |
highResolutionCanvas | Processes an HTMLCanvasElement by downsampling on the canvas to ensure that the drawn visuals do not look blurry on high-DPI screens. |
Installation
- To clone the repository, run:
git clone https://github.com/georapbox/js-utils.git
- To install dev dependancies, (from the root folder of the project) run:
$ npm install
Testing
$ npm run test