npm package: @jmellicker/j_
Description: Helpful JavaScript functions.
Latest version: 0.0.28

# 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:

```javascript
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.
```javascript
j_.indexFromArray(xmen, 'power', 'Optic blast') // => 1
```

### indexFromArrayID
Shorthand for `indexFromArray` specifically for the 'id' key.
```javascript
j_.indexFromArrayID(xmen, 2) // => 1
```

### queryArrayFirstMatch
Returns the first object in the array that matches the key/value pair.
```javascript
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.
```javascript
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).
```javascript
j_.queryArrayAllPartialMatches(xmen, 'power', 'optic')
// => [{ name: "Cyclops", power: "Optic blast", id: 2 }]
```

### queryArrayAllUniqueValues
Returns an array of unique values for a specific key.
```javascript
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).
```javascript
j_.queryArrayOneOfEach(xmen, 'power')
// => { "Teleportation": {...}, "Optic blast": {...}, ... }
```

### queryArrayMaxValue
Returns the object containing the maximum value for a given key.
```javascript
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).
```javascript
j_.removeFirstMatchFromArray(xmen, 'name', 'Cyclops')
```

### sortArrayBy
Sorts an array of objects by a key. Prefix with `-` for descending order.
```javascript
j_.sortArrayBy(xmen, 'name') // Ascending
j_.sortArrayBy(xmen, '-id')  // Descending
```

### shuffleArray
Randomly shuffles an array (modifies array in place).
```javascript
j_.shuffleArray(xmen)
```

### removeKeyFromAllArrayObjs
Removes a specific key from all objects in the array.
```javascript
j_.removeKeyFromAllArrayObjs(xmen, 'power')
```

### removeMatchedObjectsFromArray
Removes all objects matching the key and one of the values provided (array or comma-separated string).
```javascript
j_.removeMatchedObjectsFromArray(xmen, 'id', [1, 3])
```

---

## Object Operations

### get
Safely gets a nested property.
```javascript
const obj = { a: { b: { c: 1 } } }
j_.get(obj, 'a.b.c') // => 1
j_.get(obj, 'a.b.x') // => undefined
```

### isPlainObject
Checks if a value is a plain object.
```javascript
j_.isPlainObject({}) // => true
j_.isPlainObject([]) // => false
j_.isPlainObject(null) // => false
```

### arrayOfKeyValuesFromObject
Extracts values for a specific key from an object of objects.
```javascript
const data = { a: { id: 1 }, b: { id: 2 } }
j_.arrayOfKeyValuesFromObject(data, 'id') // => [1, 2]
```

### stringOfKeyValuesFromObject
Same as above but returns a comma-separated string.
```javascript
j_.stringOfKeyValuesFromObject(data, 'id') // => "1, 2"
```

### queryObjectFirstMatch
Searches an object of objects for the first matching key/value.
```javascript
j_.queryObjectFirstMatch(data, 'id', 2) // => { id: 2 }
```

### convertObj2array
Converts an object of objects into an array of objects.
```javascript
j_.convertObj2array(data) // => [{ id: 1 }, { id: 2 }]
```

### mergeObjects
Merges source object into destination object.
```javascript
j_.mergeObjects({ a: 1 }, { b: 2 }) // => { b: 2, a: 1 }
```

### cloneObject
Creates a deep clone of a JSON-safe object.
```javascript
const clone = j_.cloneObject(obj)
```

### sortObjectBy
Sorts an object's keys based on the values of a specific sub-key.
```javascript
j_.sortObjectBy(data, 'id', 'id')
```

### addKeyToTopOfObject
Merges properties of the first object into the second, effectively putting them at the "top" if order matters.
```javascript
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.
```javascript
j_.subVars('Hello {{name}}', { name: 'World' }) // => "Hello World"
```

### createTableFromUnstructuredData
Analyzes an array of objects and creates a normalized table structure with all unique columns.
```javascript
j_.createTableFromUnstructuredData([{ a: 1 }, { b: 2 }])
// => { columnNames: ['a', 'b'], gridData: [...] }
```

### objSub
Performs variable substitution on all string values within an object.
```javascript
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 , . / |).
```javascript
j_.firstItemOf(str) // => 'cat'
```

### lastItemOf
Returns the last item.
```javascript
j_.lastItemOf(str) // => 'dolphin'
```

### nthItemOf
Returns the nth item (1-based index).
```javascript
j_.nthItemOf(str, 2) // => 'dog'
```

### allButFirstItemOf
Returns everything after the first delimiter.
```javascript
j_.allButFirstItemOf(str) // => 'dog.dolphin'
```

### allButLastItemOf
Returns everything before the last delimiter.
```javascript
j_.allButLastItemOf(str) // => 'cat.dog'
```

### randomItemOf
Returns a random item from the delimited string.
```javascript
j_.randomItemOf(str) // => 'dog' (random)
```

### guessDelimiter
Returns the first matching delimiter from the set `[',', '.', '/', '|']`.
```javascript
j_.guessDelimiter('a,b,c') // => ','
```

### removeSpaces
Removes all spaces from a string.
```javascript
j_.removeSpaces(' h i ') // => 'hi'
```

### dashify
Converts to kebab-case (lowercase with dashes).
```javascript
j_.dashify('Hello World') // => 'hello-world'
```

### toTitleCase
Converts to Title Case.
```javascript
j_.toTitleCase('hello world') // => 'Hello World'
```

### decamelize
Converts camelCase to a delimited string (default `_`).
```javascript
j_.decamelize('helloWorld') // => 'hello_world'
```

### snakeToCamel
Converts snake_case to camelCase.
```javascript
j_.snakeToCamel('hello_world') // => 'helloWorld'
```

### camelToSnake
Converts camelCase to snake_case.
```javascript
j_.camelToSnake('helloWorld') // => 'hello_world'
```

### slugify
Converts text to a URL-friendly slug, handling special characters.
```javascript
j_.slugify('Hello World & Universe') // => 'hello-world-and-universe'
```

---

## Quote Operations

### replaceHtmlAttributeQuotes
Replaces escaped double quotes `\"` with escaped single quotes `\'` inside HTML tags.
```javascript
j_.replaceHtmlAttributeQuotes('<div class=\\"test\\">') // => '<div class=\'test\'>'
```

### educateQuotes
Converts straight quotes to smart/curly quotes.
```javascript
j_.educateQuotes('"Hello"') // => '“Hello”'
```

### straightenQuotes
Converts smart/curly quotes to straight quotes.
```javascript
j_.straightenQuotes('“Hello”') // => '"Hello"'
```

### quoteIfString
Wraps input in single quotes if it is a string.
```javascript
j_.quoteIfString('test') // => "'test'"
j_.quoteIfString(1) // => 1
```

### backtickIfString
Wraps input in backticks if it is a string.
```javascript
j_.backtickIfString('test') // => "`test`"
```

### escapeQuotes
Escapes quotes and backslashes in a string.
```javascript
j_.escapeQuotes('It\'s "ok"') // => 'It\\\'s \\"ok\\"'
```

### quoteAndEscapeQuotesIfString
Combines quoting and escaping.
```javascript
j_.quoteAndEscapeQuotesIfString('It\'s') // => "'It\\\'s'"
```

### quoteAndEducateQuotesIfString
Combines quoting and smart quoting.
```javascript
j_.quoteAndEducateQuotesIfString('"Hi"') // => "'“Hi”'"
```

### addAdditionalSingleQuoteIfString
Doubles single quotes (often for SQL).
```javascript
j_.addAdditionalSingleQuoteIfString("It's") // => "It''s"
```

---

## Random Operations

### randomInteger
Returns a random integer between min and max (inclusive).
```javascript
j_.randomInteger(1, 10)
```

### randomAlphaNumeric
Returns a random alphanumeric string of specified length.
```javascript
j_.randomAlphaNumeric(8)
```

### randomCrayolaColor
Returns a random Crayola color name.
```javascript
j_.randomCrayolaColor()
```

### randomColor
Alias for `randomCrayolaColor`.
```javascript
j_.randomColor()
```

### randomHexColor
Returns a random hex color code.
```javascript
j_.randomHexColor() // => "#f3a2b1"
```

### randomAnimal
Returns a random animal name.
```javascript
j_.randomAnimal()
```

### uaid
Generates a unique ID: `Letter_Timestamp_Random_Animal`.
```javascript
j_.uaid('A')
```

### ucid
Generates a unique ID: `Letter_Timestamp_Random_Color`.
```javascript
j_.ucid('B')
```

### uniqID
Generates a complex unique ID.
```javascript
j_.uniqID('prefix')
```

### id
Generates a simple random ID with prefix.
```javascript
j_.id('user') // => "userx7d8s9..."
```

### randomLoadingMessage
Returns a random funny loading message.
```javascript
j_.randomLoadingMessage()
```

### randomSuccessQuote
Returns a random motivational quote.
```javascript
j_.randomSuccessQuote()
```

---

## Validation Operations

### validEmailAddress
Validates standard email format.
```javascript
j_.validEmailAddress('test@example.com') // => true
```

### validEmailAddressNonLatin
Validates email allowing non-latin characters.
```javascript
j_.validEmailAddressNonLatin('test@example.com')
```

### luhnCheck
Validates numbers using the Luhn algorithm (credit cards, IMEIs).
```javascript
j_.luhnCheck('79927398713') // => true
```

---

## Misc Operations

### openCleanWindow
Opens a new browser window with specific dimensions and settings.
```javascript
j_.openCleanWindow('http://google.com')
```

### fillCleanWindowWithHTML
Opens a window and populates it with HTML content.
```javascript
j_.fillCleanWindowWithHTML('myWindow')
```

### secondsToHms
Converts seconds to HH:MM:SS format.
```javascript
j_.secondsToHms(3665) // => "01:01:05"
```

### hmsToSeconds
Converts HH:MM:SS to seconds.
```javascript
j_.hmsToSeconds("01:01:05") // => 3665
```

### timeAgo
Returns a human-readable string for how long ago a date was.
```javascript
j_.timeAgo(new Date(Date.now() - 600000)) // => "10 minutes ago"
```

### formatMonthYear
Formats strings like "MM-YYYY" to "MM/YY".
```javascript
j_.formatMonthYear('12-2023') // => "12/23"
```

### decodeHtmlEntity
Decodes numeric HTML entities.
```javascript
j_.decodeHtmlEntity('&#65;') // => "A"
```

### decodeHTML
Same as `decodeHtmlEntity`.
```javascript
j_.decodeHTML('&#65;') // => "A"
```

### naturalSorter
Comparator for natural sort order (e.g. "File 2" before "File 10").
```javascript
['f10', 'f2'].sort(j_.naturalSorter) // => ['f2', 'f10']
```

### trueFalse
Evaluates "truthiness" including handling empty objects as false.
```javascript
j_.trueFalse({}) // => false
j_.trueFalse({ a: 1 }) // => true
```

### tf
Alias for `trueFalse`.
```javascript
j_.tf(someVal)
```

### sleep
Returns a promise that resolves after N milliseconds.
```javascript
await j_.sleep(1000)
```