Skip to content

Instantly share code, notes, and snippets.

@MrAntix
Created February 9, 2018 16:16
Show Gist options
  • Save MrAntix/d164c7cb06ef7c1924dd5310089743b5 to your computer and use it in GitHub Desktop.
Save MrAntix/d164c7cb06ef7c1924dd5310089743b5 to your computer and use it in GitHub Desktop.
Some base classes for immutable entities in type script
export module Guid {
export function newGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/[xy]/g,
c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}
export interface IHasId {
readonly id: string
}
export abstract class Value<T> {
constructor(
data: any,
private newEntity: { new(data: any): T }) {
Object.assign(this, data);
Object.freeze(this);
}
set(data: Partial<T>): T {
return new this.newEntity(
Object.assign({}, this, data)
);
}
}
export abstract class Entity<T>
extends Value<T>
implements IHasId {
constructor(
data: any,
newEntity: { new(data: any): T }) {
super(
Object.assign({
id: Guid.newGuid()
}, data),
newEntity);
}
readonly id: string
}
export class Thing extends Entity<Thing> {
constructor(
data: Partial<Thing>
) {
super(data, Thing);
}
readonly code: string;
readonly name: string;
}
const thing = new Thing({
code: 'code',
name: 'name'
});
const newThing = thing.set({
name: 'new name'
});
// supports intellisense
// will work even better when Omit<T, 'set'> is working again :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment