addGlobal()assert()capitalize()checkErr()daysToMsec()fmtList()fmtTime()hoursToMsec()isArray()isError()isFunction()isNumber()isPlainObject()isString()isSymbol()isValidEmail()jsonParse()logEventTime()logMsg()minutesToMsec()oneOf()promiseTimeout()replaceCharAt()typeOf()unused()versionCompare()wait()timing object
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.
addGlobal() addGlobal(name, value)
Add a name to the global namespace. In bowsers, this adds name to the window object.
namevalueassert() 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.
condcond is falsey.msgassert.noAlertassert.onFailure(msg) => {...} that reports an assertion failure. When it is set, it is called with the msg string instead of calling console.assert() and displaying the popup. (The failure is still logged with logMsg() first.) Defaults to null. unitTest sets it while a test runs so that an assertion failure fails the running test.None.
capitalize() capitalize(str)
Returns the string str with the first letter capitalized.
strA string.
checkErr() 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.
valueError.checkMsg (optional)Error object's checkMsg property to, if present and truthy.Any type. value, if it is not an instance of Error.
daysToMsec() daysToMsec(days)
Returns the value of days converted to milliseconds.
daysA number of milliseconds.
fmtList() 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'
itemsend (optional)A string containing the list of items and the ending noun.
fmtTime() fmtTime(minutes)
Returns the time in minutes as <hours>:<minutes>. For example:
fmtTime(120) === '2:00'
fmtTime(45) === '0:45'
minutesA string containing formatted time.
hoursToMsec() hoursToMsec(hours)
Returns the value of hours converted to milliseconds.
hoursA number of milliseconds.
isArray() isArray(value)
Returns true if value is an Array.
valueA Boolean.
isError() isError(value)
Returns true if value is an instance of class Error.
valueA Boolean.
isFunction() isFunction(value)
Returns true if value is a function.
valueA Boolean.
isNumber() isNumber(value)
Returns true if value is a Number.
valueA Boolean.
isPlainObject() isPlainObject(value)
Returns true if value is a plain Object and not an instance of a class other than Object.
valueA Boolean.
isString() isString(value)
Returns true if value is a String.
valueA Boolean.
isSymbol() isSymbol(value)
Returns true if value is a Symbol.
valueA Boolean.
isValidEmail() 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).
strA Boolean.
jsonParse() 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.
strdflt (optional)null.Any type. The result of parsing str.
logEventTime() 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.
strdeltaStart (optional)logEventTime(). If provided, logEventTime() will log the delta between deltaStart and the current time.A number in milliseconds.
logMsg() 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.
strNone.
minutesToMsec() minutesToMsec(minutes)
Returns the value of minutes converted to milliseconds.
minutesA number of milliseconds.
oneOf() oneOf(value, ...args)
Returns true if value is included as one of the remaining arguments. A shorter version of:
[...args].includes(value)
valueargsvalue.A Boolean.
promiseTimeout() 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.
promisetimetimeoutError (optional)time expiration.A Promise.
replaceCharAt() replaceCharAt(str, pos, c)
Returns a strings that is a copy of str with the character at position pos replaced with c.
strposstr appends c.cA string.
typeOf() 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.
valueA string.
unused() unused(...args)
Does nothing except return the number of arguments. Use unused() to record that certain argunments are unused to bypass lint checking.
argsA number. The number of arguments passed.
versionCompare() 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.
version1version2comp (optional)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() wait(time)
Returns a Promise that resolves after time milliseconds.
timetime is negative, then the returned Promise is immediately rejected.A Promise.
timing objectThe 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:
countavgmaxstarttiming.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.