javascript / intermediate
Snippet
Chunking and Slicing Dataset Arrays Using Pure Transformation Pipes
Custom Angular pipes implementing PipeTransform are ideal for immutable array transformations directly inside templates. By checking array validity, normalizing boundary values, and applying Array.prototype.slice, this pipe delivers paginated slices of collections without mutating the source dataset while maintaining high performance through Angular's pure pipe caching.
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
import { Pipe, PipeTransform } from '@angular/core';@Pipe({name: 'paginate',standalone: true,pure: true})export class PaginatePipe implements PipeTransform {public transform<T>(collection: readonly T[] | null | undefined,pageIndex: number,pageSize: number): T[] {if (!Array.isArray(collection) || collection.length === 0) {return [];}const sanitizedPageSize = Math.max(1, Math.floor(pageSize));const sanitizedPageIndex = Math.max(0, Math.floor(pageIndex));const startIndex = sanitizedPageIndex * sanitizedPageSize;if (startIndex >= collection.length) {return [];}return collection.slice(startIndex, startIndex + sanitizedPageSize);}}
angular
Breakdown
1
public transform<T>(collection: readonly T[] | null | undefined, pageIndex: number, pageSize: number): T[] {
Defines a generic transform method accepting a readonly array, target page index, and items per page.
2
if (!Array.isArray(collection) || collection.length === 0) {
Performs defensive guards against null, undefined, or empty inputs to prevent runtime errors.
3
const sanitizedPageSize = Math.max(1, Math.floor(pageSize));
Normalizes the page size to guarantee an integer greater than or equal to 1.
4
return collection.slice(startIndex, startIndex + sanitizedPageSize);
Extracts the designated subset of items using immutable array slicing.