-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (50 loc) · 1.33 KB
/
index.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
function AnyPath (obj) {
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
setupHooks(prop, obj, obj[prop])
}
}
return obj
}
function setupHooks (prop, obj, value) {
var paths = allPaths(prop.split(/[\\/]/g))
var getter = function () {
return obj[prop]
}
// put the object back into its initial state.
obj.__restore__ = function () {
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
if (obj.__lookupGetter__(prop) === getter) delete obj[prop]
}
}
delete obj.__restore__
return obj
}
// expand the object to have all possible paths.
paths.forEach(function (path) {
if (path !== prop) {
obj.__defineGetter__(path, getter)
obj.__defineSetter__(path, function (newValue) {
obj[prop] = newValue
})
}
})
}
// recursively walk all combinations of paths:
// /foo/bar/hello.md
// \foo\bar\hello.md
// ... etc.
function allPaths (splitPath, partialPath, finalPaths, i) {
i = i || 0
finalPaths = finalPaths || []
partialPath = (partialPath || '') + splitPath[i]
if (i >= splitPath.length - 1) {
finalPaths.push(partialPath)
} else {
allPaths(splitPath, partialPath + '/', finalPaths, i + 1)
allPaths(splitPath, partialPath + '\\', finalPaths, i + 1)
}
return finalPaths
}
module.exports = AnyPath