javascript / expert
Snippet
Signal-Based Memoization for Derived Object Maps
Deriving a Map from an array using computed() signals creates a highly efficient lookup cache. Since computed signals are memoized, the Map is only rebuilt when the underlying rawUsers signal emits a new value, optimizing O(1) access patterns in templates.
snippet.js
1
2
3
4
5
6
const rawUsers = signal([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);const userMap = computed(() => {return new Map(rawUsers().map(u => [u.id, u]));});const getUser = (id: number) => userMap().get(id);
angular
Breakdown
1
const userMap = computed(() => {
Creates a derived, read-only signal that memoizes the result.
2
return new Map(rawUsers().map(u => [u.id, u]));
Transforms the array into a Map for constant-time lookups.