Created
July 25, 2017 14:44
-
-
Save jcalz/9fbcbf1eefd8856c9524d1a4be3e20de to your computer and use it in GitHub Desktop.
Builder Pattern example code
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 IBuilder<T> = { | |
[k in keyof T]: (arg: T[k]) => IBuilder<T> | |
} & { build(): T } | |
function proxyBuilder<T>(): IBuilder<T> { | |
var built: any = {}; | |
var builder = new Proxy({}, { | |
get: function(target, prop, receiver) { | |
if (prop === 'build') return () => built; | |
return (x: any): any => { | |
(built[prop] = x); | |
return builder; | |
} | |
} | |
}); | |
return builder as any; | |
} | |
function keyBuilder<T>(allKeys: (keyof T)[]): IBuilder<T> { | |
var built: any = {}; | |
var builder: any = { build: () => built }; | |
allKeys.forEach(k => { | |
builder[k] = function(v: any) { | |
built[k] = v; | |
return builder; | |
} | |
}); | |
return builder as any; | |
} | |
//// | |
interface IPoint { | |
x: number; | |
y: number; | |
z?: number; | |
}; | |
var point1 = proxyBuilder<IPoint>().x(1).y(2).build(); | |
var point2 = keyBuilder<IPoint>(['x', 'y', 'z']).x(1).y(2).build(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment