jexl-extended
Version:
Extended grammar for Javascript Expression Language (JEXL)
1,339 lines (1,338 loc) • 46 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayEvery = exports.arrayAny = exports.arrayMap = exports.mapField = exports.arrayToObject = exports.arrayDistinct = exports.arraySort = exports.arrayShuffle = exports.arrayReverse = exports.arrayAppend = exports.switchCase = exports.not = exports.toBoolean = exports.average = exports.min = exports.max = exports.sum = exports.formatInteger = exports.formatBase = exports.formatNumber = exports.randomNumber = exports.sqrt = exports.power = exports.round = exports.ceil = exports.floor = exports.absoluteValue = exports.parseInteger = exports.toNumber = exports.formUrlEncoded = exports.base64Decode = exports.base64Encode = exports.replace = exports.arrayJoin = exports.split = exports.endsWith = exports.startsWith = exports.contains = exports.pad = exports.trim = exports.pascalCase = exports.camelCase = exports.lowercase = exports.uppercase = exports.substringAfter = exports.substringBefore = exports.substring = exports.length = exports.toJson = exports.toString = void 0;
exports.uuid = exports._eval = exports.dateTimeAdd = exports.dateTimeToMillis = exports.dateTimeFormat = exports.toDateTime = exports.millis = exports.now = exports.objectMerge = exports.objectEntries = exports.objectValues = exports.objectKeys = exports.arrayReduce = exports.arrayFindIndex = exports.arrayFind = exports.arrayFilter = void 0;
const date_fns_1 = require("date-fns");
const uuid_1 = require("uuid");
const _1 = __importDefault(require("."));
/**
* Casts the input to a string.
*
* @example
* string(123) // "123"
* 123|string // "123"
* @group Type Conversion
*
* @param input The input can be any type.
* @param prettify If true, the output will be pretty-printed.
* @returns The input converted to a JSON string representation.
*/
const toString = (input, prettify = false) => {
return JSON.stringify(input, null, prettify ? 2 : 0);
};
exports.toString = toString;
/**
* Parses the string and returns a JSON object.
*
* @example
* toJson('{"key": "value"}') // { key: "value" }
* '{"name": "John", "age": 30}'|toJson // { name: "John", age: 30 }
*
* @param input The JSON string to parse.
* @returns The parsed JSON object or value.
* @throws {SyntaxError} If the string is not valid JSON.
*/
const toJson = (input) => {
return JSON.parse(input);
};
exports.toJson = toJson;
/**
* Returns the number of characters in a string, or the length of an array.
*
* @example
* length("hello") // 5
* length([1, 2, 3]) // 3
*
* @param input The input can be a string, an array, or an object.
* @returns The number of characters in a string, or the length of an array.
*/
const length = (input) => {
if (typeof input === 'string') {
return input.length;
}
if (Array.isArray(input)) {
return input.length;
}
if (typeof input === 'object' && input !== null) {
return Object.keys(input).length;
}
return 0;
};
exports.length = length;
/**
* Gets a substring of a string.
*
* @example
* substring("hello world", 0, 5) // "hello"
*
* @param input The input string.
* @param start The starting index of the substring.
* @param length The length of the substring.
* @returns The substring of the input string.
*/
const substring = (input, start, length) => {
let str = input;
if (typeof str !== 'string') {
str = JSON.stringify(str);
}
if (typeof str === 'string') {
let startNum = start;
let len = length !== null && length !== void 0 ? length : str.length;
if (startNum < 0) {
startNum = str.length + start;
if (startNum < 0) {
startNum = 0;
}
}
if (startNum + len > str.length) {
len = str.length - startNum;
}
if (len < 0) {
len = 0;
}
return str.substring(startNum, startNum + len);
}
return '';
};
exports.substring = substring;
/**
* Returns the substring before the first occurrence of the character sequence chars in str.
*
* @example substringBefore("hello world", " ") // "hello"
* @param input The input string.
* @param chars The character sequence to search for.
* @returns The substring before the first occurrence of the character sequence chars in str.
*/
const substringBefore = (input, chars) => {
const str = typeof input === 'string' ? input : JSON.stringify(input);
const charsStr = typeof chars === 'string' ? chars : JSON.stringify(chars);
const index = str.indexOf(charsStr);
if (index === -1) {
return str;
}
return str.substring(0, index);
};
exports.substringBefore = substringBefore;
/**
* Returns the substring after the first occurrence of the character sequence chars in str.
*
* @example
* substringAfter("hello world", " ") // "world"
*
* @param input The input string.
* @param chars The character sequence to search for.
* @returns The substring after the first occurrence of the character sequence chars in str.
*/
const substringAfter = (input, chars) => {
const str = typeof input === 'string' ? input : JSON.stringify(input);
const charsStr = typeof chars === 'string' ? chars : JSON.stringify(chars);
const index = str.indexOf(charsStr);
if (index === -1) {
return '';
}
return str.substring(index + charsStr.length);
};
exports.substringAfter = substringAfter;
/**
* Converts the input string to uppercase.
*
* @example
* uppercase("hello") // "HELLO"
* "hello world"|uppercase // "HELLO WORLD"
*
* @param input The input to convert to uppercase. Non-string inputs are converted to JSON string first.
* @returns The uppercase string.
*/
const uppercase = (input) => {
const str = typeof input === 'string' ? input : JSON.stringify(input);
return str.toUpperCase();
};
exports.uppercase = uppercase;
/**
* Converts the input string to lowercase.
*
* @example
* lowercase("HELLO") // "hello"
* "HELLO WORLD"|lowercase // "hello world"
*
* @param input The input to convert to lowercase. Non-string inputs are converted to JSON string first.
* @returns The lowercase string.
*/
const lowercase = (input) => {
const str = typeof input === 'string' ? input : JSON.stringify(input);
return str.toLowerCase();
};
exports.lowercase = lowercase;
const splitRegex = /(?<!^)(?=[A-Z])|[`~!@#%^&*()|+\\\-=?;:'.,\s_']+/;
/**
* Converts the input string to camel case.
*
* @example
* camelCase("foo bar") // "fooBar"
* "hello-world"|camelCase // "helloWorld"
* camelCase("HELLO_WORLD") // "helloWorld"
*
* @param input The input string to convert to camel case.
* @returns The camel case string, or empty string if input is not a string.
*/
const camelCase = (input) => {
if (typeof input !== 'string')
return '';
return input.split(splitRegex).map((word, index) => {
if (index === 0)
return word.toLowerCase();
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}).join('');
};
exports.camelCase = camelCase;
/**
* Converts the input string to pascal case.
*
* @example
* pascalCase("foo bar") // "FooBar"
* "hello-world"|pascalCase // "HelloWorld"
* pascalCase("HELLO_WORLD") // "HelloWorld"
*
* @param input The input string to convert to pascal case.
* @returns The pascal case string, or empty string if input is not a string.
*/
const pascalCase = (input) => {
if (typeof input !== 'string')
return '';
return input.split(splitRegex).map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join('');
};
exports.pascalCase = pascalCase;
/**
* Trims whitespace from both ends of a string.
*
* @example
* trim(" hello ") // "hello"
* " world "|trim // "world"
* trim("__hello__", "_") // "hello"
*
* @param input The input string to trim.
* @param trimChar Optional character to trim instead of whitespace.
* @returns The trimmed string, or empty string if input is not a string.
*/
const trim = (input, trimChar) => {
if (typeof input === 'string') {
if (trimChar) {
return input.replace(new RegExp(`^${trimChar}+|${trimChar}+$`, 'g'), '');
}
return input.trim();
}
return '';
};
exports.trim = trim;
/**
* Pads the input string to the specified width.
*
* @example
* pad("hello", 10) // "hello "
* pad("world", -8, "0") // "000world"
* "foo"|pad(5, ".") // "foo.."
*
* @param input The input to pad. Non-string inputs are converted to JSON string first.
* @param width The target width. Positive values pad to the right, negative values pad to the left.
* @param char The character to use for padding. Defaults to space.
* @returns The padded string.
*/
const pad = (input, width, char = ' ') => {
const str = typeof input !== 'string' ? JSON.stringify(input) : input;
if (width > 0) {
return str.padEnd(width, char);
}
else {
return str.padStart(-width, char);
}
};
exports.pad = pad;
/**
* Checks if the input string or array contains the specified value.
*
* @example
* contains("hello world", "world") // true
* "foo-bar"|contains("bar") // true
* contains([1, 2, 3], 2) // true
*
* @param input The input string or array to search in.
* @param search The value to search for.
* @returns True if the input contains the search value, false otherwise.
*/
const contains = (input, search) => {
if (typeof input === 'string' || Array.isArray(input)) {
return input.includes(search);
}
return false;
};
exports.contains = contains;
/**
* Checks if the input string starts with the specified substring.
*
* @example
* startsWith("hello world", "hello") // true
* "foo-bar"|startsWith("foo") // true
* startsWith("test", "xyz") // false
*
* @param input The input string to check.
* @param search The substring to search for at the beginning.
* @returns True if the input starts with the search string, false otherwise.
*/
const startsWith = (input, search) => {
if (typeof input === 'string') {
return input.startsWith(search);
}
return false;
};
exports.startsWith = startsWith;
/**
* Checks if the input string ends with the specified substring.
*
* @example
* endsWith("hello world", "world") // true
* "foo-bar"|endsWith("bar") // true
* endsWith("test", "xyz") // false
*
* @param input The input string to check.
* @param search The substring to search for at the end.
* @returns True if the input ends with the search string, false otherwise.
*/
const endsWith = (input, search) => {
if (typeof input === 'string') {
return input.endsWith(search);
}
return false;
};
exports.endsWith = endsWith;
/**
* Splits the input string into an array of substrings.
*
* @example
* split("foo,bar,baz", ",") // ["foo", "bar", "baz"]
* "one-two-three"|split("-") // ["one", "two", "three"]
* split("hello world", " ") // ["hello", "world"]
*
* @param input The input string to split.
* @param separator The separator string to split on.
* @returns An array of substrings, or empty array if input is not a string.
*/
const split = (input, separator) => {
if (typeof input === 'string') {
return input.split(separator);
}
return [];
};
exports.split = split;
/**
* Joins elements of an array into a string.
*
* @example
* arrayJoin(["foo", "bar", "baz"], ",") // "foo,bar,baz"
* ["one", "two", "three"]|arrayJoin("-") // "one-two-three"
* arrayJoin([1, 2, 3]) // "1,2,3"
*
* @param input The input array to join.
* @param separator The separator string to use between elements. Defaults to comma.
* @returns The joined string, or undefined if input is not an array.
*/
const arrayJoin = (input, separator) => {
if (Array.isArray(input)) {
return input.join(separator);
}
return undefined;
};
exports.arrayJoin = arrayJoin;
/**
* Replaces occurrences of a specified string with a replacement string.
*
* @example
* replace("foo-bar-baz", "-", "_") // "foo_bar_baz"
* "hello world"|replace("world", "there") // "hello there"
* replace("test test test", "test", "demo") // "demo demo demo"
*
* @param input The input string to perform replacements on.
* @param search The string to search for and replace.
* @param replacement The string to replace matches with. Defaults to empty string.
* @returns The string with replacements made, or undefined if input is not a string.
*/
const replace = (input, search, replacement) => {
if (typeof input === 'string' && typeof search === 'string') {
const _replacement = replacement === undefined ? '' : replacement;
return input.replace(new RegExp(search, 'g'), _replacement);
}
return undefined;
};
exports.replace = replace;
/**
* Encodes a string to Base64.
*
* @example
* base64Encode("hello") // "aGVsbG8="
* "hello world"|base64Encode // "aGVsbG8gd29ybGQ="
* base64Encode("test") // "dGVzdA=="
*
* @param input The input string to encode.
* @returns The Base64 encoded string, or empty string if input is not a string or encoding fails.
*/
const base64Encode = (input) => {
if (typeof input === 'string') {
try {
encodeURIComponent(input);
const bytes = new TextEncoder().encode(input);
const binString = String.fromCodePoint(...bytes);
return btoa(binString);
}
catch (error) {
return '';
}
}
return '';
};
exports.base64Encode = base64Encode;
/**
* Decodes a Base64 encoded string.
*
* @example
* base64Decode("aGVsbG8=") // "hello"
* "aGVsbG8gd29ybGQ="|base64Decode // "hello world"
* base64Decode("dGVzdA==") // "test"
*
* @param input The Base64 encoded string to decode.
* @returns The decoded string, or empty string if input is not a string.
*/
const base64Decode = (input) => {
if (typeof input === 'string') {
const binString = atob(input);
const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
return new TextDecoder().decode(bytes);
}
return '';
};
exports.base64Decode = base64Decode;
/**
* Encodes a string or object to URI component format.
*
* @example
* formUrlEncoded("hello world") // "hello%20world"
* formUrlEncoded({name: "John", age: 30}) // "name=John&age=30"
* "hello & world"|formUrlEncoded // "hello%20%26%20world"
*
* @param input The input string or object to encode.
* @returns The URL encoded string, or empty string if input is not a string or object.
*/
const formUrlEncoded = (input) => {
if (typeof input === 'string') {
return encodeURIComponent(input);
}
else if (typeof input === 'object') {
return Object.keys(input).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(input[key])}`).join('&');
}
return '';
};
exports.formUrlEncoded = formUrlEncoded;
/**
* Converts the input to a number.
*
* @example
* toNumber("123") // 123
* "45.67"|toNumber // 45.67
* toNumber("abc") // NaN
*
* @param input The input to convert to a number.
* @returns The numeric value, or NaN if conversion fails.
*/
const toNumber = (input) => {
if (typeof input === 'number')
return input;
if (typeof input === 'string')
return parseFloat(input);
return NaN;
};
exports.toNumber = toNumber;
/**
* Parses a string and returns an integer.
*
* @example
* parseInteger("123") // 123
* "45.67"|parseInteger // 45
* parseInteger(123.89) // 123
*
* @param input The input to parse as an integer.
* @returns The integer value, or NaN if parsing fails.
*/
const parseInteger = (input) => {
if (typeof input === 'string') {
return parseInt(input, 10);
}
else if (typeof input === 'number') {
return Math.floor(input);
}
return NaN;
};
exports.parseInteger = parseInteger;
/**
* Returns the absolute value of a number.
*
* @example
* absoluteValue(-5) // 5
* (-10)|absoluteValue // 10
* absoluteValue(3.14) // 3.14
*
* @param input The input number to get the absolute value of.
* @returns The absolute value, or NaN if input cannot be converted to a number.
*/
const absoluteValue = (input) => {
const num = (0, exports.toNumber)(input);
return isNaN(num) ? NaN : Math.abs(num);
};
exports.absoluteValue = absoluteValue;
/**
* Rounds a number down to the nearest integer.
*
* @example
* floor(3.7) // 3
* (3.14)|floor // 3
* floor(-2.8) // -3
*
* @param input The input number to round down.
* @returns The rounded down integer, or NaN if input cannot be converted to a number.
*/
const floor = (input) => {
const num = (0, exports.toNumber)(input);
return isNaN(num) ? NaN : Math.floor(num);
};
exports.floor = floor;
/**
* Rounds a number up to the nearest integer.
*
* @example
* ceil(3.2) // 4
* (3.14)|ceil // 4
* ceil(-2.8) // -2
*
* @param input The input number to round up.
* @returns The rounded up integer, or NaN if input cannot be converted to a number.
*/
const ceil = (input) => {
const num = (0, exports.toNumber)(input);
return isNaN(num) ? NaN : Math.ceil(num);
};
exports.ceil = ceil;
/**
* Rounds a number to the nearest integer or to specified decimal places.
*
* @example
* round(3.7) // 4
* round(3.14159, 2) // 3.14
* (2.567)|round // 3
*
* @param input The input number to round.
* @param decimals Optional number of decimal places to round to.
* @returns The rounded number, or NaN if input cannot be converted to a number.
*/
const round = (input, decimals) => {
const num = (0, exports.toNumber)(input);
return isNaN(num) ? NaN : decimals ? Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals) : Math.round(num);
};
exports.round = round;
/**
* Returns the value of a number raised to a power.
*
* @example
* power(2, 3) // 8
* (2)|power(4) // 16
* power(9) // 81 (defaults to power of 2)
*
* @param input The base number.
* @param exponent The exponent to raise the base to. Defaults to 2.
* @returns The result of base raised to the exponent, or NaN if input cannot be converted to a number.
*/
const power = (input, exponent) => {
const num = (0, exports.toNumber)(input);
const exp = exponent === undefined ? 2 : exponent;
return isNaN(num) ? NaN : Math.pow(num, exp);
};
exports.power = power;
/**
* Returns the square root of a number.
*
* @example
* sqrt(16) // 4
* (25)|sqrt // 5
* sqrt(2) // 1.4142135623730951
*
* @param input The input number to get the square root of.
* @returns The square root of the input, or NaN if input cannot be converted to a number.
*/
const sqrt = (input) => {
const num = (0, exports.toNumber)(input);
return isNaN(num) ? NaN : Math.sqrt(num);
};
exports.sqrt = sqrt;
/**
* Generates a random number between 0 (inclusive) and 1 (exclusive).
*
* @example
* randomNumber() // 0.123456789 (example output)
* randomNumber() // 0.987654321 (different each time)
*
* @returns A random floating-point number between 0 and 1.
*/
const randomNumber = () => {
return Math.random();
};
exports.randomNumber = randomNumber;
/**
* Formats a number to a decimal representation as specified by the format string.
*
* @example
* formatNumber(1234.567, "#,##0.00") // "1,234.57"
* (1000)|formatNumber("0.00") // "1000.00"
* formatNumber(42, "#,###") // "42"
*
* @param input The input number to format.
* @param format The format string specifying decimal places and grouping.
* @returns The formatted number string, or empty string if input cannot be converted to a number.
*/
const formatNumber = (input, format) => {
var _a, _b, _c;
const num = typeof input === 'number' ? input : parseInt((0, exports.toNumber)(input).toString(), 10);
return isNaN(num) ? '' : num.toLocaleString('en-us', {
minimumFractionDigits: (_a = format.split('.')[1]) === null || _a === void 0 ? void 0 : _a.length,
maximumFractionDigits: (_b = format.split('.')[1]) === null || _b === void 0 ? void 0 : _b.length,
useGrouping: (_c = format.split('.')[0]) === null || _c === void 0 ? void 0 : _c.includes(',')
});
};
exports.formatNumber = formatNumber;
/**
* Formats a number as a string in the specified base.
*
* @example
* formatBase(255, 16) // "ff"
* (10)|formatBase(2) // "1010"
* formatBase(64, 8) // "100"
*
* @param input The input number to format.
* @param base The numeric base to convert to (2-36).
* @returns The number formatted in the specified base, or empty string if input cannot be converted to a number.
*/
const formatBase = (input, base) => {
const num = typeof input === 'number' ? input : parseInt((0, exports.toNumber)(input).toString(), 10);
return isNaN(num) ? '' : num.toString(base);
};
exports.formatBase = formatBase;
/**
* Formats a number as an integer with zero padding.
*
* @example
* formatInteger(42, "000") // "042"
* (7)|formatInteger("0000") // "0007"
* formatInteger(123, "00") // "123"
*
* @param input The input number to format.
* @param format The format string indicating the minimum number of digits.
* @returns The zero-padded integer string, or empty string if input cannot be converted to a number.
*/
const formatInteger = (input, format) => {
const num = (0, exports.toNumber)(input);
return isNaN(num) ? '' : (0, exports.pad)(Math.floor(num).toString(), -format.length, '0');
};
exports.formatInteger = formatInteger;
/**
* Calculates the sum of an array of numbers.
*
* @example
* sum([1, 2, 3, 4]) // 10
* [1.5, 2.5, 3.0]|sum // 7
* sum(1, 2, 3, 4) // 10
*
* @param input The input array of numbers or individual number arguments.
* @returns The sum of all numbers, or NaN if input is not an array.
*/
const sum = (...input) => {
if (!Array.isArray(input))
return NaN;
return input.flat().reduce((acc, val) => acc + (0, exports.toNumber)(val), 0);
};
exports.sum = sum;
/**
* Finds the maximum value in an array of numbers.
*
* @example
* max([1, 5, 3, 2]) // 5
* [10, 20, 15]|max // 20
* max(1, 5, 3, 2) // 5
*
* @param input The input array of numbers or individual number arguments.
* @returns The maximum value, or NaN if input is not an array.
*/
const max = (...input) => {
if (!Array.isArray(input))
return NaN;
return Math.max(...input.flat().map(exports.toNumber));
};
exports.max = max;
/**
* Finds the minimum value in an array of numbers.
*
* @example
* min([1, 5, 3, 2]) // 1
* [10, 20, 15]|min // 10
* min(1, 5, 3, 2) // 1
*
* @param input The input array of numbers or individual number arguments.
* @returns The minimum value, or NaN if input is not an array.
*/
const min = (...input) => {
if (!Array.isArray(input))
return NaN;
return Math.min(...input.flat().map(exports.toNumber));
};
exports.min = min;
/**
* Calculates the average of an array of numbers.
*
* @example
* average([1, 2, 3, 4]) // 2.5
* [10, 20, 30]|average // 20
* average(1, 2, 3, 4) // 2.5
*
* @param input The input array of numbers or individual number arguments.
* @returns The average value, or NaN if input is not an array.
*/
const average = (...input) => {
if (!Array.isArray(input))
return NaN;
const total = (0, exports.sum)(...input);
return total / input.flat().length;
};
exports.average = average;
/**
* Converts the input to a boolean.
*
* @example
* toBoolean("true") // true
* "false"|toBoolean // false
* toBoolean(1) // true
* toBoolean(0) // false
*
* @param input The input to convert to a boolean.
* @returns The boolean value, or undefined for ambiguous string values.
*/
const toBoolean = (input) => {
if (typeof input === 'boolean')
return input;
if (typeof input === 'number')
return input !== 0;
if (typeof input === 'string') {
if (input.trim().toLowerCase() === 'true' || input.trim() === '1')
return true;
if (input.trim().toLowerCase() === 'false' || input.trim() === '0')
return false;
else
return undefined;
}
return Boolean(input);
};
exports.toBoolean = toBoolean;
/**
* Returns the logical NOT of the input.
*
* @example
* not(true) // false
* false|not // true
* not(0) // true
* not("") // true
*
* @param input The input to apply logical NOT to.
* @returns The logical NOT of the input converted to boolean.
*/
const not = (input) => {
return !(0, exports.toBoolean)(input);
};
exports.not = not;
/**
* Evaluates a list of predicates and returns the first result expression whose predicate is satisfied.
*
* @example
* switch(expression, case1, result1, case2, result2, ..., default)
*
* @param args The arguments array where the first element is the expression to evaluate, followed by pairs of case and result, and optionally a default value.
* @returns The result of the first case whose predicate is satisfied, or the default value if no case is satisfied.
*/
const switchCase = (...args) => {
if (args.length < 3)
return null;
const expressionResult = args[0];
for (let i = 1; i < args.length - 1; i += 2) {
const caseResult = args[i];
if (JSON.stringify(expressionResult) === JSON.stringify(caseResult)) {
return args[i + 1];
}
}
// Return default
if (args.length % 2 === 0) {
const defaultResult = args[args.length - 1];
return defaultResult;
}
// Return null if no default specified
return null;
};
exports.switchCase = switchCase;
/**
* Appends elements to an array.
*
* @example
* append([1, 2], 3) // [1, 2, 3]
* [1, 2]|append(3, 4) // [1, 2, 3, 4]
* append([], 1, 2, 3) // [1, 2, 3]
*
* @param input The input values to append to an array.
* @returns A new array with all inputs flattened and appended, or empty array if no valid input.
*/
const arrayAppend = (...input) => {
if (!Array.isArray(input))
return [];
return [...input.flat()];
};
exports.arrayAppend = arrayAppend;
/**
* Reverses the elements of an array.
*
* @example
* reverse([1, 2, 3]) // [3, 2, 1]
* [1, 2, 3]|reverse // [3, 2, 1]
* reverse(["a", "b", "c"]) // ["c", "b", "a"]
*
* @param input The input values to reverse.
* @returns A new array with elements in reverse order, or empty array if no valid input.
*/
const arrayReverse = (...input) => {
if (!Array.isArray(input))
return [];
return [...input.flat()].reverse();
};
exports.arrayReverse = arrayReverse;
/**
* Shuffles the elements of an array randomly.
*
* @example
* shuffle([1, 2, 3]) // [2, 1, 3] (random order)
* [1, 2, 3]|shuffle // [3, 1, 2] (random order)
* shuffle(["a", "b", "c"]) // ["c", "a", "b"] (random order)
*
* @param input The input array to shuffle.
* @returns The same array with elements randomly shuffled, or empty array if input is not an array.
*/
const arrayShuffle = (input) => {
if (!Array.isArray(input))
return [];
for (let i = input.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[input[i], input[j]] = [input[j], input[i]];
}
return input;
};
exports.arrayShuffle = arrayShuffle;
/**
* Sorts the elements of an array.
*
* @example
* sort([3, 1, 2]) // [1, 2, 3]
* [3, 1, 2]|sort // [1, 2, 3]
* sort([{age: 30}, {age: 20}], "age") // [{age: 20}, {age: 30}]
* sort([{age: 30}, {age: 20}], "age", true) // [{age: 30}, {age: 20}]
*
* @param input The input array to sort.
* @param expression Optional JEXL expression to determine sort value for objects.
* @param descending Optional flag to sort in descending order.
* @returns A new sorted array, or empty array if input is not an array.
*/
const arraySort = (input, expression, descending) => {
if (!Array.isArray(input))
return [];
if (!expression)
return [...input].sort();
const expr = _1.default.compile(expression);
const compareFunction = (a, b) => {
const aValue = expr.evalSync(a);
const bValue = expr.evalSync(b);
if (aValue < bValue)
return descending ? -1 : 1;
if (aValue > bValue)
return descending ? 1 : -1;
return 0;
};
return [...input].sort(compareFunction);
};
exports.arraySort = arraySort;
/**
* Returns a new array with duplicate elements removed.
*
* @example
* distinct([1, 2, 2, 3, 1]) // [1, 2, 3]
* [1, 2, 2, 3]|distinct // [1, 2, 3]
* distinct(["a", "b", "a", "c"]) // ["a", "b", "c"]
*
* @param input The input array to remove duplicates from.
* @returns A new array with duplicates removed, or empty array if input is not an array.
*/
const arrayDistinct = (input) => {
if (!Array.isArray(input))
return [];
return [...new Set(input)];
};
exports.arrayDistinct = arrayDistinct;
/**
* Creates a new object based on key-value pairs or string keys.
*
* @example
* toObject([["name", "John"], ["age", 30]]) // {name: "John", age: 30}
* toObject("name", "John") // {name: "John"}
* toObject(["key1", "key2"], "defaultValue") // {key1: "defaultValue", key2: "defaultValue"}
*
* @param input The input string key or array of key-value pairs.
* @param val Optional default value for string keys or when array elements are strings.
* @returns A new object created from the input, or empty object if input is invalid.
*/
const arrayToObject = (input, val) => {
if (typeof input === 'string')
return { [input]: val };
if (!Array.isArray(input))
return {};
return input.reduce((acc, kv) => {
if (Array.isArray(kv) && kv.length === 2) {
acc[kv[0]] = kv[1];
return acc;
}
else if (typeof kv === 'string') {
acc[kv] = val;
return acc;
}
return acc;
}, {});
};
exports.arrayToObject = arrayToObject;
/**
* Returns a new array with elements transformed by extracting a specific field.
*
* @example
* mapField([{name: "John"}, {name: "Jane"}], "name") // ["John", "Jane"]
* [{age: 30}, {age: 25}]|mapField("age") // [30, 25]
* mapField([{x: 1, y: 2}, {x: 3, y: 4}], "x") // [1, 3]
*
* @param input The input array of objects to extract fields from.
* @param field The field name to extract from each object.
* @returns A new array with extracted field values, or empty array if input is not an array.
*/
const mapField = (input, field) => {
if (!Array.isArray(input))
return [];
return input.map(item => item[field]);
};
exports.mapField = mapField;
/**
* Returns an array containing the results of applying the expression parameter to each value in the array parameter.
* The expression must be a valid JEXL expression string, which is applied to each element of the array.
* The relative context provided to the expression is an object with the properties value, index and array (the original array).
*
* @example
* map([1, 2, 3], "value * 2") // [2, 4, 6]
* [{name: "John"}, {name: "Jane"}]|map("value.name") // ["John", "Jane"]
* map([1, 2, 3], "value + index") // [1, 3, 5]
*
* @param input The input array to transform.
* @param expression The JEXL expression to apply to each element.
* @returns A new array with transformed elements, or undefined if input is not an array.
*/
const arrayMap = (input, expression) => {
if (!Array.isArray(input))
return undefined;
const expr = _1.default.compile(expression);
return input.map((value, index, array) => {
return expr.evalSync({ value, index, array });
});
};
exports.arrayMap = arrayMap;
/**
* Checks whether the provided array has any elements that match the specified expression.
* The expression must be a valid JEXL expression string, and is applied to each element of the array.
* The relative context provided to the expression is an object with the properties value, index and array (the original array).
*
* @example
* any([1, 2, 3], "value > 2") // true
* [{age: 25}, {age: 35}]|any("value.age > 30") // true
* any([1, 2, 3], "value > 5") // false
*
* @param input The input array to test.
* @param expression The JEXL expression to test against each element.
* @returns True if any element matches the expression, false otherwise or if input is not an array.
*/
const arrayAny = (input, expression) => {
if (!Array.isArray(input))
return false;
const expr = _1.default.compile(expression);
return input.some((value, index, array) => {
return expr.evalSync({ value, index, array });
});
};
exports.arrayAny = arrayAny;
/**
* Checks whether the provided array has all elements that match the specified expression.
* The expression must be a valid JEXL expression string, and is applied to each element of the array.
* The relative context provided to the expression is an object with the properties value, index and array (the original array).
*
* @example
* every([2, 4, 6], "value % 2 == 0") // true
* [{age: 25}, {age: 35}]|every("value.age > 20") // true
* every([1, 2, 3], "value > 2") // false
*
* @param input The input array to test.
* @param expression The JEXL expression to test against each element.
* @returns True if all elements match the expression, false otherwise or if input is not an array.
*/
const arrayEvery = (input, expression) => {
if (!Array.isArray(input))
return false;
const expr = _1.default.compile(expression);
return input.every((value, index, array) => {
return expr.evalSync({ value, index, array });
});
};
exports.arrayEvery = arrayEvery;
/**
* Returns a new array with the elements of the input array that match the specified expression.
* The expression must be a valid JEXL expression string, and is applied to each element of the array.
* The relative context provided to the expression is an object with the properties value, index and array (the original array).
*
* @example
* filter([1, 2, 3, 4], "value > 2") // [3, 4]
* [{age: 25}, {age: 35}]|filter("value.age > 30") // [{age: 35}]
* filter([1, 2, 3, 4], "value % 2 == 0") // [2, 4]
*
* @param input The input array to filter.
* @param expression The JEXL expression to test against each element.
* @returns A new array containing only elements that match the expression, or empty array if input is not an array.
*/
const arrayFilter = (input, expression) => {
if (!Array.isArray(input))
return [];
const expr = _1.default.compile(expression);
return input.filter((value, index, array) => {
return expr.evalSync({ value, index, array });
});
};
exports.arrayFilter = arrayFilter;
/**
* Finds the first element in an array that matches the specified expression.
* The expression must be a valid JEXL expression string, and is applied to each element of the array.
* The relative context provided to the expression is an object with the properties value, index and array (the original array).
*
* @example
* find([1, 2, 3, 4], "value > 2") // 3
* [{name: "John"}, {name: "Jane"}]|find("value.name == 'Jane'") // {name: "Jane"}
* find([1, 2, 3], "value > 5") // undefined
*
* @param input The input array to search.
* @param expression The JEXL expression to test against each element.
* @returns The first element that matches the expression, or undefined if no match found or input is not an array.
*/
const arrayFind = (input, expression) => {
if (!Array.isArray(input))
return undefined;
const expr = _1.default.compile(expression);
return input.find((value, index, array) => {
return expr.evalSync({ value, index, array });
});
};
exports.arrayFind = arrayFind;
/**
*
* Finds the index of the first element in the input array that satisfies the given Jexl expression.
*
* @example
* [1, 2, 3, 4]|findIndex('value > 2'); // returns 2
*
* @param input - The array to search through.
* @param expression - A Jexl expression string to evaluate for each element. The expression has access to `value`, `index`, and `array`.
* @returns The index of the first matching element, or `-1` if no element matches, or `undefined` if the input is not an array.
*/
const arrayFindIndex = (input, expression) => {
if (!Array.isArray(input))
return undefined;
const expr = _1.default.compile(expression);
return input.findIndex((value, index, array) => {
return expr.evalSync({ value, index, array });
});
};
exports.arrayFindIndex = arrayFindIndex;
/**
* Returns an aggregated value derived from applying the function parameter successively to each value in array in combination with the result of the previous application of the function.
* The expression must be a valid JEXL expression string, and behaves like an infix operator between each value within the array.
* The relative context provided to the expression is an object with the properties accumulator, value, index and array (the original array).
*
* @example
* reduce([1, 2, 3, 4], "accumulator + value", 0) // 10
* [1, 2, 3]|reduce("accumulator * value", 1) // 6
* reduce(["a", "b", "c"], "accumulator + value", "") // "abc"
*
* @param input The input array to reduce.
* @param expression The JEXL expression to apply for each reduction step.
* @param initialValue The initial value for the accumulator.
* @returns The final accumulated value, or undefined if input is not an array.
*/
const arrayReduce = (input, expression, initialValue) => {
if (!Array.isArray(input))
return undefined;
const expr = _1.default.compile(expression);
return input.reduce((accumulator, value, index, array) => {
return expr.evalSync({ accumulator, value, index, array });
}, initialValue);
};
exports.arrayReduce = arrayReduce;
/**
* Returns the keys of an object as an array.
*
* @example
* keys({name: "John", age: 30}) // ["name", "age"]
* {a: 1, b: 2}|keys // ["a", "b"]
* keys({}) // []
*
* @param input The input object to get keys from.
* @returns An array of object keys, or undefined if input is not an object.
*/
const objectKeys = (input) => {
if (typeof input === 'object' && input !== null) {
return Object.keys(input);
}
return undefined;
};
exports.objectKeys = objectKeys;
/**
* Returns the values of an object as an array.
*
* @example
* values({name: "John", age: 30}) // ["John", 30]
* {a: 1, b: 2}|values // [1, 2]
* values({}) // []
*
* @param input The input object to get values from.
* @returns An array of object values, or undefined if input is not an object.
*/
const objectValues = (input) => {
if (typeof input === 'object' && input !== null) {
return Object.values(input);
}
return undefined;
};
exports.objectValues = objectValues;
/**
* Returns an array of key-value pairs from the input object.
*
* @example
* entries({name: "John", age: 30}) // [["name", "John"], ["age", 30]]
* {a: 1, b: 2}|entries // [["a", 1], ["b", 2]]
* entries({}) // []
*
* @param input The input object to get entries from.
* @returns An array of [key, value] pairs, or undefined if input is not an object.
*/
const objectEntries = (input) => {
if (typeof input === 'object' && input !== null) {
return Object.entries(input);
}
return undefined;
};
exports.objectEntries = objectEntries;
/**
* Returns a new object with the properties of the input objects merged together.
*
* @example
* merge({a: 1}, {b: 2}) // {a: 1, b: 2}
* {a: 1}|merge({b: 2}, {c: 3}) // {a: 1, b: 2, c: 3}
* merge({a: 1}, {a: 2}) // {a: 2} (later values override)
*
* @param args The input objects to merge.
* @returns A new object with all properties merged together.
*/
const objectMerge = (...args) => {
return args.reduce((acc, obj) => {
if (!Array.isArray(obj) && typeof obj === 'object' && obj !== null) {
return { ...acc, ...obj };
}
if (Array.isArray(obj)) {
for (const item of obj) {
if (typeof item === 'object' && item !== null) {
acc = { ...acc, ...item };
}
}
}
return acc;
}, {});
};
exports.objectMerge = objectMerge;
/**
* Returns the current date and time in the ISO 8601 format.
*
* @example
* now() // "2023-12-25T10:30:00.000Z"
* now() // "2023-12-25T14:45:30.123Z" (different time)
*
* @returns The current date and time as an ISO 8601 string.
*/
const now = () => {
return new Date().toISOString();
};
exports.now = now;
/**
* Returns the current date and time in milliseconds since the Unix epoch.
*
* @example
* millis() // 1703505000000
* millis() // 1703505123456 (different time)
*
* @returns The current timestamp in milliseconds.
*/
const millis = () => {
return Date.now();
};
exports.millis = millis;
/**
* Parses the number of milliseconds since the Unix epoch or parses a string (with or without specified format) and returns the date and time in the ISO 8601 format.
*
* @example
* toDateTime(1703505000000) // "2023-12-25T10:30:00.000Z"
* toDateTime("2023-12-25") // "2023-12-25T00:00:00.000Z"
* toDateTime("25/12/2023", "dd/MM/yyyy") // "2023-12-25T00:00:00.000Z"
* toDateTime() // Current date/time (same as now())
*
* @param input Optional timestamp in milliseconds or date string.
* @param format Optional format string for parsing date strings.
* @returns The date and time as an ISO 8601 string, or undefined if parsing fails.
*/
const toDateTime = (input, format) => {
if (typeof input === 'number') {
return new Date(input).toISOString();
}
if (typeof input === 'string') {
if (format) {
// Add UTC as timezone if not provided
const _format = (format.includes('x') || format.includes('X')) ? format : `${format} X`;
const _input = (format.includes('x') || format.includes('X')) ? input : `${input} Z`;
return (0, date_fns_1.parse)(_input, _format, new Date()).toISOString();
}
return new Date(input).toISOString();
}
if (input === undefined) {
return new Date().toISOString();
}
return undefined;
};
exports.toDateTime = toDateTime;
/**
* Converts a date and time to a provided format.
*
* @example
* dateTimeFormat(datetime, format)
* datetime|dateTimeFormat(format)
*
* @param input The input date and time, either as a string or number.
* @param format The format to convert the date and time to.
* @returns The date and time in the specified format.
*/
const dateTimeFormat = (input, format) => {
let dateTime;
if (typeof input === 'string') {
dateTime = new Date(input);
}
else if (typeof input === 'number') {
dateTime = new Date(input);
}
else {
return null;
}
// Convert to UTC
const utcDateTime = new Date(dateTime.getTime() + dateTime.getTimezoneOffset() * 60000);
// Format the date
return (0, date_fns_1.format)(utcDateTime, format);
};
exports.dateTimeFormat = dateTimeFormat;
/**
* Parses the date and time in the ISO 8601 format and returns the number of milliseconds since the Unix epoch.
*
* @example
* dateTimeToMillis("2023-12-25T10:30:00.000Z") // 1703505000000
* "2023-01-01T00:00:00.000Z"|dateTimeToMillis // 1672531200000
* dateTimeToMillis("2023-12-25") // 1703462400000
*
* @param input The date and time string to parse.
* @returns The timestamp in milliseconds since Unix epoch.
*/
const dateTimeToMillis = (input) => {
return new Date(input).getTime();
};
exports.dateTimeToMillis = dateTimeToMillis;
/**
* Adds a time range to a date and time in the ISO 8601 format.
*
* @example
* dateTimeAdd("2023-12-25T10:30:00.000Z", "day", 1) // "2023-12-26T10:30:00.000Z"
* now()|dateTimeAdd("hour", -2) // Two hours ago
* dateTimeAdd("2023-01-01T00:00:00.000Z", "month", 3) // "2023-04-01T00:00:00.000Z"
*
* @param input The input date and time string in ISO 8601 format.
* @param unit The time unit to add ("day", "hour", "minute", "second", "month", "year", etc.).
* @param value The amount to add (can be negative to subtract).
* @returns The new date and time as an ISO 8601 string.
*/
const dateTimeAdd = (input, unit, value) => {
// if unit doesn't end with 's' add it
const _unit = unit.toLowerCase().endsWith('s') ? unit.toLowerCase() : `${unit.toLowerCase()}s`;
const returnDate = (0, date_fns_1.add)(new Date(input), { [_unit]: value });
return returnDate.toISOString();
// dateAdd(new Date(input), { [unit]: value });
};
exports.dateTimeAdd = dateTimeAdd;
/**
* Evaluates a JEXL expression and returns the result.
* If only one argument is provided, it is expected that the first argument is a JEXL expression.
* If two arguments are provided, the first argument is the context (must be an object) and the second argument is the JEXL expression.
* The expression uses the default JEXL extended grammar and can't use any custom defined functions or transforms.
*
* @example
* _eval("1 + 2") // 3
* _eval({x: 5, y: 10}, "x + y") // 15
* "2 * 3"|_eval // 6
* _eval({name: "John"}, "name") // "John"
*
* @param input Either a JEXL expression string or a context object.
* @param expression Optional JEXL expression when first argument is context.
* @returns The result of evaluating the expression, or undefined if evaluation fails.
*/
const _eval = (input, expression) => {
if (expression === undefined) {
const _input = typeof input === 'string' ? input : JSON.stringify(input);
return _1.default.evalSync(_input);
}
if (typeof input === 'object') {
return _1.default.evalSync(expression, input);
}
return undefined;
};
exports._eval = _eval;
/**
* Generates a new UUID (Universally Unique Identifier).
*
* @example
* uuid() // "123e4567-e89b-12d3-a456-426614174000"
* uuid() // "987fcdeb-51a2-43d7-b123-456789abcdef" (different each time)
*
* @returns A new UUID v4 string.
*/
const uuid = () => {
return (0, uuid_1.v4)();
};
exports.uuid = uuid;