Skip to content

Instantly share code, notes, and snippets.

@alaboudi
Created May 6, 2020 20:21
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 alaboudi/e7f465d126a2a1e658f93875ad1e5a4d to your computer and use it in GitHub Desktop.
Save alaboudi/e7f465d126a2a1e658f93875ad1e5a4d to your computer and use it in GitHub Desktop.
load-state.js
// You and your teammate have been working on a project for two and a half
// weeks. Everything is going well except you notice that one of the functions
// your teammate wrote is failing a test case, which you know to be correct.
// Unfortunately, your teammate is sick today and to make matters worse, you
// realize that you need to demo your project in ten minutes. So you decide
// to try and fix the function. Can you fix it in time for your demo?
////////////////////////////////////////////////////////////////////////////////
const SYMBOLS = [ 'AAPL', 'AMZN', 'MONY', 'PETS', 'PZZA', 'SHOP', 'TSLA', 'WIFI' ];
////////////////////////////////////////////////////////////////////////////////
const readJSON = function()
{
// Simulate success rate
if (Math.random() > 0.2)
{
// Call was successful
return Promise.resolve
({
version: 1,
payload: {
AAPL: 1588773600,
AMZN: 1588690800,
MONY: 1588428000,
PETS: 1588532400,
SHOP: 1588525200,
TSLA: 1588608000
}
});
}
else return Promise.reject ('the file could not be opened for reading');
};
////////////////////////////////////////////////////////////////////////////////
const loadState = function()
{
// Read the previous state
const result = readJSON();
return result.then (state =>
{
// If state is compliant
if (state.version !== 1)
{
console.warn ('version mismatch with previous state, rebuilding...');
return { };
}
return state.payload;
}, () => ({}))
.then (payload =>
{
// Populate primary queue data
for (const symbol of SYMBOLS)
{
if (!(symbol in payload))
payload[symbol] = 0;
}
// Oldest entries to the top
return Object.fromEntries (
Object.entries (payload)
.sort ((a, b) => b[1] > a[1])
);
});
};
////////////////////////////////////////////////////////////////////////////////
(async () =>
{
const state = JSON.stringify (await loadState());
const success = JSON.stringify
({
AAPL: 1588773600,
AMZN: 1588690800,
MONY: 1588428000,
PETS: 1588532400,
PZZA: 0,
SHOP: 1588525200,
TSLA: 1588608000,
WIFI: 0,
});
const failure = JSON.stringify
({
AAPL: 0,
AMZN: 0,
MONY: 0,
PETS: 0,
PZZA: 0,
SHOP: 0,
TSLA: 0,
WIFI: 0
});
// Perform a poor-mans comparison on result
if (state !== success && state !== failure)
throw new Error ('unrecognized result');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment