@jmellicker/j_
v0.0.28
Published
Helpful JavaScript functions.
Readme
j_
it's a toolkit of random and useful functions
Install
yarn add @jmellicker/j_Array Operations
j_ array ops generally operate on arrays of objects.
Given this array:
const xmen = [
{ name: 'Nightcrawler', power: 'Teleportation', id: 1 },
{ name: 'Cyclops', power: 'Optic blast', id: 2 },
{ name: 'Rogue', power: 'Absorbing powers', id: 3 },
{ name: 'Wolverine', power: 'Regeneration', id: 4 }
]indexFromArray
Searches an array of objects for a key/value pair and returns the index of the first match.
j_.indexFromArray(xmen, 'power', 'Optic blast') // => 1indexFromArrayID
Shorthand for indexFromArray specifically for the 'id' key.
j_.indexFromArrayID(xmen, 2) // => 1queryArrayFirstMatch
Returns the first object in the array that matches the key/value pair.
j_.queryArrayFirstMatch(xmen, 'power', 'Optic blast')
// => { name: "Cyclops", power: "Optic blast", id: 2 }queryArrayAllMatches
Returns all objects in the array that match the key/value pair.
j_.queryArrayAllMatches(xmen, 'power', 'Teleportation')
// => [{ name: "Nightcrawler", power: "Teleportation", id: 1 }]queryArrayAllPartialMatches
Returns all objects where the value for the key partially matches (string includes).
j_.queryArrayAllPartialMatches(xmen, 'power', 'optic')
// => [{ name: "Cyclops", power: "Optic blast", id: 2 }]queryArrayAllUniqueValues
Returns an array of unique values for a specific key.
j_.queryArrayAllUniqueValues(xmen, 'power')
// => ['Teleportation', 'Optic blast', 'Absorbing powers', 'Regeneration']queryArrayOneOfEach
Returns an object where keys are the unique values of the specified key, and values are the corresponding objects (last match wins).
j_.queryArrayOneOfEach(xmen, 'power')
// => { "Teleportation": {...}, "Optic blast": {...}, ... }queryArrayMaxValue
Returns the object containing the maximum value for a given key.
j_.queryArrayMaxValue(xmen, 'id')
// => { name: "Wolverine", power: "Regeneration", id: 4 }removeFirstMatchFromArray
Removes the first object matching the key/value pair from the array (modifies array in place).
j_.removeFirstMatchFromArray(xmen, 'name', 'Cyclops')sortArrayBy
Sorts an array of objects by a key. Prefix with - for descending order.
j_.sortArrayBy(xmen, 'name') // Ascending
j_.sortArrayBy(xmen, '-id') // DescendingshuffleArray
Randomly shuffles an array (modifies array in place).
j_.shuffleArray(xmen)removeKeyFromAllArrayObjs
Removes a specific key from all objects in the array.
j_.removeKeyFromAllArrayObjs(xmen, 'power')removeMatchedObjectsFromArray
Removes all objects matching the key and one of the values provided (array or comma-separated string).
j_.removeMatchedObjectsFromArray(xmen, 'id', [1, 3])Object Operations
get
Safely gets a nested property.
const obj = { a: { b: { c: 1 } } }
j_.get(obj, 'a.b.c') // => 1
j_.get(obj, 'a.b.x') // => undefinedisPlainObject
Checks if a value is a plain object.
j_.isPlainObject({}) // => true
j_.isPlainObject([]) // => false
j_.isPlainObject(null) // => falsearrayOfKeyValuesFromObject
Extracts values for a specific key from an object of objects.
const data = { a: { id: 1 }, b: { id: 2 } }
j_.arrayOfKeyValuesFromObject(data, 'id') // => [1, 2]stringOfKeyValuesFromObject
Same as above but returns a comma-separated string.
j_.stringOfKeyValuesFromObject(data, 'id') // => "1, 2"queryObjectFirstMatch
Searches an object of objects for the first matching key/value.
j_.queryObjectFirstMatch(data, 'id', 2) // => { id: 2 }convertObj2array
Converts an object of objects into an array of objects.
j_.convertObj2array(data) // => [{ id: 1 }, { id: 2 }]mergeObjects
Merges source object into destination object.
j_.mergeObjects({ a: 1 }, { b: 2 }) // => { b: 2, a: 1 }cloneObject
Creates a deep clone of a JSON-safe object.
const clone = j_.cloneObject(obj)sortObjectBy
Sorts an object's keys based on the values of a specific sub-key.
j_.sortObjectBy(data, 'id', 'id')addKeyToTopOfObject
Merges properties of the first object into the second, effectively putting them at the "top" if order matters.
j_.addKeyToTopOfObject({ z: 1 }, { a: 2 }) // => { a: 2, z: 1 } (Note: JS object key order isn't guaranteed)subVars
Substitutes {{variable}} placeholders in a string with values from an object.
j_.subVars('Hello {{name}}', { name: 'World' }) // => "Hello World"createTableFromUnstructuredData
Analyzes an array of objects and creates a normalized table structure with all unique columns.
j_.createTableFromUnstructuredData([{ a: 1 }, { b: 2 }])
// => { columnNames: ['a', 'b'], gridData: [...] }objSub
Performs variable substitution on all string values within an object.
j_.objSub({ msg: 'Hello {{name}}' }, { name: 'Dave' }) // => { msg: "Hello Dave" }String Operations
Given: const str = 'cat.dog.dolphin'
firstItemOf
Returns the first item based on a delimiter (defaults to auto-detecting , . / |).
j_.firstItemOf(str) // => 'cat'lastItemOf
Returns the last item.
j_.lastItemOf(str) // => 'dolphin'nthItemOf
Returns the nth item (1-based index).
j_.nthItemOf(str, 2) // => 'dog'allButFirstItemOf
Returns everything after the first delimiter.
j_.allButFirstItemOf(str) // => 'dog.dolphin'allButLastItemOf
Returns everything before the last delimiter.
j_.allButLastItemOf(str) // => 'cat.dog'randomItemOf
Returns a random item from the delimited string.
j_.randomItemOf(str) // => 'dog' (random)guessDelimiter
Returns the first matching delimiter from the set [',', '.', '/', '|'].
j_.guessDelimiter('a,b,c') // => ','removeSpaces
Removes all spaces from a string.
j_.removeSpaces(' h i ') // => 'hi'dashify
Converts to kebab-case (lowercase with dashes).
j_.dashify('Hello World') // => 'hello-world'toTitleCase
Converts to Title Case.
j_.toTitleCase('hello world') // => 'Hello World'decamelize
Converts camelCase to a delimited string (default _).
j_.decamelize('helloWorld') // => 'hello_world'snakeToCamel
Converts snake_case to camelCase.
j_.snakeToCamel('hello_world') // => 'helloWorld'camelToSnake
Converts camelCase to snake_case.
j_.camelToSnake('helloWorld') // => 'hello_world'slugify
Converts text to a URL-friendly slug, handling special characters.
j_.slugify('Hello World & Universe') // => 'hello-world-and-universe'Quote Operations
replaceHtmlAttributeQuotes
Replaces escaped double quotes \" with escaped single quotes \' inside HTML tags.
j_.replaceHtmlAttributeQuotes('<div class=\\"test\\">') // => '<div class=\'test\'>'educateQuotes
Converts straight quotes to smart/curly quotes.
j_.educateQuotes('"Hello"') // => '“Hello”'straightenQuotes
Converts smart/curly quotes to straight quotes.
j_.straightenQuotes('“Hello”') // => '"Hello"'quoteIfString
Wraps input in single quotes if it is a string.
j_.quoteIfString('test') // => "'test'"
j_.quoteIfString(1) // => 1backtickIfString
Wraps input in backticks if it is a string.
j_.backtickIfString('test') // => "`test`"escapeQuotes
Escapes quotes and backslashes in a string.
j_.escapeQuotes('It\'s "ok"') // => 'It\\\'s \\"ok\\"'quoteAndEscapeQuotesIfString
Combines quoting and escaping.
j_.quoteAndEscapeQuotesIfString('It\'s') // => "'It\\\'s'"quoteAndEducateQuotesIfString
Combines quoting and smart quoting.
j_.quoteAndEducateQuotesIfString('"Hi"') // => "'“Hi”'"addAdditionalSingleQuoteIfString
Doubles single quotes (often for SQL).
j_.addAdditionalSingleQuoteIfString("It's") // => "It''s"Random Operations
randomInteger
Returns a random integer between min and max (inclusive).
j_.randomInteger(1, 10)randomAlphaNumeric
Returns a random alphanumeric string of specified length.
j_.randomAlphaNumeric(8)randomCrayolaColor
Returns a random Crayola color name.
j_.randomCrayolaColor()randomColor
Alias for randomCrayolaColor.
j_.randomColor()randomHexColor
Returns a random hex color code.
j_.randomHexColor() // => "#f3a2b1"randomAnimal
Returns a random animal name.
j_.randomAnimal()uaid
Generates a unique ID: Letter_Timestamp_Random_Animal.
j_.uaid('A')ucid
Generates a unique ID: Letter_Timestamp_Random_Color.
j_.ucid('B')uniqID
Generates a complex unique ID.
j_.uniqID('prefix')id
Generates a simple random ID with prefix.
j_.id('user') // => "userx7d8s9..."randomLoadingMessage
Returns a random funny loading message.
j_.randomLoadingMessage()randomSuccessQuote
Returns a random motivational quote.
j_.randomSuccessQuote()Validation Operations
validEmailAddress
Validates standard email format.
j_.validEmailAddress('[email protected]') // => truevalidEmailAddressNonLatin
Validates email allowing non-latin characters.
j_.validEmailAddressNonLatin('[email protected]')luhnCheck
Validates numbers using the Luhn algorithm (credit cards, IMEIs).
j_.luhnCheck('79927398713') // => trueMisc Operations
openCleanWindow
Opens a new browser window with specific dimensions and settings.
j_.openCleanWindow('http://google.com')fillCleanWindowWithHTML
Opens a window and populates it with HTML content.
j_.fillCleanWindowWithHTML('myWindow')secondsToHms
Converts seconds to HH:MM:SS format.
j_.secondsToHms(3665) // => "01:01:05"hmsToSeconds
Converts HH:MM:SS to seconds.
j_.hmsToSeconds("01:01:05") // => 3665timeAgo
Returns a human-readable string for how long ago a date was.
j_.timeAgo(new Date(Date.now() - 600000)) // => "10 minutes ago"formatMonthYear
Formats strings like "MM-YYYY" to "MM/YY".
j_.formatMonthYear('12-2023') // => "12/23"decodeHtmlEntity
Decodes numeric HTML entities.
j_.decodeHtmlEntity('A') // => "A"decodeHTML
Same as decodeHtmlEntity.
j_.decodeHTML('A') // => "A"naturalSorter
Comparator for natural sort order (e.g. "File 2" before "File 10").
['f10', 'f2'].sort(j_.naturalSorter) // => ['f2', 'f10']trueFalse
Evaluates "truthiness" including handling empty objects as false.
j_.trueFalse({}) // => false
j_.trueFalse({ a: 1 }) // => truetf
Alias for trueFalse.
j_.tf(someVal)sleep
Returns a promise that resolves after N milliseconds.
await j_.sleep(1000)