0

I recently started studying a bit of AngularJS (with almost no previous experiences in programming). I would like to create a tool for statistical analysis and to do so I worked on a few "proof-of-concept" examples.

Like this one: http://jsfiddle.net/nitecorp/udcjnoxo/

It works but I have the feeling that the way I am using the functions is highly inefficient:

<tr>
    <td>Average Age</td>
    <td>{{getAverage()}}</td>
</tr>
<tr>
    <td>Younger</td>
    <td>{{getStats(getAges())['younger']}}</td>
</tr>
<tr>
    <td>Older</td>
    <td>{{getStats(getAges())['older']}}</td>
</tr>

Question What is the right approach to store getAges and use the results instead of recalculating every time? Same for getStats: can I just store the values instead of recalculating twice (in the example)?

Note: In this example is not a big deal, but I need to apply that code to a more complex scenario, with more complex stats (standard deviation, variance etc) and using more than 1M values...

Thanks

4
  • So you want to render 1M rows long table to a page? Commented Mar 14, 2015 at 8:46
  • Not really, I need to calculate similar stats as the JSFiddle but over much bigger data. And I am concerned that however simple calculation run on huge arrays might affect performance if code is not efficient. Commented Mar 14, 2015 at 8:50
  • So calculate it once in the controller and pass. Commented Mar 14, 2015 at 9:05
  • That's exactly what I don't know how to do... Commented Mar 14, 2015 at 9:05

1 Answer 1

1

Use a $watch to listen for updates to your data structure, then update your variables accordingly.

I've created a fork of your fiddle to illustrate this, with the code below demonstrating the important bits:

$scope.$watch(
    function(scope) {
        return $scope.dogs.length;
    },
    function(oldVal, newVal) {
        console.log('dogs changed');
        $scope.updateStats($scope.getAges());
        $scope.updateAverage();
    });
Sign up to request clarification or add additional context in comments.

1 Comment

It took a bit to implement it in my project but it´s working like a charm! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.