Various utilities - classes with static getters and methods.
Installation
npm install @alius/utils
API
EnvUtils
Properties
isBrowser
Returns true if code is running in browser environment.
isNode
Returns true if code is running in Node.js environment.
isDeno
Returns true if code is running in Deno environment.
StringUtils
Properties
HTML_CHAR_MAP
Map of characters to HTML
XML_CHAR_MAP
Map of characters to XML
Methods
escapeHtml(text)
Escapes special characters so it is safe to add text to html as value.
Replaces following characters: & < > " ' \ \n \r \t \u2028 \u2029.
If parameter is not string - it is converted to string before escaping.
Returns empty string if parameter is null or undefined.
escapeXml(text)
Escapes special characters so it is safe to add text to xml as value.
Replaces following characters: & < > " '
If parameter is not string - it is converted to string before escaping.
Returns empty string if parameter is null or undefined.
escapeRegExp(text)
Escapes RegExp
control characters.
If parameter is not string - it is converted to string before escaping.
Returns empty string if parameter is null or undefined.
pretty(object, indent, indentLevel = 2)
Converts provided value to pretty string.
Object properties and array elements can be indented with specified number of spaces.
toUTF8Bytes(text)
Converts string to array of
UTF-8 bytes.
fromUTF8Bytes(bytes)
Converts array of UTF-8
bytes to string.
fromBase64(text)
Decodes base64 encoded string.
toBase64(bytes)
Encodes byte array to base64 string.
fromBase64url(text)
Decodes base64url encoded string.
toBase64url(bytes)
Encodes byte array to base64url string.
ObjectUtils
Types
Cloner
test: (value: any) => boolean
- function tests wether this cloner should be usedclone: (value: any, cloners: Array<Cloner>, path: Array<[any, any]>) => any
- function clones provided value
Cloner type.
Objects of this type are used in ObjectUtils.deepClone()
to clone provided values.
cloner.test()
is used to test if this cloner should be used to clone specified value.
cloner.clone()
should clone provided value.
If you need deep clone any internal property - add original and cloned values to path and
pass cloners and path params further down eg:
const cloned = {};
path.push([orig, cloned]);
cloned.internal1 = ObjectUtils.deepClone(orig.internal1, cloners, path);
cloned.internal2 = ObjectUtils.deepClone(orig.internal2, cloners, path);
Methods
deepFreeze(o)
Deep freezes provided object.
If provided object is array
- deep freezes all elements of that array.
If provided object is Set
- deep freezes all elements of that set.
If provided object is Map
- deep freezes all keys and values of that map.
If provided object is Object
- deep freezes all values of that object.
filter(obj, props = [])
Makes shallow object copy with only specified properties.
const o = {
prop1: 1,
prop2: "Hello",
prop3: true
};
console.log(ObjectUtils.filter(o, ["prop1", "prop3"])) // {prop1: 1, prop3: true}
If obj
is not an object - returns obj
.
If props
is empty - returns shallow copy of provided object.
If props
is specified - returned object will contain only properties specifed in it.
deepClone(object, cloners = [])
Deep clones specified object.
Supports following types:
- undefined - undefined
- null - null
- boolean - boolean
- number - number
- bigint - bigint
- string - string
- symbol - Does not clone: returns same Symbol object
- function - Does not clone: returns same function object. Covers AsyncFunction, AsyncGeneratorFunction, GeneratorFunction
- BigInt - Wrapper for primitive. Does not clone: returns same object
- Boolean - Wrapper for primitive. Does not clone: returns same object
- Number - Wrapper for primitive. Does not clone: returns same object
- String - Wrapper for primitive. Does not clone: returns same object
- Symbol - Wrapper for primitive. Does not clone: returns same object
- Atomics - JS defined object. Does not clone: returns same object
- globalThis - JS defined object. Does not clone: returns same object
- Intl - JS defined object. Does not clone: returns same object
- JSON - JS defined object. Does not clone: returns same object
- Math - JS defined object. Does not clone: returns same object
- Reflect - JS defined object. Does not clone: returns same object
- Error - Does not clone: returns same object. Covers all instances of Error
- ArrayBuffer|SharedArrayBuffer - new object with copied underlying buffer
- DataView - new object with copied underlying buffer
- TypedArray - new object with copied underlying buffer. Covers following typed buffers: BigInt64Array, BigUint64Array, Float32Array, Float64Array, Int16Array, Int32Array, Int8Array, Uint16Array, Uint32Array, Uint8Array, Uint8ClampedArray
- AsyncGenerator|Generator - Does not clone: returns same object
- FinalizationRegistry|WeakSet|WeakMap|WeakRef - Does not clone: returns same object
- Promise - Does not clone: returns same object
- Date - new Date created with same getTime() as original
- RegExp - new RegExp created with same pattern and flags as original
- Set - new Set with deep cloned elements
- Array - new Array with deep cloned elements
- Map - new Map with deep cloned keys and deep cloned values.
- Object - new Object with same prototype and deep cloned own properties.
Proxy instances are cloned as normal instances because there is no official way
to identify is provided object is a proxy or not
Handles circular references:
keeps track of all traversed objects and their respective clones;
if encounters reference to already traversed object - returns it's respective clone.
class Person {
#firstName;
#lastName;
constructor(firstName, lastName) {
this.#firstName = firstName;
this.#lastName = lastName;
}
get fullName() {
return this.#firstName + " " + this.#lastName;
}
clone() {
return new Person(this.#firstName, this.#lastName);
}
}
const o = {
person: new Person("John", "Doe"),
title: "worker",
started: new Date("2023-01-01"),
manager: new Person("Jane", "Smith")
};
const oc = ObjectUtils.deepClone(o, [{
test: value => value instanceof Person,
clone: value => value.clone()
}]);
getPathValue(obj, path)
Retrieves value from provided object via specified path.
If provided path is empty - returns initial obj
value.
If provided path can not be traversed - returns undefined
.
const o = {
prop1: [
1,
{
prop: "Hello"
},
false
],
prop2: "World"
};
console.log(ObjectUtils.getPathValue(o, "prop1[0]")) // 1
console.log(ObjectUtils.getPathValue(o, "prop1[1].prop")) // Hello
console.log(ObjectUtils.getPathValue(o, "prop2")) // World
ClassUtils
Types
ClassDescriptorType
- module: string - module name
- class?: string - class name
- method?: string - method name
Class descriptor type.
Objects of this type can be used to load classes
with Utils.loadClass().
Methods
isClassDescriptor(descriptor)
Tests is provided object is instance of ClassDescriptorType
loadClass(descriptor)
Loads class.
Local module (name starts with ./ or ../) will be loaded relative
to current working directory. Otherwise module (from node_modules) will be loaded.
If descriptor
contains property class
then
it will be used to select specific class from module export
otherwise default export will be used.
importTextModule(jsCode)
Loads javascript source code as module (import).
const code = `
export const hi = "Hello world";
export function sum(a, b) {
return a + b;
}
`;
const module = await ClassUtils.importTextModule(code);
console.log(module.hi); // Hello world
console.log(module.sum(1, 2)); // 3