Tuesday, 31 May 2022

use memo in your angular component template function call

import { Component } from '@angular/core';

function hasDifferentArgs(prev: unknown[], next: unknown[]) {
if (prev.length !== next.length) return true;
for (let i = 0; i < prev.length; i++) {
if (!Object.is(prev[i], next[i])) return true;
}
return false;
}

function memo(fnToMemoize) {
let prevArgs = [{}];
let result;

return function (...newArgs) {
if (hasDifferentArgs(prevArgs, newArgs)) {
result = fnToMemoize(...newArgs);
prevArgs = newArgs;
}
return result;
};
}

function expensiveComputing(name: string) {
return '$' + name + '$';
}

@Component({
selector: 'my-app',
template: 'Hello, {{fancyName(name)}}!',
})
export class AppComponent {
name = 'World';

fancyName = memo((name) => expensiveComputing(name));
}


No comments:

Post a Comment