Commit 1e61d001 authored by David Sveningsson's avatar David Sveningsson

feat(transform): add `offsetToLineColumn` helper

parent fe1705e1
Pipeline #99808751 passed with stages
in 9 minutes and 20 seconds
import { offsetToLineColumn } from "./helpers";
describe("offsetToLineColumn() should calculate line and column from offset", () => {
const data = "lorem\nipsum dolor\nsit amet";
it.each`
offset | line | column | character
${0} | ${1} | ${1} | ${"l"}
${1} | ${1} | ${2} | ${"o"}
${5} | ${1} | ${6} | ${"\n"}
${6} | ${2} | ${1} | ${"i"}
${16} | ${2} | ${11} | ${"r"}
${18} | ${3} | ${1} | ${"s"}
${25} | ${3} | ${8} | ${"t"}
`(
"Offset $offset should be $line:$column",
({ offset, line, column, character }) => {
expect.assertions(2);
expect(data[offset]).toEqual(character);
expect(offsetToLineColumn(data, offset)).toEqual([line, column]);
}
);
});
/**
* Given an offset into a source, calculate the corresponding line and column.
*/
export function offsetToLineColumn(
data: string,
offset: number
): [number, number] {
let line = 1;
let prev = 0;
let pos = data.indexOf("\n");
/* step one line at a time until newline position is beyond wanted offset */
while (pos !== -1) {
if (pos >= offset) {
return [line, offset - prev + 1];
}
line++;
prev = pos + 1;
pos = data.indexOf("\n", pos + 1);
}
/* missing final newline */
return [line, offset - prev + 1];
}
......@@ -3,6 +3,7 @@ import { TransformContext } from "./context";
export { TransformContext } from "./context";
export { TemplateExtractor } from "./template";
export { offsetToLineColumn } from "./helpers";
export type Transformer = (
this: TransformContext,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment