@panyam/tsutils
Version:
Some basic TS utils for personal use
79 lines • 2.14 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCircularReplacer = void 0;
exports.encodeAs = encodeAs;
exports.dictGet = dictGet;
exports.ifDefined = ifDefined;
exports.stripQuotes = stripQuotes;
exports.trimmedSplit = trimmedSplit;
exports.ArrayTimesN = ArrayTimesN;
exports.firstIndexOf = firstIndexOf;
function encodeAs(value, alphabet) {
let out = "";
const nDig = alphabet.length;
while (value > 0) {
const digit = value % nDig;
out = alphabet[digit] + out;
value = Math.floor(value / nDig);
}
return out;
}
function dictGet(dict, key, onmissing) {
if (!(key in dict)) {
if (typeof onmissing === "function")
return onmissing(key);
else
return onmissing;
}
return dict[key];
}
function ifDefined(value, elseVal = null) {
return typeof value === "undefined" ? elseVal : value;
}
function stripQuotes(str) {
str = str.trim();
if (str.startsWith('"'))
str = str.substring(1);
if (str.endsWith('"'))
str = str.substring(0, str.length - 1);
return str;
}
function trimmedSplit(value, delimiter) {
if (value == null)
return [];
return (value || "")
.split(delimiter)
.map((v) => v.trim())
.filter((v) => v.length > 0);
}
function ArrayTimesN(count, value) {
const out = [];
for (let i = 0; i < count; i++) {
out.push(value);
}
return out;
}
function firstIndexOf(items, cmpFunc, startIndex = 0, ensure = false) {
for (let i = startIndex; i < items.length; i++) {
if (cmpFunc(items[i]))
return i;
}
if (ensure) {
throw new Error("Matching item not found");
}
return -1;
}
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
exports.getCircularReplacer = getCircularReplacer;
//# sourceMappingURL=misc.js.map
;