Sometimes we might have some expensive function to calcuate state directly from template:
{ { calculate (item.num)}}
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.tsimport { 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); }}
{ { item.num | calculate }}
If we call 'calcualate' with the same params, it will return the cached value.