forked from less/less.js
/
utils.js
121 lines (110 loc) · 2.96 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/* jshint proto: true */
import * as Constants from './constants';
export function getLocation(index, inputStream) {
let n = index + 1;
let line = null;
let column = -1;
while (--n >= 0 && inputStream.charAt(n) !== '\n') {
column++;
}
if (typeof index === 'number') {
line = (inputStream.slice(0, index).match(/\n/g) || '').length;
}
return {
line,
column
};
}
export function copyArray(arr) {
let i;
const length = arr.length;
const copy = new Array(length);
for (i = 0; i < length; i++) {
copy[i] = arr[i];
}
return copy;
}
export function clone(obj) {
const cloned = {};
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
cloned[prop] = obj[prop];
}
}
return cloned;
}
export function defaults(obj1, obj2) {
let newObj = obj2 || {};
if (!obj2._defaults) {
newObj = {};
const defaults = {...obj1};
newObj._defaults = defaults;
const cloned = obj2 ? {...obj2} : {};
Object.assign(newObj, defaults, cloned);
}
return newObj;
}
export function copyOptions(obj1, obj2) {
if (obj2 && obj2._defaults) {
return obj2;
}
const opts = defaults(obj1, obj2);
if (opts.strictMath) {
opts.math = Constants.Math.PARENS;
}
// Back compat with changed relativeUrls option
if (opts.relativeUrls) {
opts.rewriteUrls = Constants.RewriteUrls.ALL;
}
if (typeof opts.math === 'string') {
switch (opts.math.toLowerCase()) {
case 'always':
opts.math = Constants.Math.ALWAYS;
break;
case 'parens-division':
opts.math = Constants.Math.PARENS_DIVISION;
break;
case 'strict':
case 'parens':
opts.math = Constants.Math.PARENS;
break;
default:
opts.math = Constants.Math.PARENS;
}
}
if (typeof opts.rewriteUrls === 'string') {
switch (opts.rewriteUrls.toLowerCase()) {
case 'off':
opts.rewriteUrls = Constants.RewriteUrls.OFF;
break;
case 'local':
opts.rewriteUrls = Constants.RewriteUrls.LOCAL;
break;
case 'all':
opts.rewriteUrls = Constants.RewriteUrls.ALL;
break;
}
}
return opts;
}
export function merge(obj1, obj2) {
for (const prop in obj2) {
if (obj2.hasOwnProperty(prop)) {
obj1[prop] = obj2[prop];
}
}
return obj1;
}
export function flattenArray(arr, result = []) {
for (let i = 0, length = arr.length; i < length; i++) {
const value = arr[i];
if (Array.isArray(value)) {
flattenArray(value, result);
} else {
if (value !== undefined) {
result.push(value);
}
}
}
return result;
}