@js-data-tools/js-helpers
Version:
A set of JavaScript / TypeScript helper functions for parsing, converting, transforming and formatting data.
76 lines (75 loc) • 3.14 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.skipPairsUntil = exports.skipUntilClosingQuote = exports.CHAR_CODE_BACKTICK = exports.CHAR_CODE_APOSTROPHE = exports.CHAR_CODE_QUOTE = exports.CHAR_CODE_CLOSE_BRACE = exports.CHAR_CODE_OPEN_BRACE = exports.CHAR_CODE_CLOSE_BRACKET = exports.CHAR_CODE_OPEN_BRACKET = exports.CHAR_CODE_CLOSE_PAREN = exports.CHAR_CODE_OPEN_PAREN = void 0;
exports.CHAR_CODE_OPEN_PAREN = 40;
exports.CHAR_CODE_CLOSE_PAREN = 41;
exports.CHAR_CODE_OPEN_BRACKET = 91;
exports.CHAR_CODE_CLOSE_BRACKET = 93;
exports.CHAR_CODE_OPEN_BRACE = 123;
exports.CHAR_CODE_CLOSE_BRACE = 125;
exports.CHAR_CODE_QUOTE = 34;
exports.CHAR_CODE_APOSTROPHE = 39;
exports.CHAR_CODE_BACKTICK = 96;
function skipUntilClosingQuote(text, start, quote) {
for (let i = start; i < text.length; ++i) {
const current = text.charCodeAt(i);
if (current === quote) {
return i;
}
if (current == 92) {
i++;
}
}
return text.length;
}
exports.skipUntilClosingQuote = skipUntilClosingQuote;
function skipPairsUntil(text, start, match, throwOnMismatch) {
const stack = [];
if (typeof (match) === "string") {
match = match.charCodeAt(0);
}
const matchSymbol = typeof (match) === "number" ? ((x) => x === match) : match;
for (let i = start; i < text.length; ++i) {
const current = text.charCodeAt(i);
if (matchSymbol(current) && !stack.length) {
return i;
}
switch (current) {
case exports.CHAR_CODE_OPEN_PAREN:
stack.push(exports.CHAR_CODE_CLOSE_PAREN);
break;
case exports.CHAR_CODE_OPEN_BRACKET:
stack.push(exports.CHAR_CODE_CLOSE_BRACKET);
break;
case exports.CHAR_CODE_OPEN_BRACE:
stack.push(exports.CHAR_CODE_CLOSE_BRACE);
break;
case exports.CHAR_CODE_CLOSE_PAREN:
case exports.CHAR_CODE_CLOSE_BRACKET:
case exports.CHAR_CODE_CLOSE_BRACE:
{
const pending = stack.pop();
if (pending != current) {
if (throwOnMismatch !== false) {
throw new Error(`Unexpected '${String.fromCharCode(current)}' at offset ${i}. Expected '${pending ? String.fromCharCode(pending) : "(none)"}'`);
}
return text.length;
}
}
break;
case exports.CHAR_CODE_QUOTE:
case exports.CHAR_CODE_APOSTROPHE:
case exports.CHAR_CODE_BACKTICK:
i = skipUntilClosingQuote(text, i + 1, current);
if (i === text.length) {
return i;
}
break;
}
}
if (throwOnMismatch !== false && stack.length) {
throw new Error(`There are ${stack.length} unclosed groups: '${stack.map(x => String.fromCharCode(x)).join("','")}'`);
}
return text.length;
}
exports.skipPairsUntil = skipPairsUntil;