4

Dear all I was going through a question where the accepted answers suggested to use a filter with ng-repeat which basically use lodash's chunk function along with memoize function. The author describe the reason for using memoize is following

Many people prefer to accomplish this in the view with a filter. This is possible, but should only be used for display purposes! If you add inputs within this filtered view, it will cause problems that can be solved, but are not pretty or reliable.

The problem with this filter is that it returns new nested arrays each time.Angular is watching the return value from the filter.

The first time the filter runs, Angular knows the value, then runs it again to ensure it is done changing. If both values are the same, the cycle is ended.

If not, the filter will fire again and again until they are the same, or Angular realizes and infinite digest loop is occurring and shuts down.

Because new nested arrays/objects were not previously tracked by Angular, it always sees the return value as different from the previous.

To fix these "unstable" filters, you must wrap the filter in a memoize function.

lodash has a memoize function and the latest version of lodash also includes a chunk function, so we can create this filter very simply using npm modules and compiling the script with browserify or webpack.

Can anyone please help me understand how memoize is functioning here with ng-repeat and filter?

Community
  • 1
  • 1
Muhammad Raihan Muhaimin
  • 5,559
  • 7
  • 47
  • 68

1 Answers1

1

I guess when you are calling .filter('chunk', func) in angular its like you instruct it the following:

" Whenever a filter with the name 'chunk' is applied, call the function that is returned by my second parameter and pass it:

param1: the array on which it was applied.
param2: the part after ':' 

"

From what I understand in any case the filter will run at least two times.

The problem is that each time chunk is called it accesses the array. Even if there is no actual modification to it, the filter will run again to perform a modification check, so it will again call chunk e.t.c...

By proxifying chunk with memoize it's like we say: "The the output of chunk is deterministic (always the same for the same params), so cache it."

This means that:

  • Filter will be called at least twice.
  • memoize will be called as many times as filter is run.
  • but chunk will only be called one time less.
  • Marinos An
    • 9,481
    • 6
    • 63
    • 96