UNPKG

basic-pragma

Version:

Configurable JSX pragma using a basic vdom

95 lines (94 loc) 2.77 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.join = exports.map = exports.filter = exports.forEach = exports.compact = exports.getLength = void 0; const common_1 = require("./common"); /** * (Lua-safe) Gets or sets the length of the array. This is a number one higher * than the highest index in the array. */ const getLength = (arr) => common_1.isLua ? Object.keys(arr).reduce((max, key) => { const keyAsNumber = parseInt(key); if (!Number.isNaN(keyAsNumber)) { return max > keyAsNumber ? max : keyAsNumber; } return max; }, 0) : arr.length; exports.getLength = getLength; /** * Removes nils from the array. */ const compact = (arr) => { if (!common_1.isLua) { return arr.filter((v) => v != null); } const length = (0, exports.getLength)(arr); const newArr = []; for (let i = 0; i < length; i++) { const val = arr[i]; if (val != null) newArr.push(val); } return newArr; }; exports.compact = compact; /** * (Lua-safe) Performs the specified action for each element in an array. */ const forEach = (arr, fn) => { if (!common_1.isLua) return arr.forEach((e, i) => fn(e, i)); const length = (0, exports.getLength)(arr); for (let i = 0; i < length; i++) fn(arr[i], i); }; exports.forEach = forEach; /** * (Lua-safe) Returns the elements of an array that meet the condition specified * in a callback function. */ exports.filter = ((arr, fn) => { if (!common_1.isLua) return arr.filter((e, i) => fn(e, i)); const length = (0, exports.getLength)(arr); const newArr = []; let n = 0; for (let i = 0; i < length; i++) { const v = arr[i]; if (fn(v, i)) newArr[n++] = v; } return newArr; }); /** * (Lua-safe) Calls a defined callback function on each element of an array, and * returns an array that contains the results. */ const map = (arr, fn) => { if (!common_1.isLua) return arr.map((e, i) => fn(e, i)); const length = (0, exports.getLength)(arr); const newArr = []; for (let i = 0; i < length; i++) newArr[i] = fn(arr[i], i); return newArr; }; exports.map = map; /** * (Lua-safe) Adds all the elements of an array into a string, separated by the * specified separator string. */ const join = (arr, separator = ",") => { if (!common_1.isLua) return arr.join(separator); const length = (0, exports.getLength)(arr); const strs = []; for (let i = 0; i < length; i++) { strs.push(arr[i].toString()); if (i < length - 1 && separator.length > 0) strs.push(separator); } return strs.join(""); }; exports.join = join;