3 module.exports = factory
5 function factory(file) {
6 var contents = indices(String(file))
9 toPosition: offsetToPositionFactory(contents),
10 toOffset: positionToOffsetFactory(contents)
14 // Factory to get the line and column-based `position` for `offset` in the bound
16 function offsetToPositionFactory(indices) {
17 return offsetToPosition
19 // Get the line and column-based `position` for `offset` in the bound indices.
20 function offsetToPosition(offset) {
22 var length = indices.length
28 while (++index < length) {
29 if (indices[index] > offset) {
32 column: offset - (indices[index - 1] || 0) + 1,
42 // Factory to get the `offset` for a line and column-based `position` in the
44 function positionToOffsetFactory(indices) {
45 return positionToOffset
47 // Get the `offset` for a line and column-based `position` in the bound
49 function positionToOffset(position) {
50 var line = position && position.line
51 var column = position && position.column
53 if (!isNaN(line) && !isNaN(column) && line - 1 in indices) {
54 return (indices[line - 2] || 0) + column - 1 || 0
61 // Get indices of line-breaks in `value`.
62 function indices(value) {
64 var index = value.indexOf('\n')
66 while (index !== -1) {
67 result.push(index + 1)
68 index = value.indexOf('\n', index + 1)
71 result.push(value.length + 1)