2022-11-07 22:31:17 +01:00
|
|
|
interface TypeMap {
|
2022-11-06 13:50:39 +01:00
|
|
|
string: string
|
|
|
|
number: number
|
2022-11-24 22:12:40 +01:00
|
|
|
bigint: bigint
|
2022-11-06 13:50:39 +01:00
|
|
|
boolean: boolean
|
|
|
|
object: object
|
2022-11-24 22:12:40 +01:00
|
|
|
symbol: symbol
|
|
|
|
undefined: undefined
|
2022-11-06 13:50:39 +01:00
|
|
|
}
|
|
|
|
|
2022-11-24 22:12:40 +01:00
|
|
|
// Type predicate higher order function for use with e.g. filter or map
|
|
|
|
export function isType<T extends keyof TypeMap>(type: T): (v: unknown) => v is TypeMap[T] {
|
2022-11-06 13:50:39 +01:00
|
|
|
return (v: unknown): v is TypeMap[T] => typeof v === type
|
|
|
|
}
|
2022-11-08 01:19:15 +01:00
|
|
|
|
2022-11-24 22:12:40 +01:00
|
|
|
// Type predicate for object keys
|
|
|
|
// Only safe for const objects, as other objects might carry additional, undeclared properties
|
|
|
|
export function isKeyOfConstObject<T extends object>(key: string | number | symbol, obj: T): key is keyof T {
|
|
|
|
return key in obj
|
|
|
|
}
|
|
|
|
|
|
|
|
// Use for exhaustiveness checks in switch/case
|
2022-11-08 01:19:15 +01:00
|
|
|
export function assertTypeExhausted(v: never): never {
|
|
|
|
throw new Error(`Type should be exhausted but is not. Value "${JSON.stringify(v)}`)
|
|
|
|
}
|
2022-11-24 22:12:40 +01:00
|
|
|
|
|
|
|
export function strCamelCaseToSnakeCase(str: string): string {
|
|
|
|
return str
|
|
|
|
.replace(/\B([A-Z][a-z])/g, ' $1')
|
|
|
|
.toLowerCase()
|
|
|
|
.trim()
|
|
|
|
.replace(/\s+/g, '_')
|
|
|
|
}
|
|
|
|
|
|
|
|
export function strReverse(str: string): string {
|
|
|
|
return str.split('').reverse().join('')
|
|
|
|
}
|
|
|
|
|
|
|
|
export function strTrimRight(str: string, char: string): string {
|
|
|
|
return strReverse(strReverse(str).replace(new RegExp(`^[${char}]+`), ''))
|
|
|
|
}
|