TypeScript is great, but I often feel like there are fundamental pieces missing. This document is my go-to when I need some re-ocurring feature.
Snippets are in Pulic Domain.
Separate array into two arrays based on filter
function partition<T>(array: T[], predicate: (element: T) => boolean): [T[], T[]] {
const pass: T[] = [], fail: T[] = []
for (const element of array) {
(predicate(element) ? pass : fail).push(element)
}
return [pass, fail]
}
Example
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const [pass, fail] = partition(arr, x => x < 5)
console.log(pass) // [0, 1, 2, 3, 4]
console.log(fail) // [5, 6, 7, 8, 9]
Type-safe truthy filter
function truthy<T>(element: T): element is NonNullable<T> {
return Boolean(element)
}
Example
const list = ['test', undefined, '', null, 'best']
const strings: string = list.filter(truthy)
console.log(strings) // ['test', 'best']
Public Domain