homebridge-prometheus-exporter/src/std.ts

42 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-11-07 22:31:17 +01:00
interface TypeMap {
2022-11-06 13:50:39 +01:00
string: string
number: number
bigint: bigint
2022-11-06 13:50:39 +01:00
boolean: boolean
object: object
symbol: symbol
undefined: undefined
2022-11-06 13:50:39 +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
// 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)}`)
}
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}]+`), ''))
}