UNPKG

@visulima/error

Version:

Error with more than just a message, stacktrace parsing.

51 lines (49 loc) 1.52 kB
const binarySearch = (element, array) => { let m = 0; let n = array.length - 2; while (m < n) { const key = m + (n - m >> 1); if (element < array[key]) { n = key - 1; } else if (element >= array[key + 1]) { m = key + 1; } else { m = key; break; } } return m; }; const getLineStartIndexes = (string_) => ( // eslint-disable-next-line unicorn/no-array-reduce string_.split(/\n|\r(?!\n)/).reduce( (accumulator, current) => { accumulator.push(accumulator.at(-1) + current.length + 1); return accumulator; }, [0] ) ); const indexToLineColumn = (input, index, options) => { const skipChecks = options?.skipChecks ?? false; if (!skipChecks && (!Array.isArray(input) && typeof input !== "string" || (typeof input === "string" || Array.isArray(input)) && input.length === 0)) { return { column: 0, line: 0 }; } if (!skipChecks && (typeof index !== "number" || typeof input === "string" && index >= input.length || Array.isArray(input) && index + 1 >= input.at(-1))) { return { column: 0, line: 0 }; } if (typeof input === "string") { const startIndexesOfEachLine = getLineStartIndexes(input); const line2 = binarySearch(index, startIndexesOfEachLine); return { column: index - startIndexesOfEachLine[line2] + 1, line: line2 + 1 }; } const line = binarySearch(index, input); return { column: index - input[line] + 1, line: line + 1 }; }; export { indexToLineColumn as default };