Skip to content

Instantly share code, notes, and snippets.

@jcalz
Created July 25, 2017 14:44
Show Gist options
  • Save jcalz/9fbcbf1eefd8856c9524d1a4be3e20de to your computer and use it in GitHub Desktop.
Save jcalz/9fbcbf1eefd8856c9524d1a4be3e20de to your computer and use it in GitHub Desktop.
Builder Pattern example code
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