helpers/jrh_misc

Collection of general purpose helper functions

Source:
Author:

Methods

(async, inner) asyncAwaitForEachFunctionCall(array, func)

Source:
See:

Take an iteratble (array) of objects and a function to call on each, and do an await function on each.

Example
asyncAwaitForEachFunctionCall([1 2 3], (x) => {console.log(x)})
Parameters:
Name Type Description
array array
func function

(async, inner) asyncAwaitForEachObjectKeyFunctionCall(array, func)

Source:
See:

Take an iteratble (array) of objects and a function to call on each, and do an await function on each.

Example
asyncAwaitForEachFunctionCall({key: val}}, (key, val) => {console.log(val)})
Parameters:
Name Type Description
array array
func function

(inner) asyncNextTick(func)

Source:

Just a wrapper for process.nextTick for use when running an async await from a non async function Having a dedicated function for this makes it easier to search for.

Example
asyncNextTick(async () => {await anAsyncFunc(a,b,c);})
Parameters:
Name Type Description
func function

(inner) copyMissingValues(target, source)

Source:
See:

Copy over any values with keys not already in target; leave others identical

Example
asyncAwaitForEachFunctionCall([1 2 3], (x) => {console.log(x)})
Parameters:
Name Type Description
target object
source object

(inner) createObjectFromJsonParse(str, defaultVal)

Source:

Simple wrapper around JSON.parse, which parses a json string and creates an object. Only thing extra we do is check for being passed in an empty string/null/undefined and return {} in that case

Parameters:
Name Type Description
str string
defaultVal *
Returns:

result of JSON.parse on string or if string is "" or undefined or null

(inner) DateNowPlusMinutes(expirationMinutes)

Source:

return a new Date() whose date is a certain number of minutes in the future; useful for setting expiration times

Parameters:
Name Type Description
expirationMinutes int
Returns:

Date

(inner) deepIterationCopy(src)

Source:

Performs a deep copy of an object, recursing into sub properties to clone them instead of reuse references

Notes

See Medium.com post on different ways to copy objects

Parameters:
Name Type Description
src *
Returns:

new object deep copy of the source

(inner) ErrorToHashableMapObject(err)

Source:

For Error object instances, convert to nice simple object

Parameters:
Name Type Description
err Error
Returns:

a standard object with name, message, stack features

(inner) findLongestPrefixAndRemainder(longstr, haystack, separatorStr)

Source:

Find the longest string in haystack which matches a prefix of longstr (with separatorStr or empty) Then return a tuple [longeststring, remainder] with separatorStr removed from longeststring and remainder

Parameters:
Name Type Description
longstr string
haystack array
separatorStr string

(inner) firstCoercedTrueValue(…args)

Source:

Accepts a variadic list of arguments and returns the first one that can be coerced to true.

Parameters:
Name Type Attributes Description
args * <repeatable>

variadic list of arguments

Returns:

the first arg that evaluates to true (e.g. not null, undefined, false, ""); if none found returns undefined

(inner) getCompactNowString()

Source:

Return current date as a compact string suitable for filename

Returns:

current date as string

(inner) getNiceDateValString()

Source:

Return date as a string in a nice format, in local time zone

Returns:

current date as string

(inner) getNiceDurationTimeMs(elapsedMs)

Source:

Nice string expressing duration at useful granularity

Parameters:
Name Type Description
elapsedMs integer
Returns:

human readable string describing the durations in milliseconds

(inner) getNiceNowString()

Source:

Return current date as a string in a nice format, in local time zone

Returns:

current date as string

(inner) getNonFalseValueOrDefault(val, defaultVal)

Source:

If val evaluates to false (which will happen on values of null, undefined, false, and ""), return defaultVal, otherwise return val.

Notes
  • The intention of this function is to be used to check if a value was provided for some option, and use a default if not.
  • This can be confusing if the false value is passed in and caller expects to get it back instead of the defaultVal
  • In previous version we explicitly tested val against null, undefined, and ""
  • The main reason to use a function for this instead of just using a line in code testing truthiness of val, is to help us locate these kind of tests in code via a search, since they are prone to issues.
Parameters:
Name Type Description
val *
defaultVal *
Returns:

val [if it evaluates to true] else defaultVal

(inner) getNonNullValueFromObject(obj, key, jrResult, hintMessage)

Source:

Returns the value of a property of an object, or pushes a JrResult error and returns null if not found

Parameters:
Name Type Description
obj *
key string
jrResult *
hintMessage *
Returns:

value of property or null if not found (and pushes JrResult error)

(inner) getNonNullValueOrDefault(val, defaultVal)

Source:

If val is not undefined and not null, return it; otherwise return default val.

Notes
  • The intention of this function is to be used to check if a value was provided for some option, and use a default if not.
  • This can be confusing if the false value is passed in and caller expects to get it back instead of the defaultVal
  • The main reason to use a function for this instead of just using a line in code testing truthiness of val, is to help us locate these kind of tests in code via a search, since they are prone to issues.
Parameters:
Name Type Description
val *
defaultVal *
Returns:

val [if it evaluates to true] else defaultVal

(inner) getPreciseNowString()

Source:

Return the current date in a standardized string format with precise timing; suitable for timestampign to seconds accuracy

Returns:

current date and time as string with seconds precision

(inner) getServerIpAddress()

Source:

Try to figure out the servers ip address, and return it as a string.

Notes
  • see stackoverflow post
  • This function has barely been tested and should not be considered reliable.
  • We are currently using it only to get a string that we can use to look for a site-specific configuration file based on the current server ip, and just to display on screen and in logs.
  • So our goal is simply to return a string that is different on different servers, but always the same on a given server
  • You cannot assume that the returned value is of a particular format; we dont check for that.
Returns:

string representation of ip address

(inner) isInAnyArray(val, …arrays)

Source:

Check if a value is present in any arrays

Parameters:
Name Type Attributes Description
val *
arrays array <repeatable>

(1 or more arrays passed as variadic arguements)

Returns:

true if val is found in any of the arrays

(inner) isObjectEmpty(obj)

Source:
See:

Checks if the passed argument is an empty object/array/list by checking its length

Parameters:
Name Type Description
obj *

an array, object, or iterable with length property, OR an undefined/null valued variable

Returns:

true if the passed obj evaluates to false (null, undefined, "", false) OR is an object/array with no properties.

(inner) isObjectHashMappableType(maybeObj)

Source:

Returns true if the passed value is derived from the Object class/constructor.

Parameters:
Name Type Description
maybeObj *
Returns:

true if the passed value is a object

(inner) isPromise(value)

Source:
See:

Returns true if the object passed is a promise

Parameters:
Name Type Description
value *
Returns:

true if the passed value is a promise

(inner) isSimpleObject(maybeObj)

Source:

Returns true if the passed value is derived from the Object class/constructor.

Notes
  • This will return false for object that are more elaborate classes, and is only meant to be used for doing deep copies of simple {} objects
  • This will return false if the passed value is null or undefined
  • This will return false if the passed object is a function (unlike the code it was based on)
  • see stackoverflow on checking if a value is an object
Parameters:
Name Type Description
maybeObj *
Returns:

true if the passed value is a (simple) object

(inner) makeSafeForFormInput(str)

Source:

Escape any characters or remove them, that would be illegal to have inside a form input value

Notes
  • Replaces double quote characters with "
Parameters:
Name Type Description
str string
Returns:

version of string with double quotes replaced, etc.

(inner) mergeArraysDedupe(array1, array2)

Source:

Combine two arrays and return the combined array, removing all duplicates

Parameters:
Name Type Description
array1 array
array2 array
Returns:

the combined de-duped array

(inner) mergeArraysKeepDupes(array1, array2)

Source:

Combine two arrays and return the concatenation; duplicates are not removed

Parameters:
Name Type Description
array1 array
array2 array
Returns:

concatenated array

(inner) objectHasProperty(obj, prop)

Source:

Simple wrapper that returns true if pop is a property of obj

Parameters:
Name Type Description
obj object
prop string
Returns:

returns true if pop is a property of obj

(inner) objToString(obj, flagCompact)

Source:

Stringify an object nicely for display on console

Notes
Parameters:
Name Type Description
obj *

the object to stringify

flagCompact *

if true then we use a compact single line output format

Returns:

string suitable for debug/diagnostic display

(inner) objToString2(obj, flagCompact)

Source:

Stringify2 an object nicely for display on console

Notes
Parameters:
Name Type Description
obj *

the object to stringify

flagCompact *

if true then we use a compact single line output format

Returns:

string suitable for debug/diagnostic display

(inner) regexEscapeStr(str)

Source:
To Do:
  • Security: check this for any security vulnerabilities

Replace special characters in string so it can be used in regex. This is useful when we want to use a user-provided string in a regular expression and so we need to validate/escape it first. It is used in our admin crud area filters to convert a simple user substring into a wildcard search string

Parameters:
Name Type Description
str string
Returns:

escaped version of string suitable for use inside a regular expression (i.e. no unescaped regex characters)

(inner) resolvePossiblyRelativeDirectory(dirpath, basedir)

Source:

If path starts with a . then resolve it relative to the passed basedir

Parameters:
Name Type Description
dirpath *
basedir *
Returns:

absolute path of dirpath

(inner) shallowCopy(source)

Source:

Copies an objects properties, in a shallow fashion (nested objects/arrays reuse the references)

Notes
Parameters:
Name Type Description
source object
Returns:

new object with cloned properties

(inner) stringArrayToNiceString(arr)

Source:

Simple wrapper arround array.toString that returns blank string if passed value is null, undefined, or empty

Parameters:
Name Type Description
arr array

an array or null or undefined

Returns:

arr.toString() if there are items in the array, otherwise empty string ""

(inner) usleep(ms)

Source:

Awaiting on this will sleep the program for a specified number of milliseconds. Used for testing. see https://stackoverflow.com/questions/14249506/how-can-i-wait-in-node-js-javascript-l-need-to-pause-for-a-period-of-time

Parameters:
Name Type Description
ms *