-
Notifications
You must be signed in to change notification settings - Fork 0
/
source-tracker.js
51 lines (42 loc) · 1.12 KB
/
source-tracker.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
'use strict';
const SOURCES = Symbol();
/*
SourceTracker can be used to remember/retrieve the source locations of each
key and value within a TOML document.
*/
class SourceTracker {
constructor() {
Object.defineProperty(this, SOURCES, { value: new WeakMap() });
}
getKeySource(obj, key) {
return getSourceRecord(this[SOURCES], obj, key).key;
}
getValueSource(obj, key) {
return getSourceRecord(this[SOURCES], obj, key).value;
}
}
function getSourceRecord(sources, obj, key) {
if (typeof obj !== 'object' || obj === null) {
throw new TypeError('Expected the tracked entity to be an object or array');
}
if (typeof key !== 'string' && !Number.isInteger(key)) {
throw new TypeError('Expected key to be a string or integer');
}
const map = sources.get(obj);
if (!map) {
if (Array.isArray(obj)) {
throw new TypeError('No source tracked for that array');
} else {
throw new TypeError('No source tracked for that object');
}
}
const record = map.get(key);
if (!record) {
throw new TypeError('No source tracked for that key');
}
return record;
}
Object.assign(exports, {
SourceTracker,
SOURCES,
});