Repository navigation
Expand file tree
/
Copy pathexample.js
More file actions
100 lines (83 loc) · 1.81 KB
/
Copy pathexample.js
File metadata and controls
100 lines (83 loc) · 1.81 KB
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
'use strict';
function fromTrail(tree, last) {
if (last[0] === 'left') {
return {
value: last[1],
left: tree,
right: last[2]
};
}
return {
value: last[1],
left: last[2],
right: tree
};
}
function rebuildTree(tree, trail) {
if (trail.length === 0) return tree;
var last = trail[0];
return rebuildTree(fromTrail(tree, last), trail.slice(1));
}
var Zipper = function (tree, trail) {
this.tree = tree;
this.trail = trail;
};
Zipper.fromTree = function (tree) {
return new Zipper(tree, []);
};
Zipper.prototype.toTree = function () {
return rebuildTree(this.tree, this.trail);
};
Zipper.prototype.value = function () {
return this.tree.value;
};
Zipper.prototype.left = function () {
if (!this.tree.left) return null;
return new Zipper(
this.tree.left,
[['left', this.tree.value, this.tree.right]].concat(this.trail)
);
};
Zipper.prototype.right = function () {
if (!this.tree.right) return null;
return new Zipper(
this.tree.right,
[['right', this.tree.value, this.tree.left]].concat(this.trail)
);
};
Zipper.prototype.up = function () {
if (this.trail.length === 0) return null;
var last = this.trail[0];
return new Zipper(fromTrail(this.tree, last), this.trail.slice(1));
};
Zipper.prototype.setValue = function (value) {
return new Zipper(
{
value: value,
left: this.tree.left,
right: this.tree.right
},
this.trail
);
};
Zipper.prototype.setLeft = function (left) {
return new Zipper(
{
value: this.tree.value,
left: left,
right: this.tree.right
},
this.trail
);
};
Zipper.prototype.setRight = function (right) {
return new Zipper(
{
value: this.tree.value,
left: this.tree.left,
right: right
},
this.trail
);
};
module.exports = Zipper;