Dajme tomu ze mame objekt, ktory obaluje iny objekt ten objekt "sporostredkuje" "bezpecne" nastavenie a citanie hodnot na entite
import * as R from 'ramda';
export type TPath = string | string[];
type TEntity = {
Id: number;
Name: string;
Body: string;
CustomProps: any;
}
export class CustomProps {
constructor(private entity: TEntity) {}
protected toPath = (path: TPath) => [
'CustomProps', ...Array.isArray(path) ? path : path.split('/')
]
get(path: TPath, defaultValue: any = undefined) {
return R.pathOr(defaultValue, this.toPath(path), this.entity);
}
set(path: TPath, value: any) {
this.entity = R.assocPath(this.toPath(path), value, this.entity);
// toto je zle nakolko povodny objekt sa premaze novym JS nema operator &=
}
}
const nejakaEntita = {
Id: 5,
Name: "Ukážka dákej entity",
Body: "Lorem ipsum",
CustomProps: {}
}
let customProps = new CustomProps(nejakaEntita);
customProps.set('style/border/thickness', 5);
console.log('nejakaEntita', nejakaEntita);
nezmeni nic nakolko v metode set sa this.entity nahradi novym objektom na inom mieste v pamati a this.props ukazuje na novy objekt.