loony-utils
v0.1.1
Published
Loony Utils is a collection of utility functions for JavaScript and TypeScript projects, designed to simplify common tasks and enhance productivity.
Readme
Loony JS Utils
Table of Contents
Collections / Arrays
Brief signatures and behavior (see examples below for common usage).
chunk(array, size = 1)— Splitarrayinto groups ofsize.compact(array)— Remove falsey-like values (false, null, 0, "", undefined, NaN).concat(array, ...values)— Return a new array concatenatingarraywithvalues(arrays flattened one level).difference(array, ...values)— Elements inarraynot present in the flattenedvalues.drop(array, n = 1)— Return array without the firstnelements.dropRight(array, n = 1)— Return array without the lastnelements.fill(array, value, start = 0, end = array.length)— Return a copy with range filled withvalue.findIndex(array, predicate, fromIndex = 0)— Return index matching predicate or-1.findLastIndex(array, predicate, fromIndex = array.length - 1)— Search from the end.flatten(array)— Flatten one level.flattenDeep(array)— Fully flatten nested arrays.flattenDepth(array, depth = 1)— Flatten up todepthlevels.fromPairs(pairs)— Convert[[k,v]]to object{k:v}.head(array)— First element orundefined.indexOf(array, value, fromIndex = 0)— Uses deep equality; returns index or-1.initial(array)— All but last element.intersection(...arrays)— Values common to all arrays.join(array, separator = ',')— Join elements to string.last(array)— Last element orundefined.nth(array, n = 0)— Element atn, supports negative indices.pull(array, ...values)— Return array without any of thevalues.pullAt(array, indexes)— Remove by indexes (mutates input) and return removed values.remove(array, predicate)— Remove elements matchingpredicate(mutates input) and return removed.reverse(array)— Return a reversed copy.slice(array, start = 0, end = array.length)— Return a shallow slice.sortedIndex(array, value)— Binary search index to insertvalueinto sortedarray.sortedUniq(array)— Return unique values (assumes sorted input is fine but works generally).tail(array)— All except the first element.take(array, n = 1)— Take the firstnelements.takeRight(array, n = 1)— Take the lastnelements.union(...arrays)— Unique union of all arrays.uniq(array)— Unique values (preserves first occurrence order).uniqBy(array, iteratee)— Unique byiterateeresult.unzip(array)— Transpose array of arrays (inverse ofzip).without(array, ...values)— Return array without specifiedvalues.zip(...arrays)— Combine values by index.
Examples
chunk([1, 2, 3, 4, 5], 2); // -> [[1,2],[3,4],[5]]
compact([0, 1, false, 2, "", 3]); // -> [1,2,3]
flattenDeep([1, [2, [3, 4]], 5]); // -> [1,2,3,4,5]
indexOf([{ a: 1 }, { a: 2 }], { a: 2 }); // -> 1 (deep equality)Objects
assign(object, ...sources)— Shallow merge into new object.defaults(object, ...sources)— Assign missing keys from sources.findKey(object, predicate)— Return first key where predicate(value,key,object) truthy.forOwn(object, iteratee)— Iterate own enumerable properties; break if iteratee returns false.keys(object)—Object.keyswrapper.mapKeys(object, iteratee)— Return new object with transformed keys.mapValues(object, iteratee)— Return new object with transformed values.merge(object, ...sources)— Deep merge sources into new object.omit(object, paths)— Return new object withoutpaths.pick(object, paths)— Return new object with onlypaths.toPairs(object)— Return[[key,value]].values(object)— Return array of values.
Example:
merge({ a: 1, nested: { x: 1 } }, { b: 2, nested: { y: 2 } });
// -> { a:1, b:2, nested: { x:1, y:2 } }Functions
debounce(func, wait, immediate = false)— Debounce calls; returns wrapper.throttle(func, wait)— Throttle calls; returns wrapper.memoize(func, resolver)— Cache results keyed byresolveror serialized args.once(func)— Ensurefuncruns only once and returns cached result.
Example:
const memo = memoize((n) => n * 2);
memo(2); // computed
memo(2); // cachedStrings
camelCase(str)— Convert tocamelCase.capitalize(str)— Capitalize first character.kebabCase(str)— Convert tokebab-case.snakeCase(str)— Convert tosnake_case.startsWith(str, target, position = 0)—String.prototype.startsWithguard.trim(str, chars='\\s')— Trim whitespace or provided characters.trimEnd(str, chars='\\s')— Trim end.trimStart(str, chars='\\s')— Trim start.words(str, pattern=/[^a-zA-Z0-9]+/g)— Split into words.
Example:
camelCase("Foo-bar_baz"); // -> 'fooBarBaz'
words("one,two three"); // -> ['one','two','three']Lang / Types
isArray,isBoolean,isDate,isEmpty,isEqual,isFunction,isNil,isNull,isNumber,isObject,isPlainObject,isString,isUndefinedtoNumber(value)— Coerce to number (non-numeric -> 0).toString(value)— Coerce to string (null/undefined -> "").
Example:
isEqual([1, { x: 2 }], [1, { x: 2 }]); // -> true
isEmpty({}); // -> trueMath
clamp(number, lower, upper)— Clamp into range.inRange(number, start, end)— Is number in [start, end).max,maxBy,min,minBy,sum,sumBy
Example:
clamp(10, 0, 5); // -> 5
sum([1, 2, 3]); // -> 6Numbers
random(lower=0, upper=1, floating=false)— Random int or float. When single argument provided, treated asupper.
Utilities
range(start=0, end, step=1)— Create numeric sequence.times(n, iteratee)— Call iterateentimes and collect results.
Helpers / Internal
_createPredicate(predicate)— Create predicate function from function/object/string/array._createIteratee(iteratee)— Create iteratee function from function/string.mixin(object = this, source = {}, options = {})— Attach functions fromsourcetoobject.
Next steps
- I can add full JSDoc comments into
src/utils.mjsso editors show inline docs. - I can generate a more detailed docs page where each function has parameters, return types, and examples.
- I can add a table of contents with anchor links from
README.md.
Tell me which of those you want and I'll implement it. Loony JS Utils
This document lists the utilities exported by src/utils.mjs, grouped by category, with short descriptions and examples to help you get started.
Import:
Use named imports from the module file. Example if running from project root:
import { chunk, debounce, merge } from "./src/utils.mjs";Contents
- Collection / Array Functions: chunk, compact, concat, difference, drop, dropRight, fill, findIndex, findLastIndex, flatten, flattenDeep, flattenDepth, fromPairs, head, indexOf, initial, intersection, join, last, nth, pull, pullAt, remove, reverse, slice, sortedIndex, sortedUniq, tail, take, takeRight, union, uniq, uniqBy, unzip, without, zip
- Object Functions: assign, defaults, findKey, forOwn, keys, mapKeys, mapValues, merge, omit, pick, toPairs, values
- Function Utilities: debounce, throttle, memoize, once
- String Functions: camelCase, capitalize, kebabCase, snakeCase, startsWith, trim, trimEnd, trimStart, words
- Lang / Type Checks: isArray, isBoolean, isDate, isEmpty, isEqual, isFunction, isNil, isNull, isNumber, isObject, isPlainObject, isString, isUndefined, toNumber, toString
- Math Helpers: clamp, inRange, max, maxBy, min, minBy, sum, sumBy
- Number Utilities: random
- General Utilities: range, times
- Helpers / Internal: _createPredicate, _createIteratee, mixin
Selected Examples
- chunk(array, size = 1)
chunk([1, 2, 3, 4, 5], 2); // => [[1,2],[3,4],[5]]- debounce(func, wait, immediate = false)
const log = () => console.log("called");
const debounced = debounce(log, 200);
debounced();- memoize(func, resolver)
const slow = (n) => {
/* expensive */ return n * 2;
};
const fast = memoize(slow);
fast(10); // computed
fast(10); // returned from cache- merge(object, ...sources)
merge({ a: 1, nested: { x: 1 } }, { b: 2, nested: { y: 2 } });
// => { a:1, b:2, nested: { x:1, y:2 } }- isEqual(a, b)
isEqual([1, { x: 2 }], [1, { x: 2 }]); // => true- random(lower = 0, upper = 1, floating = false)
random(1, 10); // integer between 1 and 10
random(0, 1, true); // float between 0 and 1- range(start = 0, end, step = 1)
range(4); // => [0,1,2,3]
range(1, 5); // => [1,2,3,4]
range(5, 1, -1); // => [5,4,3,2]Function Reference (brief)
Below is a concise reference — signatures and a one-line description for each exported function.
Collection / Array
chunk(array, size=1)— split array into groups ofsize.compact(array)— remove falsy-like values (false, null, 0, "", undefined, NaN).concat(array, ...values)— merge arrays/values into a new array.difference(array, ...values)— return elements not present in other arrays.drop(array, n=1)— drop firstnelements.dropRight(array, n=1)— drop lastnelements.fill(array, value, start=0, end=array.length)— fill an array range withvalue.findIndex(array, predicate, fromIndex=0)— find index by predicate.findLastIndex(array, predicate, fromIndex=array.length-1)— find last index by predicate.flatten(array)— flatten a single level.flattenDeep(array)— fully flatten nested arrays.flattenDepth(array, depth=1)— flatten up todepthlevels.fromPairs(pairs)— convert [[k,v]] to object.head(array)— first element.indexOf(array, value, fromIndex=0)— index of value using deep equality.initial(array)— all but last element.intersection(...arrays)— common elements across arrays.join(array, separator=',')— join elements with separator.last(array)— last element.nth(array, n=0)— get element at index (supports negative).pull(array, ...values)— return array without specified values.pullAt(array, indexes)— remove and return elements at indexes (mutates input).remove(array, predicate)— remove elements matching predicate (mutates input) and return removed.reverse(array)— return reversed copy.slice(array, start=0, end=array.length)— slice copy.sortedIndex(array, value)— binary search insert index for sorted array.sortedUniq(array)— unique values (for sorted arrays).tail(array)— all but first.take(array, n=1)— take first n elements.takeRight(array, n=1)— take last n elements.union(...arrays)— union of arrays values.uniq(array)— unique values in array.uniqBy(array, iteratee)— unique by iteratee result.unzip(array)— transposes array of arrays.without(array, ...values)— return array without specified values.zip(...arrays)— combine arrays by index.
Object
assign(object, ...sources)— shallow copy properties onto a new object.defaults(object, ...sources)— fill undefined props from sources.findKey(object, predicate)— return first key matching predicate.forOwn(object, iteratee)— iterate own keys until iteratee returns false.keys(object)— own enumerable keys.mapKeys(object, iteratee)— transform keys.mapValues(object, iteratee)— transform values.merge(object, ...sources)— deep merge sources into a new object.omit(object, paths)— return new object without specified paths.pick(object, paths)— select specified keys.toPairs(object)— [[key, value]] array.values(object)— array of values.
Functions
debounce(func, wait, immediate=false)— debounce a function.throttle(func, wait)— throttle a function.memoize(func, resolver)— cache results offunc.once(func)— runfuncat most once.
Strings
camelCase(str)— convert to camelCase.capitalize(str)— capitalize first char.kebabCase(str)— convert to kebab-case.snakeCase(str)— convert to snake_case.startsWith(str, target, position=0)— test prefix.trim(str, chars='\\s')— trim characters (or whitespace by default).trimEnd(str, chars='\\s')— trim end.trimStart(str, chars='\\s')— trim start.words(str, pattern=/[^a-zA-Z0-9]+/g)— split into words.
Lang / Type
isArray(value)— Array.isArray.isBoolean(value)— boolean check.isDate(value)— Date instance.isEmpty(value)— check for emptiness.isEqual(a, b)— deep equality.isFunction(value)— function check.isNil(value)— null or undefined.isNull(value)— strict null.isNumber(value)— number check.isObject(value)— plain object/any object.isPlainObject(value)— constructor === Object.isString(value)— string check.isUndefined(value)— undefined.toNumber(value)— coerce to number (NaN -> 0).toString(value)— coerce to string.
Math
clamp(number, lower, upper)— clamp into range.inRange(number, start, end)— check within [start, end).max(array)— max number or undefined.maxBy(array, iteratee)— max element by iteratee.min(array)— min number or undefined.minBy(array, iteratee)— min element by iteratee.sum(array)— numeric sum.sumBy(array, iteratee)— sum by iteratee.
Numbers
random(lower=0, upper=1, floating=false)— random int/float.
Utilities
range(start=0, end, step=1)— create range array.times(n, iteratee)— call iterateentimes and return results.
Helpers
_createPredicate(predicate)— internal helper to generate predicate functions._createIteratee(iteratee)— internal helper to generate iteratee functions.mixin(object = this, source = {}, options = {})— attach functions from source to object.
