ephemeral.ts (676B)
1 export class Ephemeral<T> { 2 static of<T>(value: NonNullable<T>, ttl: number): Ephemeral<NonNullable<T>> { 3 return new this(value, Date.now() + ttl); 4 } 5 6 static empty(): Ephemeral<never> { 7 return new this(); 8 } 9 10 constructor( 11 private readonly value: T | null = null, 12 public readonly expire: number = 0, 13 ) { 14 } 15 16 get ttl(): number { 17 return Math.max(this.expire - Date.now(), 0); 18 } 19 20 get isExpired(): boolean { 21 return this.value === null || 22 this.value === undefined || 23 this.ttl === 0; 24 } 25 26 orElse<U = T>(value: U): T | U { 27 return !this.isExpired ? this.value! : value; 28 } 29 30 valueOf() { 31 return this.orElse(null); 32 } 33 }