Skip to content

Instantly share code, notes, and snippets.

@Domiii
Created September 25, 2020 08:01
Show Gist options
  • Save Domiii/4a5995f1a0ba08c3714af8bf52e55493 to your computer and use it in GitHub Desktop.
Save Domiii/4a5995f1a0ba08c3714af8bf52e55493 to your computer and use it in GitHub Desktop.
getLinesAroundOffset.js
/**
* Gets the line at given offset in s, as well as `nLines` lines below and above.
* If a line is very long (e.g. in bundled/obfuscated files), i.e. if it exceeds `maxChars`, get at most `maxChars` more in each direction
*/
function getLinesAroundOffset(s, offset, nLines = 1, maxChars = 200) {
let start = offset - 1;
for (let i = 0; i < nLines; ++i) {
const newIdx = s.lastIndexOf('\n', start) - 1;
if (Math.abs(start - newIdx) > maxChars) {
// probably compressed code
start -= maxChars;
break;
}
if (newIdx >= 0) {
start = newIdx;
}
}
let end = offset + 1;
for (let i = 0; i <= nLines; ++i) {
const newIdx = s.indexOf('\n', end) + 1;
if (Math.abs(end - newIdx) > maxChars) {
// probably compressed code
end += maxChars;
break;
}
if (newIdx >= 0) {
end = newIdx;
}
}
return s.substring(start, end);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment