Cursor Pagination With Encode
Implement cursor-based pagination with base64 encode and stable sorting for large dataset navigation.
Code
export interface Cursor{sort:number;id:string;}export function encodeCursor(c:Cursor):string{return Buffer.from(JSON.stringify(c)).toString('base64');}export function decodeCursor(s:string):Cursor{const json=Buffer.from(s,'base64').toString('utf8');const parsed=JSON.parse(json)as Cursor;if(typeof parsed.sort!=='number'||typeof parsed.id!=='string')throw new Error('invalid cursor');return parsed;}export function paginate<T extends{id:string;sort:number}>(items:T[],limit:number):{items:T[];nextCursor:string|null}{const page=items.slice(0,limit);const next=items[limit];return{items:page,nextCursor:next?encodeCursor({sort:next.sort,id:next.id}):null};}Report a problem with this exampleOpens a pre-filled issue on GitHub.