JSFiddle - React, Tailwind, and code Playground
by maciejgurban
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.13.0/polyfill.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.0.2/mocha.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.0.2/mocha.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.js"></script>
<!-- No need to change this -->
<!-- Mocha test output goes here. -->
<div id="mocha"></div>
JavaScript
const responseToTimeseries = response => {
console.log(response);
const arrayOfZeroes = () => new Array(response.length).fill(0);
const makeEmptyItem = x => ({ x, points: arrayOfZeroes(), total: 0 });
const result = {};
console.log(arrayOfZeroes);
console.log(makeEmptyItem);
for (let [index, { data }] of Object.entries(response)) {
for (let [x, point] of data) {
result[x] = result[x] || makeEmptyItem(x);
result[x].points[index] = point;
result[x].total += point;
}
}
console.log(result);
return result;
};
/* TESTS */
// Configure Mocha, telling both it and chai to use BDD-style tests.
mocha.setup("bdd");
chai.should();
describe('responseToTimeseries()', () => {
describe('when receiving data for one point in time', () => {
it('returns the expected output', () => {
const input = [
{ data: [[1242362340000, 10], [1242362340001, 4]] },
];
const output = {
1242362340000: {
x: 1242362340000,
points: [10],
total: 10,
},
1242362340001: {
x: 1242362340001,
points: [4],
total: 4,
}
};
responseToTimeseries(input).should.deep.equal(output);
});
});
describe('when receiving data for multiple points in time', () => {
it('returns the expected output', () => {
const input = [
{ data: [[1242362340000, 10], [1242362340001, 4]] },
{ data: [[1242362340000, 6], [1242362340001, 9]] },
{ data: [[1242362340000, 11], [1242362340001, 13]] },
];
const output = {
1242362340000: {
x: 1242362340000,
points: [10, 6, 11],
total: 27,
},
1242362340001: {
x: 1242362340001,
points: [4, 9, 13],
total: 26,
}
};
responseToTimeseries(input).should.deep.equal(output);
});
});
describe('when some point is missing', () => {
it('returns the expected output', () => {
const input = [
{ data:...