Skip to content

Instantly share code, notes, and snippets.

@jchip
Created June 17, 2018 08:16
Show Gist options
  • Save jchip/ffecffde9b7d8b70288699f415b3ff0e to your computer and use it in GitHub Desktop.
Save jchip/ffecffde9b7d8b70288699f415b3ff0e to your computer and use it in GitHub Desktop.
position to line/column
function posToLine(template, pos) {
const lines = template.split("\n");
let run = 0;
let x;
for (x = 0; x < lines.length; x++) {
const line = lines[x];
if (run + line.length < pos) {
run += line.length + 1;
} else {
break;
}
}
const line = x + 1;
const col = pos - run;
return { line, col };
}
console.log(
posToLine(
`abc
12345
hello world
foo bar`,
12
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment