Presupuestador_web/shared/lib/contexts/common/domain/entities/KeyValueMap.ts
2024-06-17 18:54:30 +02:00

36 lines
952 B
TypeScript

import { Result } from "./Result";
import { Primitive, ValueObject } from "./ValueObject";
type KeyValueMapProps = Map<string, Primitive>;
export class KeyValueMap extends ValueObject<KeyValueMapProps> {
public static create(entries?: [string, Primitive][]) {
const map = new Map<string, Primitive>(entries);
return Result.ok(new KeyValueMap(map));
}
get(key: string): Primitive | undefined {
return this.props.get(key);
}
set(key: string, value: Primitive): KeyValueMap {
const newMap = new Map(this.props);
newMap.set(key, value);
return new KeyValueMap(newMap);
}
delete(key: string): KeyValueMap {
const newMap = new Map(this.props);
newMap.delete(key);
return new KeyValueMap(newMap);
}
public toPrimitive(): string {
return JSON.stringify(Object.fromEntries(this.props.entries()));
}
public entries(): [string, Primitive][] {
return Array.from(this.props.entries());
}
}