Skip to content

Instantly share code, notes, and snippets.

@Flydiverny
Created April 2, 2016 11:48
Show Gist options
  • Select an option

  • Save Flydiverny/6c5af7db4ef4935bd961bc438742032e to your computer and use it in GitHub Desktop.

Select an option

Save Flydiverny/6c5af7db4ef4935bd961bc438742032e to your computer and use it in GitHub Desktop.
Ran into some challenge while I was bored, thanks curbside :)
var http = require('http');
var Promise = require('promise');
var sessionGet = 0;
var sessionPromise;
var handleNext = function(req) {
var obj = JSON.parse(req.toLowerCase()); // lazy since some keys are in borked case.
return new Promise(function(resolve, reject) {
if (obj.next !== undefined) {
if (typeof obj.next === 'string') {
obj.next = [obj.next]; // make life easier with a single code path
}
var promises = obj.next.map(function(v, k) {
return fetchWithSession(v).then(handleNext);
});
Promise.all(promises)
.then(function(res) {
resolve(res.join(''));
});
} else {
resolve(obj.secret);
}
});
};
var fetchWithSession = function(path) {
if (sessionPromise === undefined || ++sessionGet == 10) {
sessionGet = 0;
sessionPromise = fetchPath("get-session");
}
return sessionPromise
.then(function(session) {
return fetchPath(path, session);
});
};
var fetchPath = function(path, session) {
return new Promise(function(resolve, reject) {
var options = {
host: 'challenge.shopcurbside.com',
path: path,
headers: {'Session': session || ""}
};
var httpCbk = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
resolve(str);
});
};
http.get(options, httpCbk).end();
});
};
fetchWithSession("start")
.then(handleNext)
.then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment