UNPKG

1.51 kBJavaScriptView Raw
1'use strict';
2
3const os = require('os');
4const util = require('util');
5
6//////////////////////////////////////
7// Returns the End-Of-Line from text.
8function getEOL(text) {
9 const m1 = text.match(/\r\n/g);
10 const m2 = text.match(/\n/g);
11 const w = m1 ? m1.length : 0;
12 const u = m2 ? m2.length - w : 0;
13 if (u === w) {
14 return os.EOL;
15 }
16 return u > w ? '\n' : '\r\n';
17}
18
19///////////////////////////////////////////////////////
20// Returns {line, column} of an index within the text.
21function getIndexPos(text, index, eol) {
22 let lineIdx = 0, colIdx = index, pos = 0;
23 do {
24 pos = text.indexOf(eol, pos);
25 if (pos === -1 || index < pos + eol.length) {
26 break;
27 }
28 lineIdx++;
29 pos += eol.length;
30 colIdx = index - pos;
31 } while (pos < index);
32 return {
33 line: lineIdx + 1,
34 column: colIdx + 1
35 };
36}
37
38///////////////////////////////////////////
39// Returns a space gap for console output.
40function messageGap(level) {
41 return ' '.repeat(level * 4);
42}
43
44////////////////////////////////////////////////////
45// Legacy type inspection, to support Node.js < 6.x
46function addInspection(type, cb) {
47 // istanbul ignore else;
48 if (util.inspect.custom) {
49 type.prototype[util.inspect.custom] = cb;
50 } else {
51 type.prototype.inspect = cb;
52 }
53}
54
55module.exports = {
56 getEOL,
57 getIndexPos,
58 messageGap,
59 addInspection
60};