Created
February 27, 2020 12:09
-
-
Save vabka/358bf760f7da64ef2afa3c09c451ec12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Container<T> = Readonly<{ value: T, pipe<U>(f: (value: T) => U): Container<T> }>; | |
class PersistentContainer<T> implements Container<T> { | |
private readonly _value: T; | |
public get value() { | |
return this._value; | |
} | |
constructor(value: T) { | |
this._value = value; | |
} | |
public readonly pipe = <U>(f: (value: T) => U) => new LazyContainer(() => f(this.value)); | |
} | |
class LazyContainer<T> implements Container<T> { | |
private readonly _factory; | |
private _value: T | undefined; | |
private _initialized: boolean = false; | |
constructor(factory: () => T) { | |
this._factory = factory; | |
} | |
public get value() { | |
if (!this._initialized) { | |
this._value = this._factory(); | |
this._initialized = true; | |
} | |
return this._value; | |
} | |
public readonly pipe = <U>(f: (value: T) => U) => new LazyContainer(() => f(this.value)); | |
} | |
const wrap = <T>(value: T) => new PersistentContainer(value); | |
wrap(10) | |
.pipe(x => x.toString()) | |
.pipe(x => [...x]) | |
.pipe(x => typeof x) | |
.value; // string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment