-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathwrapper.js
91 lines (75 loc) · 2.06 KB
/
wrapper.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
/** @module liaison/wrapper */
define([
"decor/Observable",
"decor/ObservableArray"
], function (Observable, ObservableArray) {
"use strict";
var getPrototypeOf = Object.getPrototypeOf;
/**
* @function module:liaison/wrapper.wrap
* @param {Object} o A plain object.
* @returns {module:decor/Observable} The {@link module:decor/Observable Observable} version of the given object.
*/
function wrap(o) {
var root = o,
tree = [];
function wrapImpl(o) {
var index = tree.indexOf(o);
if (index >= 0) {
return tree[index + 1];
}
var proto,
isArray = Array.isArray(o),
isObject = Observable.test(o) || o && typeof o === "object" && (o === root || (proto = getPrototypeOf(o)) && !getPrototypeOf(proto)),
wrapped = isArray ? new ObservableArray() : isObject ? new Observable() : o;
tree.push(o, wrapped);
if (isArray) {
for (var i = 0, l = o.length; i < l; ++i) {
wrapped[i] = wrapImpl(o[i]);
}
} else if (isObject) {
for (var s in o) {
wrapped[s] = wrapImpl(o[s]);
}
}
tree.splice(-2, 2);
return wrapped;
}
return wrapImpl(o);
}
/**
* @function module:liaison/wrapper.unwrap
* @param {module:decor/Observable} o A {@link module:decor/Observable Observable}.
* @returns {Object} The plain object version of the given {@link module:decor/Observable Observable}.
*/
function unwrap(o) {
var tree = [];
function unwrapImpl(o) {
var index = tree.indexOf(o);
if (index >= 0) {
return tree[index + 1];
}
var proto,
isArray = Array.isArray(o),
isObject = Observable.test(o) || o && typeof o === "object" && (proto = getPrototypeOf(o)) && !getPrototypeOf(proto),
unwrapped = isArray ? [] : isObject ? {} : o;
tree.push(o, unwrapped);
if (isArray) {
for (var i = 0, l = o.length; i < l; ++i) {
unwrapped[i] = unwrapImpl(o[i]);
}
} else if (isObject) {
for (var s in o) {
unwrapped[s] = unwrapImpl(o[s]);
}
}
tree.splice(-2, 2);
return unwrapped;
}
return unwrapImpl(o);
}
return {
wrap: wrap,
unwrap: unwrap
};
});