Skip to content

Instantly share code, notes, and snippets.

@joelbowen
Created September 13, 2016 21:16
Show Gist options
  • Save joelbowen/63131a57b204c5e5bc256e8503405718 to your computer and use it in GitHub Desktop.
Save joelbowen/63131a57b204c5e5bc256e8503405718 to your computer and use it in GitHub Desktop.
An example of reducing a set of data
/*
Implement a function that given two arbitrary dates ‘dateFrom’ and ‘dateTo’, will display a sorted list of the stocks based on their performance over those dates. For example:
*/
const stocks = {
AAPL: [
{
'date': '2016-03-02',
'price': 98.32,
'dayChange': -1.5
},
{
'date': '2016-03-03',
'price': 100.00,
'dayChange': 2.60
},
{
'date': '2016-03-04',
'price': 101.2,
'dayChange': -1.22
},
{
'date': '2016-03-07',
'price': 104.64,
'dayChange': 3.44
}
],
FB: [
{
'date': '2016-03-02',
'price': 98.32,
'dayChange': -1.1
},
{
'date': '2016-03-03',
'price': 100.00,
'dayChange': 1.68
},
{
'date': '2016-03-04',
'price': 101.2,
'dayChange': 1.2
},
{
'date': '2016-03-07',
'price': 104.64,
'dayChange': 3.44
}
],
GOOGL: [
{
'date': '2016-03-02',
'price': 98.32,
'dayChange': -1.1
},
{
'date': '2016-03-03',
'price': 100.00,
'dayChange': 1.68
},
{
'date': '2016-03-04',
'price': 101.2,
'dayChange': -12
},
{
'date': '2016-03-07',
'price': 104.64,
'dayChange': 1.44
}
]
};
const _ = require('underscore');
const showPerformanceBetweenDates2 = (startDate, endDate) => {
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
const now = new Date().getTime()
if (start > end) { return console.log('Dates are out of order'); }
if (now - start > 31536000000) { return console.log('Start date is over 1 year old'); }
_.mapObject(stocks, (value, key) => {
stocks[key] = value.filter((s) => {
const thisDate = new Date(s.date).getTime();
return thisDate >= start && thisDate <= end;
})
.reduce((totalValue, currentDay) => (totalValue + currentDay.dayChange), 0);
});
console.log(stocks);
};
showPerformanceBetweenDates2('2016-03-03', '2016-03-04')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment