General Functions Reference

Table of contents


Introduction

All general utility functions are properties of the global/window object and may be used without importing.

The global timing object, documented below, measures and accumulates time intervals.


Functions

addGlobal()

Syntax

addGlobal(name, value)

Add a name to the global namespace. In bowsers, this adds name to the window object.

Parameters


assert()

Syntax

assert(cond, msg)

Reports an assertion failure if cond is not true. Execution continues after an assertion failure. On failure, assert() first logs Assertion failure: followed by msg using logMsg(), which writes it to the console. If assert.onFailure is set, it is then called with msg and nothing else happens; otherwise, console.assert() is called and, unless assert.noAlert is true, a popup displays the msg string.

Parameters

Properties

Return value

None.


capitalize()

Syntax

capitalize(str)

Returns the string str with the first letter capitalized.

Parameters

Return value

A string.


checkErr()

Syntax

checkErr(value)
checkErr(value, checkMsg)

Check whether value is an instance of Error and, if it is, throw it as an exception. If checkMsg is present and truthy, it is set as the value of the Error object's checkMsg property.

Parameters

Return value

Any type. value, if it is not an instance of Error.


daysToMsec()

Syntax

daysToMsec(days)

Returns the value of days converted to milliseconds.

Parameters

Return value

A number of milliseconds.


fmtList()

Syntax

fmtList(items)
fmtList(items, end)

Returns the strings in items formatted as an English list with commas inserted as appropriate. If end is present, it is a noun that will appear at the end of the list and will have an 's' added to it if there is more than one item. For example:

fmtList(['a', 'b', 'c']) === 'a, b, and c'
fmtList(['a', 'b', 'c'], 'letter') === 'a, b, and c letters'
fmtList(['a'], 'letter') === 'a letter'

Parameters

Return value

A string containing the list of items and the ending noun.


fmtTime()

Syntax

fmtTime(minutes)

Returns the time in minutes as <hours>:<minutes>. For example:

fmtTime(120) === '2:00'
fmtTime(45) === '0:45'

Parameters

Return value

A string containing formatted time.


hoursToMsec()

Syntax

hoursToMsec(hours)

Returns the value of hours converted to milliseconds.

Parameters

Return value

A number of milliseconds.


isArray()

Syntax

isArray(value)

Returns true if value is an Array.

Parameters

Return value

A Boolean.


isError()

Syntax

isError(value)

Returns true if value is an instance of class Error.

Parameters

Return value

A Boolean.


isFunction()

Syntax

isFunction(value)

Returns true if value is a function.

Parameters

Return value

A Boolean.


isNumber()

Syntax

isNumber(value)

Returns true if value is a Number.

Parameters

Return value

A Boolean.


isPlainObject()

Syntax

isPlainObject(value)

Returns true if value is a plain Object and not an instance of a class other than Object.

Parameters

Return value

A Boolean.


isString()

Syntax

isString(value)

Returns true if value is a String.

Parameters

Return value

A Boolean.


isSymbol()

Syntax

isSymbol(value)

Returns true if value is a Symbol.

Parameters

Return value

A Boolean.


isValidEmail()

Syntax

isValidEmail(str)

Returns true if str is a string and the whole string is a valid email address of the form "x@y". The domain is a series of dot-separated labels and does not need to contain a dot (e.g., "x@localhost" is valid).

Parameters

Return value

A Boolean.


jsonParse()

Syntax

jsonParse(str)
jsonParse(str, dflt)

Returns the result of parsing str as a JSON string. If str can't be parsed, return null or dflt if provided. jsonParse() catches any JSON parsing exceptions.

Parameters

Return value

Any type. The result of parsing str.


logEventTime()

Syntax

logEventTime(str)
logEventTime(str, `deltaStart`)

Log an event with a time stamp using logMsg(). The log message includes the event str, the time since the application started, the time since the last event was logged, and, if deltaStart is provided, the time since deltaStart. All times are in milliseconds. logEventTime() returns the current time stamp in milliseconds. This value may be subsequently passed as the deltaStart argument to a later event, to record the time delta between the two.

Parameters

Return value

A number in milliseconds.


logMsg()

Syntax

logMsg(str)

Logs str to the console. It also appends str and a newline character to the logMsg.log property. To limit memory use, logMsg.log keeps only the most recent log text: when it grows beyond 128K characters, it is trimmed to its last 64K characters.

Parameters

Return value

None.


minutesToMsec()

Syntax

minutesToMsec(minutes)

Returns the value of minutes converted to milliseconds.

Parameters

Return value

A number of milliseconds.


oneOf()

Syntax

oneOf(value, ...args)

Returns true if value is included as one of the remaining arguments. A shorter version of:

[...args].includes(value)

Parameters

Return value

A Boolean.


promiseTimeout()

Syntax

promiseTimeout(promise, time)
promiseTimeout(promise, time, timeoutError)

Add a timeout to any Promise. promiseTimeout() returns a Promise that is rejected if promise doesn't resolve or reject before time milliseconds. In that case, it will reject with the value of timeoutError if provided or the string 'timeout' if timeoutError is not provided. If promise resolves or rejects before time expires, the Promise will resolve or reject with the values provided by the promise.

Parameters

Return value

A Promise.


replaceCharAt()

Syntax

replaceCharAt(str, pos, c)

Returns a strings that is a copy of str with the character at position pos replaced with c.

Parameters

Return value

A string.


typeOf()

Syntax

typeOf(value)

Returns the type of the value. Unlike the typeof operator, typeOf() detects the type of the built-in objects as well as class names: It detects the following types:

Type Returned string
Array array
BigInt bigint
Boolean boolean
Date date
Function function
Map map
Number number
Set set
String string
Symbol symbol
Undefined undefined

Other built-in objects (e.g., Error, HTMLImageElement, Blob) return their class name. Instances of classes and constructor functions return the class name (constructor.name) or the name of the constructor function, if available, or <noname> if the constructor has no name. Plain objects and null return the strings object and null, respectively; regular expressions and arguments objects are also detected.

Parameters

Return value

A string.


unused()

Syntax

unused(...args)

Does nothing except return the number of arguments. Use unused() to record that certain argunments are unused to bypass lint checking.

Parameters

Return value

A number. The number of arguments passed.


versionCompare()

Syntax

versionCompare(version1, version2)
versionCompare(version1, version2, comp)

Compares two version strings of the form 'X.Y.Z...'. If provided, comp limits how many version number segments to compare. Setting comp to 0 would only compare the first segment of each version string (e.g., 'X') and setting comp to a higher number compares more segments. For example, setting comp to 1 would only compare the first two segments of each version string (e.g., 'X.Y'). If one version string has fewer segments than the other, only the segments that both have are compared, so 'X.Y' is equal to 'X.Y.Z'. Segments are compared numerically (so '1.10' is newer than '1.9').

If version2 is missing (falsey), versionCompare() returns 1; otherwise, if version1 is missing, it returns -1.

versionCompare() returns zero if version1 is the same as version2 under the comp limit. It returns a positive number if version1 is more recent than version2 under the comp limit. It returns a negative number if version1 is older than version2 under the comp limit.

Parameters

Return value

A number. Zero means the versions strings are the same under the comp limit. A positive number means that version1 is more recent than version2 and a negative number means that version1 is older than version2 under the comp limits.


wait()

Syntax

wait(time)

Returns a Promise that resolves after time milliseconds.

Parameters

Return value

A Promise.


The timing object

The global timing object accumulates statistics about time intervals. Intervals are identified by an id, which can be any value usable as a Map key. Each id has an interval data object with the following properties:

timing.now()

timing.now()

Returns the current time in milliseconds. This uses performance.now(), which provides a high-resolution time relative to the page load.

timing.lookup()

timing.lookup(id)

Returns the interval data object for id. If id has not been used before, it is created with all of its values reset.

timing.start()

timing.start(id)

Starts timing an interval for id by recording the current time in the start property.

timing.stop()

timing.stop(id)

Stops timing the interval for id, increments count, updates avg and max, and sets start to 0. Returns the length of the interval in milliseconds.

timing.reset()

timing.reset(id)

Resets count, avg, max, and start to zero for id.

timing.resetAll()

timing.resetAll()

Resets the interval data for every id that has been used.