Skip to content

Instantly share code, notes, and snippets.

@vladdeSV
Last active March 9, 2023 13:38
Show Gist options
  • Save vladdeSV/1246acd91711253a1fdb1af38807119c to your computer and use it in GitHub Desktop.
Save vladdeSV/1246acd91711253a1fdb1af38807119c to your computer and use it in GitHub Desktop.
TypeScript snippets I often find myself needing to rewrite.

TypeScript Snippets

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.

array-partition

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]

filter-truthy

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']

License

Public Domain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment