javascript / intermediate
Snippet
Stateful Immutable Array Operations in Signal-Driven Services
Combining object-oriented inheritance with Angular Signals creates structured state containers for array manipulation. Modern ECMAScript non-mutating array methods such as toSorted and toSpliced produce fresh immutable array instances inside signal update callbacks, preventing unexpected mutation bugs while cleanly notifying reactive consumers.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { Injectable, signal, computed } from '@angular/core';export interface TaskRecord {readonly id: string;readonly priority: number;readonly title: string;}export abstract class BaseCollectionModel<T extends { id: string }> {protected readonly itemsSignal = signal<readonly T[]>([]);readonly items = this.itemsSignal.asReadonly();readonly count = computed(() => this.itemsSignal().length);abstract sortEntries(): void;}@Injectable({ providedIn: 'root' })export class TaskManagerService extends BaseCollectionModel<TaskRecord> {sortEntries(): void {this.itemsSignal.update(current =>current.toSorted((a, b) => b.priority - a.priority));}removeTaskById(targetId: string): void {this.itemsSignal.update(current => {const index = current.findIndex(task => task.id === targetId);return index !== -1 ? current.toSpliced(index, 1) : current;});}}
angular
Breakdown
1
export abstract class BaseCollectionModel<T extends { id: string }> {
Declares an abstract generic base class enforcing object-oriented structure and generic item constraints.
2
current.toSorted((a, b) => b.priority - a.priority)
Uses the immutable toSorted() method to create a new sorted array copy without mutating existing signal state.
3
return index !== -1 ? current.toSpliced(index, 1) : current;
Employs toSpliced() to return a new array omitting the target index without altering the original array reference.