.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / vfile-location / index.js
1 'use strict'
2
3 module.exports = factory
4
5 function factory(file) {
6   var contents = indices(String(file))
7
8   return {
9     toPosition: offsetToPositionFactory(contents),
10     toOffset: positionToOffsetFactory(contents)
11   }
12 }
13
14 // Factory to get the line and column-based `position` for `offset` in the bound
15 // indices.
16 function offsetToPositionFactory(indices) {
17   return offsetToPosition
18
19   // Get the line and column-based `position` for `offset` in the bound indices.
20   function offsetToPosition(offset) {
21     var index = -1
22     var length = indices.length
23
24     if (offset < 0) {
25       return {}
26     }
27
28     while (++index < length) {
29       if (indices[index] > offset) {
30         return {
31           line: index + 1,
32           column: offset - (indices[index - 1] || 0) + 1,
33           offset: offset
34         }
35       }
36     }
37
38     return {}
39   }
40 }
41
42 // Factory to get the `offset` for a line and column-based `position` in the
43 // bound indices.
44 function positionToOffsetFactory(indices) {
45   return positionToOffset
46
47   // Get the `offset` for a line and column-based `position` in the bound
48   // indices.
49   function positionToOffset(position) {
50     var line = position && position.line
51     var column = position && position.column
52
53     if (!isNaN(line) && !isNaN(column) && line - 1 in indices) {
54       return (indices[line - 2] || 0) + column - 1 || 0
55     }
56
57     return -1
58   }
59 }
60
61 // Get indices of line-breaks in `value`.
62 function indices(value) {
63   var result = []
64   var index = value.indexOf('\n')
65
66   while (index !== -1) {
67     result.push(index + 1)
68     index = value.indexOf('\n', index + 1)
69   }
70
71   result.push(value.length + 1)
72
73   return result
74 }