Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 21 additions & 18 deletions lib/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@ let PreviousMap = require('./previous-map')
let terminalHighlight = require('./terminal-highlight')

let lineToIndexCache = Symbol('lineToIndexCache')
let lastLineCache = Symbol('lastLineCache')

let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
let pathAvailable = Boolean(resolve && isAbsolute)

function getLineToIndex(input) {
if (input[lineToIndexCache]) return input[lineToIndexCache]
let lines = input.css.split('\n')
let lineToIndex = new Array(lines.length)
let prevIndex = 0

for (let i = 0, l = lines.length; i < l; i++) {
lineToIndex[i] = prevIndex
prevIndex += lines[i].length + 1
let css = input.css
let lineToIndex = [0]
let index = css.indexOf('\n')
while (index !== -1) {
lineToIndex.push(index + 1)
index = css.indexOf('\n', index + 1)
}

input[lineToIndexCache] = lineToIndex
Expand Down Expand Up @@ -169,26 +169,29 @@ class Input {

fromOffset(offset) {
let lineToIndex = getLineToIndex(this)
let lastLine = lineToIndex[lineToIndex.length - 1]

let min = 0
if (offset >= lastLine) {
min = lineToIndex.length - 1
} else {
let max = lineToIndex.length - 2
let lastLine = lineToIndex.length - 1

// Parser asks for positions in order, so the answer is usually
// the line from the previous call or the next one
let min = this[lastLineCache] || 0
if (offset < lineToIndex[min]) {
min = 0
} else if (min < lastLine && offset >= lineToIndex[min + 1]) {
min += 1
}
if (min < lastLine && offset >= lineToIndex[min + 1]) {
let max = lastLine
let mid
while (min < max) {
mid = min + ((max - min) >> 1)
mid = min + ((max - min + 1) >> 1)
if (offset < lineToIndex[mid]) {
max = mid - 1
} else if (offset >= lineToIndex[mid + 1]) {
min = mid + 1
} else {
min = mid
break
}
}
}
this[lastLineCache] = min
return {
col: offset - lineToIndex[min] + 1,
line: min + 1
Expand Down
Loading