Calculator Library - Utils
Praise Magidi avatar
Written by Praise Magidi
Updated over a week ago

utils provides a wide range of utility functions for various operations, including data type conversion, mathematical calculations, object manipulation, cryptographic operations, string handling, date operations, and much more. These assist in data manipulation, data validation, object manipulation, cryptographic operations, etc.

This article provides information on the following Utils that can be used in the Calculator step:

convert(val, toType, format)

Converts a value to a specified data type using the provided format.

Parameters

  • val: The value to convert.

  • toType: The data type to convert to.

  • format: The format to use (default: 'default').

round(num, precision)

Rounds a number to a specified precision.

Parameters

  • num: The number to round.

  • precision: The precision to round to.

copy(obj)

Makes a copy of an object.

Parameters

  • obj: The object to copy.

Example

const obj = {
name: "Peter Parker",
alias: "Spiderman"
};

let obj2 = utils.copy(obj);
// obj2 = {name: "Peter Parker",alias: "Spiderman"}

Returns

  • object: A copy of the object.

hash(obj, options)

Creates a hash from an object using the specified options.

Parameters

  • obj: The object to hash.

  • options: Additional options.

Returns

  • string: The hash of the object.

createBuffer(obj, encoding)

Creates a buffer from a string, array, Buffer, or ArrayBuffer.

Parameters

  • obj: The object to create a buffer from (String, Array, Buffer, ArrayBuffer).

  • encoding: Optional. If the object is a string, this parameter is used to specify its encoding.

Returns

  • Buffer: The created buffer.

Example

let string = "Peter Parker";
let buf = utils.createBuffer(string, 'utf8');
// buf is a Buffer object

concatBuffer(...buffers)

Concatenates multiple buffers into a single buffer.

Parameters

  • buffers: An array of buffers to concatenate.

Returns

  • Buffer: The concatenated buffer.

jwtSign(payload, key, options)

Creates a JSON Web Token (JWT) for the provided payload.

Parameters

  • payload: The payload to sign.

  • key: The key to sign with.

  • options: Additional options, including algorithm, expiration, issuer, and more.

Returns

  • string: The JWT.

jwtVerify(jwt, key, options)

Verifies a JSON Web Token (JWT) using the provided key and options.

Parameters

  • jwt: The JWT to verify.

  • key: The key to verify with.

  • options: Additional options, including algorithms, audience, issuer, and more.

Returns

  • object: The decoded JWT.

cryptoCreateHash(algorithm, options)

Creates and returns a Hash object for generating hash digests.

Parameters

  • algorithm: The hashing algorithm.

  • options: Optional options to control stream behavior.

cryptoCreateHmac(algorithm, key, options)

Creates a Hash-based Message Authentication Code (HMAC) using the specified algorithm and key.

Parameters

  • algorithm: The HMAC algorithm.

  • key: The HMAC key.

  • options: Additional options, including encoding.

randomBytes(size)

Generates cryptographically strong pseudorandom data as a Buffer.

Parameters

  • size: The number of bytes to generate.

Returns

  • Buffer: The generated random data.

Example

let random = utils.randomBytes(128);

dayjs(date, timezone)

Creates a Day.js object with the specified date and timezone.

Parameters

  • date: The date to create.

  • timezone: The timezone to use.

For more information on the returned object visit Day.js

Example

let djsDate = utils.dayjs(new Date(), "utc");
// djsDate = "2023-10-24T12:25:42.635Z"
let threeDaysFromNow = djsDate.add(3, 'day');
// threeDaysFromNow = "2023-10-27T12:25:42.635Z"

duration(length, unit)

Creates a duration using a specified length and unit.

Parameters

  • length: The length of the duration.

  • unit: The unit of the duration.

deepEqual(a, b, options)

Compares two objects a and b recursively to check if they are equal.

Parameters

  • a: The first object to compare.

  • b: The second object to compare.

  • options: Additional options, including strict equality.

mergeObjects(a, b, options)

Merges two objects a and b deeply, returning a new merged object.

Parameters

  • a: The first object to merge.

  • b: The second object to merge.

  • options: Additional options, including array merging and cloning.

Example

const obj1 = {
name: "Peter Parker",
alias: "Spiderman"
}
const obj2 = {
city: "New York City",
age: 18
}
const result = utils.mergeObjects(obj1, obj2);
// result = {name: "Peter Parker", alias: "Spiderman", city: "New York City", age: 18}

isObject(val)

Checks if a value is an object.

Parameters

  • val: The value to check.

Returns

  • boolean: true if the value is an object, false otherwise.

isArray(val)

Checks if a value is an array.

Parameters

  • val: The value to check.

Returns

  • boolean: true if the value is an array, false otherwise.

isEmptyObject(obj)

Checks if an object is empty.

Parameters

  • obj: The object to check.

Returns

  • boolean: true if the object is empty, false otherwise.

isAssigned(thing)

Checks if a value is not null or undefined.

Parameters

  • thing: The value to check.

Returns

  • boolean: true if the value is not null or undefined, false otherwise.

isString(val)

Checks if a value is a string.

Parameters

  • val: The value to check.

Returns

  • boolean: true if the value is a string, false otherwise.

isBuffer(val)

Checks if a value is a Buffer.

Parameters

  • val: The value to check.

Returns

  • boolean: true if the value is a Buffer, false otherwise.

isInteger(val)

Checks if a value is an integer.

Parameters

  • val: The value to check.

Returns

  • boolean: true if the value is an integer, false otherwise.

isNumber(val)

Checks if a value is a number.

Parameters

  • val: The value to check.

Returns

  • boolean: true if the value is a number, false otherwise.

isBoolean(val)

Checks if a value is a boolean.

Parameters

  • val: The value to check.

Returns

  • boolean: true if the value is a boolean, false otherwise.

isDate(val)

Checks if a value is a date.

Parameters

  • val: The value to check.

Returns

  • boolean: true if the value is a date, false otherwise.

isFloat(val)

Checks if a value is a float.

Parameters

  • val: The value to check.

Returns

  • boolean: true if the value is a float, false otherwise.

jsonGet(obj, path, separator, ignoreSeparator)

Lookup a value in an object by path.

Parameters

  • obj: The object or array to check.

  • path: The path to retrieve.

  • separator (optional): The path separator, either slash or dot.

  • ignoreSeparator (optional): Whether to ignore the separation or not.

Example

let obj = {
name: "Peter Parker",
alias: "Spiderman",
city: "New York City",
age: 18,
address: {
street: "20 Ingram Street"
}
}
let street = utils.jsonGet("address.street", "20 Ingram Street")
// street = "20 Ingram Street"

jsonSet(obj, path, value, ignoreSeparator)

Set a value for the path on the specified object.

Parameters

  • obj: The object or array to set the value on.

  • path: The path to set the value on.

  • value: The value to set.

  • ignoreSeparator (optional): Whether to ignore the separation or not.

Example

let obj = {
name: "Peter Parker",
alias: "Spiderman",
city: "New York City",
age: 18
}

utils.jsonSet(obj, "address.street", "20 Ingram Street", false)
// obj = {
// name: "Peter Parker",
// alias: "Spiderman",
// city: "New York City",
// age: 18,
// address: {
// street: "20 Ingram Street"
// }
//}

jsonWalk(obj, iterator, separator)

Walk an object or array and call an iterator function.

Parameters

  • obj: The object or array to walk.

  • iterator: The iterator function.

  • separator (optional): The path separator.

formatDate(date, format)

Converts a date to a new format.

Parameters

  • date: The date to convert.

  • format: The format to convert to.

Example

let inputRecord = input.record;
const date = "July 16 1969 13:32:00";
inputRecord.date = utils.formatDate(date, "YYYY-MM-DD HH:mm:ss");

return inputRecord;
// inputRecord = {date: "1969-07-16 13:32:00"}

generateSchemaFromJSON(obj)

Generates a schema from the provided JSON object.

Parameters

  • obj: The object to generate a schema from.

Returns

  • object: The generated schema.

Example

let inputRecord = input.record;
let obj = {
name: "Peter Parker",
alias: "Spiderman",
city: "New York City",
age: 18
};

let schema = utils.generateSchemaFromJSON(obj);
// schema = {
// "type": "object",
// "properties": {
// "name": {
// "type": "string",
// "stringLength": 12
// },
// "alias": {
// "type": "string",
// "stringLength": 9
// },
// "city": {
// "type": "string",
// "stringLength": 13
// },
// "age": {
// "type": "integer"
// }
// }
// }

mergeSchemas(schemas)

Merges multiple schemas into one schema.

Parameters

  • schemas: The schemas to merge.

Returns

  • object: The merged schema.

flattenSchema(schema)

Creates a flattened schema from the provided schema.

Parameters

  • schema: The schema to flatten.

Returns

  • object[]: The flattened schema.

Example

let inputRecord = input.record;
let schema = {
type: "object",
properties: {
name: {
type: "string",
stringLength: 12,
},
alias: {
type: "string",
stringLength: 9,
},
city: {
type: "string",
stringLength: 13,
},
age: {
type: "integer",
},
},
};

const result = utils.flattenSchema(schema);
// result = {
// type: "object",
// properties: {
// name: {
// type: "string",
// stringLength: 12,
// },
// alias: {
// type: "string",
// stringLength: 9,
// },
// city: {
// type: "string",
// stringLength: 13,
// },
// age: {
// type: "integer",
// },
// },
// };

validateSchema(document, schema, coerce, showAllErrors)

Validates an object against a schema.

Parameters

  • document: The object to validate.

  • schema: The schema to validate against.

  • coerce: Whether to coerce values or not.

  • showAllErrors: Whether to show all validation errors.

Example

let inputRecord = input.record;
let schema = {
"type": "object",
"properties": {
"name": {
"type": "string",
"stringLength": 12
},
"alias": {
"type": "string",
"stringLength": 9
},
"city": {
"type": "string",
"stringLength": 13
},
"age": {
"type": "integer"
}
}
}
let obj = {
name: "Peter Parker",
alias: "Spiderman",
city: "New York City",
age: 18
};

let invalid= utils.validateSchema(obj, schema);
// invalid = null
let obj2 = {
name: "Peter Parker",
alias: "Spiderman",
city: "New York City",
age: "Just A Number"
};
invalid = utils.validateSchema(obj2, schema);
// {
// "message": "should be integer",
// "dataPath": ".age",
// "keyword": "type",
// "schemaPath": "#/properties/age/type"
// }

escapeXml(s)

Replaces all occurrences of unsafe characters in a string with their escaped counterparts.

Parameters

  • s: The string to escape.

parseAddress(address)

Parses an address into its components.

Parameters

  • address: The address to parse.

Example

let address = "20 Ingram Street, Forest Hills, Queens"
const parsedAddress = utils.parseAddress(address);
// parsedAddress = {
// "originalAddress": "20 Ingram Street, Forest Hills, Queens",
// "addressLine1": "20 Ingram St",
// "streetNumber": "20",
// "streetSuffix": "St",
// "streetName": "Ingram"
// }

toposort(nodes, reverse)

Sorts an array of nodes topologically.

Parameters

  • nodes: The nodes to sort.

  • reverse: Whether to reverse the sort or not.

xsdToJsonSchema(schemas, returnSchema)

Converts XML Schema Definitions (XSD) to JSON Schema.

Parameters

  • schemas: The XSD schemas to convert.

  • returnSchema: Whether to return the schema.

generateUUID()

Generates a UUID (Universally Unique Identifier).

Returns

  • string: The generated UUID.

generateObjectId()

Generates an ObjectId.

Example

let newId = utils.generateObjectId();
// newId = "6537b938685876233821ba33"

Did this answer your question?