Skip to content

Instantly share code, notes, and snippets.

@nonamephysics
Forked from phgrey/tz.js
Created March 20, 2019 17:14
Show Gist options
  • Save nonamephysics/8bf15f9c502844ff208597c821cfa6b4 to your computer and use it in GitHub Desktop.
Save nonamephysics/8bf15f9c502844ff208597c821cfa6b4 to your computer and use it in GitHub Desktop.
#! /usr/bin/node
/**
* HTTP server for some data transitions Endpoint: http://XXX/compute/<request_id>
* details - https://www.corva.ai/software-engineer-interview-question/
*/
const http = require('http'),
assert = require('assert');
const port = process.env.PORT || 3000;
const requestHandler = (request, response) => {
const params = request.url.split('/');
if(params[1] == 'compute' && params[2] && request.method == 'POST' ){
try {
const ret = build_output(JSON.parse(request.body), params[2]);
response.end(JSON.stringify(ret));
}catch (err){
log('Error parsing request', err, request );
return error_me( response,'401');
}
}else{
log("404 for url / method",request.url, request.method );
return error_me( response,'404');
}
};
/**
* Input POST Value:
{
"timestamp": 1493758596,
"data": [
{ "title": "Part 1", "values": [0, 3, 5, 6, 2, 9] },
{ "title": "Part 2", "values": [6, 3, 1, 3, 9, 4] }
]
}
The service shall take the array from Part 1 and subtract the values from Part 2, subtracting numbers that exist in the same index of the array. The final array is also the same size (6).
The return value will be a JSON document in the following format containing the resultant array and request ID.
Output:
{
"request_id": "<request_id>",
"timestamp": 1493758596,
"result": { "title": "Result", "values": […] }
}
*/
function build_output(input, request_id){
if(!input.data || ! input.data.length)
throw("Mailformed input - no data");
const p1 = input.data.filter(item => item.title == 'Part 1')[0],
p2 = input.data.filter(item => item.title == 'Part 2')[0];
if(!p1 || ! p2 || !p1.values || !p2.values)
throw("Mailformed input - Part1 or Part2");
if(p1.values.length != p2.values.length)
throw("Mailformed input - Part1 and Part2");
return {
request_id,
timestamp: input.timestamp,
result: {
title: 'Result',
values: Array.from(p1.values.keys()).map(i => p1.values[i] - p2.values[i])
}
};
}
assert.deepEqual(build_output({
"timestamp": 1493758596,
"data": [
{ "title": "Part 1", "values": [0, 3, 5, 6, 2, 9] },
{ "title": "Part 2", "values": [6, 3, 1, 3, 9, 4] }
]
}, '<request_id>'), {
"request_id": "<request_id>",
"timestamp": 1493758596,
"result": { "title": "Result", "values": [-6, 0, 4, 3, -7, 5] }
});
function error_me(response, code){
response.writeHead(code);
response.end();
}
function log(){
console.log(arguments);
}
const server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return log('something bad happened', err);
}
log(`server is listening on ${port}`)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment