Created
March 14, 2012 08:53
-
-
Save fillano/2035204 to your computer and use it in GitHub Desktop.
callback with binary tree tranversal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ObjectId(str) { | |
return str; | |
} | |
var Subject = { | |
"data": { | |
"4f5ca201e7a3792f5e000003": { | |
"_id": ObjectId("4f5ca201e7a3792f5e000003"), | |
"childId": ObjectId("4f5ca5939da509475e000003"), | |
"name": "資產類", | |
"parentId": "-1", | |
"siblingId": ObjectId("4f5ca20ce7a3792f5e000005"), | |
"sn": "1000" | |
}, | |
"4f5ca20ce7a3792f5e000005":{ | |
"_id": ObjectId("4f5ca20ce7a3792f5e000005"), | |
"name": "負債類", | |
"parentId": "4f5ca201e7a3792f5e000003", | |
"siblingId": ObjectId("4f5ca215e7a3792f5e00000a"), | |
"sn": "2000" | |
}, | |
"4f5ca215e7a3792f5e00000a":{ | |
"parentId": "4f5ca20ce7a3792f5e000005", | |
"name": "業主權益類", | |
"sn": "3000", | |
"_id": ObjectId("4f5ca215e7a3792f5e00000a") | |
}, | |
"4f5ca5939da509475e000003":{ | |
"parentId": "4f5ca201e7a3792f5e000003", | |
"name": "流動資產", | |
"sn": "1100", | |
"_id": ObjectId("4f5ca5939da509475e000003") | |
}, | |
"4f5ca7a19da509475e000005":{ | |
"parentId": "4f5ca5939da509475e000003", | |
"name": "基金及投資", | |
"sn": "1100", | |
"_id": ObjectId("4f5ca7a19da509475e000005") | |
} | |
}, | |
"findOne": function(qry,cb) { | |
for(var i in this.data) { | |
if(this.data[i].parentId==="-1") { | |
cb(false, this.data[i]); | |
return; | |
} | |
} | |
cb(true); | |
}, | |
"findById": function(qry,cb) { | |
for(var i in this.data) { | |
if(this.data[i]._id===qry._id) { | |
cb(false, this.data[i]); | |
} | |
} | |
cb(true); | |
} | |
}; | |
var wait = function (cb) { | |
var payload = []; | |
return { | |
next: function (data) { | |
if(data) payload.push(data); | |
}, | |
stop: function(end) { | |
if(end) | |
cb(payload); | |
} | |
}; | |
}; | |
var Tree = function() { | |
var subArray = []; | |
var getRootId = function(cb) { | |
Subject.findOne({ | |
parentId: -1 | |
}, function(err, node) { | |
if(!err) { | |
cb(node._id); | |
} | |
}); | |
}; | |
var preOrder = function(nodeId, cb) { | |
Subject.findById({ | |
_id: nodeId | |
}, function(err, node) { | |
if (err) return; | |
if (node !== undefined) { | |
subArray.push({ | |
name: node.name, | |
sn: node.sn, | |
id: node._id | |
}); | |
cb.next(JSON.stringify(subArray)); | |
preOrder(node.childId, cb); | |
preOrder(node.siblingId, cb); | |
subArray.pop(); | |
cb.stop(node.parentId==='-1'); | |
} | |
}); | |
}; | |
return { | |
getSubArray: function(cb) { | |
getRootId(function(nodeId) { | |
preOrder(nodeId,cb); | |
}); | |
} | |
}; | |
}; | |
var tree = Tree(); | |
tree.getSubArray(wait(function(subs) {console.log(subs);})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment