Skip to content

Instantly share code, notes, and snippets.

@Trindaz
Created March 29, 2012 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Trindaz/2234466 to your computer and use it in GitHub Desktop.
Save Trindaz/2234466 to your computer and use it in GitHub Desktop.
Deep Copy walk with forced async completion before return
var http = require('http');
var request = require('request');
var samplePayload = {
"key1":{
"key1.1": {
"key1.1.1": ["val1.1.1.1", "val1.1.1.2", "val1.1.1.3", "val1.1.1.4"]
},
"key1.2": ["val1.2.1" ,"val1.2.2"]
},
"key2":"val2"
}
function attemptClose(response, callStack, parentResult){
if(callStack.length==0){
response.end(JSON.stringify(parentResult, undefined, 4));
}
}
function processObjWithRef(obj, result, callStack, res, parentResult){
if(obj==null || typeof obj != 'object'){
//nothing really to do here - you're going to lose the reference to result if you try an assignment
}
if(obj instanceof Array) {
for(var i=0; i<obj.length; i++){
result.push();
processObjWithRef(obj[i], result[i], callStack, res, parentResult);
}
}
if(obj instanceof Object){
for(var l in obj){
(function(){
var k = l;
if(obj[k]==null || typeof obj[k] != 'object'){
callStack.push("some_value");
request({ uri:"http://www.craigslist.com"}, function (error, response, body) {
var snippet = body.substring(0, 50)+"...";
result[k] = snippet;
callStack.pop();
attemptClose(res, callStack, parentResult);
});
}else if(obj[k] instanceof Array) {
result[k] = [];
processObjWithRef(obj[k], result[k], callStack, res, parentResult);
}else if(obj[k] instanceof Object){
result[k] = {};
processObjWithRef(obj[k], result[k], callStack, res, parentResult);
}
})();
}
}
}
function processRequest(req, res){
var callStack = [];
var myNewObj = {};
processObjWithRef(samplePayload, myNewObj, callStack, res, myNewObj);
attemptClose(res, callStack, myNewObj);
}
var server = http.createServer(processRequest);
server.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment