[Angular] Using Pipe for function memoization
Sometimes we might have some expensive function to calcuate state directly from template:
<div class="chip"> {{ calculate (item.num)}} </div>
calculate(num: number) { return fibonacci(num); }
The ´calculate´ function is a pure function, we can use memoization to imporve the profermance. Angualr pure Pipe is good match for that:
// calculate.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; const fibonacci = (num: number): number => { if (num === 1 || num === 2) { return 1; } return fibonacci(num - 1) + fibonacci(num - 2); }; @Pipe({ name: 'calculate' }) export class CalculatePipe implements PipeTransform { transform(num: number): any { return fibonacci(num); } }
<div class="chip"> {{ item.num | calculate }} </div>
If we call 'calcualate' with the same params, it will return the cached value.