0

I've got the following data for a single stock across a range of dates which for the moment is an Ember fixture:

App.Stock.FIXTURES = [
    {
        id:1,
        value:85.7,
        date: '2014-01-01T00:00:00'
    },
    {
        id:2,
        value:82.7,
        date: '2014-01-02T00:00:00'
    },  
    {
        id:3,
        value:89.5,
        date: '2014-01-03T00:00:00'
    }
]

What's the most sensible way to get things such as the current price (defined by the highest date) or the highest value this year?

tooba
  • 551
  • 5
  • 22

1 Answers1

1

I would define these calculated properties in a controller. So for example:

App.SomeRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('stock');
    }
});

App.SomeController = Ember.ArrayController.extend({
    dateSorting: ['date:desc'],

    sortedByDate: Ember.computed.sort('model', 'dateSorting'),

    filteredByCurrentYear: Ember.computed.filter('model',function(stock) {
        var currentYear = new Date().getFullYear();
        // check if date begins with current year
        return stock.get('date').indexOf(currentYear) === 0;
    }),

    valuesCurrentYear: Ember.computed.mapBy('filteredByCurrentYear', 'value'),

    highestValueCurrentYear: Ember.computed.max('valuesCurrentYear'),

    currentPrice: function() {
        var highestDate = this.get('sortedByDate.firstObject');
        return highestDate ? highestDate.get('value') : null;
    }.property('sortedByDate')
});

For date calculations I would recommend to use momentjs though.

jcbvm
  • 1,640
  • 1
  • 15
  • 22