Skip to content

Instantly share code, notes, and snippets.

@lazywithclass lazywithclass/challenge.js
Last active Sep 24, 2015

Embed
What would you like to do?
Traversing a graph whose elements you get from API calls, using a token that expires after 10 calls. Leaves contain a secret message.
var async = require('async'),
request = require('request');
function traverse(start, token) {
var queue = [];
queue.unshift(start);
async.forever(function(next) {
if (queue.length === 0) next('no more items');
var item = queue.pop();
getAdjacents(item, token, function(err, adjacents) {
if (adjacents.secret) {
process.stdout.write(adjacents.secret);
} else {
adjacents.hashes.forEach(function(adjacent) {
queue.unshift(adjacent);
});
}
next();
});
}, process.exit);
}
function getAdjacents(item, token, cb) {
var params = {
url: 'http://challenge.shopcurbside.com/' + item,
headers: {
Session: token
}
};
request(params, function(err, res, body) {
body = JSON.parse(body);
if (body.error) {
refreshToken(function(err, token) {
getAdjacents(item, token, cb);
});
} else {
sanitiseAdjacents(body, cb);
}
});
}
function sanitiseAdjacents(body, cb) {
var adjacents = body[getNextKey(body)] || [];
if (body.secret) {
cb(null, { secret: body.secret });
} else {
if (typeof adjacents === 'string') adjacents = [adjacents];
cb(null, { hashes: adjacents });
}
}
function getNextKey(body) {
var keys = Object.keys(body), nextKey = '';
return keys.reduce(function(_, key) {
if (key != 'id' && key != 'depth' && key != 'message' && key != 'secret') return key;
});
}
function refreshToken(cb) {
request('http://challenge.shopcurbside.com/get-session', function(err, res, body) {
cb(null, body);
});
}
refreshToken(function(err, token) {
console.log('the message will appear as we traverse the graph');
traverse('start', token);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.