Skip to content

Instantly share code, notes, and snippets.

@masotime
Last active June 21, 2016 01:18
Show Gist options
  • Save masotime/12a059f11627e652a811583f003ba9dc to your computer and use it in GitHub Desktop.
Save masotime/12a059f11627e652a811583f003ba9dc to your computer and use it in GitHub Desktop.
Getting a JSON matrix of MRT travel times
/* global $ */
function getInputs() {
return $('#stations-list li').map(function() {
return {
symbol: $(this).data('skey'),
name: $(this).text()
};
}).toArray();
}
function getLookup() {
return getInputs().reduce((acc, data) => {
acc[data.symbol] = data.name;
return acc;
}, {});
}
function throttled(promiseGeneratingFn, batchSize = 100) {
let count = 0;
let waitChain = Promise.resolve();
let promiseQueue = [];
return (...args) => {
if (count % batchSize === 0) {
// awkward, because of the mutable aspect of promiseQueue
waitChain = (queue => waitChain.then(() => Promise.all(queue)))(promiseQueue);
promiseQueue = [];
}
const tail = waitChain.then(() => promiseGeneratingFn(...args));
promiseQueue.push(tail);
count += 1;
return tail;
}
}
function tripInfo(from, to) {
return $.ajax('tripcalc', {
type: 'POST',
data: `station_a=${from}&station_b=${to}`
}).then(msg =>
({
from, to, duration: /about ([0-9]+) minutes/.exec(msg)[1]
})
);
}
const throttledTripInfo = throttled(tripInfo, 30);
function main() {
const promises = [];
const matrix = {};
const inputs = getInputs();
const len = inputs.length;
for (var i = 0; i < len; i += 1) {
for (var j = 0; j < len; j+= 1) {
if (i !== j) {
const station1 = inputs[i].symbol;
const station2 = inputs[j].symbol;
promises.push(throttledTripInfo(station1, station2));
}
}
}
return Promise.all(promises).then(everything => {
everything.forEach(thing => {
matrix[thing.from] = matrix[thing.from] || {};
matrix[thing.from][thing.to] = thing.duration;
});
return matrix;
});
}
main().then(matrix => console.log(matrix));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment