For source click on [GitHub] & To Tryout click on [CodePen]
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'applyPure',
pure: true // immutable (value) inputs & pure fn (function)
})
export class ApplyPurePipe implements PipeTransform {
transform(value: any, fn: Function): any {
return fn(value);
}
}
@Pipe({
name: 'apply',
pure: false // any (value) inputs & any fn (function)
})
export class ApplyPipe implements PipeTransform {
transform(value: any, fn: Function): any {
return fn(value);
}
}
Write your functions in components, and pass the function itself as pipe value-arg to be applied
@Component()({
selector: 'my-app',
template: `<p>SUM of {{fib | json}} = {{fib | apply: sum}}</p>`
})
class AppComponent {
fib = [1, 2, 3, 5, 8];
public sum(collection: [number]): number {
return collection.reduce((first, second) => first + second);
}
}
Pure pipes leverage many advantages which come with Pure functions
Impure pipes can’t leverage caching, instance re-use and simple tests
(1) is obvious but (2) is something easy to trip over. Let us see it with examples