UNPKG

space-lift

Version:

TypeScript Array, Object, Map, Set, Union, Enum utils

87 lines (86 loc) 2.6 kB
import { clone } from './immupdate'; export class ObjectWrapper { constructor(_value) { this._value = _value; this._isLiftWrapper = true; this.pipe = pipe; } value() { return this._value; } _clone() { return clone(this._value); } /** * Adds a new key/value to this object. This creates a new type. * To add a nullable key to an object while preserving its type, use "update()" instead. */ add(key, value) { const result = this._clone(); result[key] = value; return new ObjectWrapper(result); } /** * Returns whether this object contains no keys. */ isEmpty() { return Object.keys(this.value()).length === 0; } /** * Creates an Array of all this object's keys, in no particular order. * If the keys are a subtype of string, the Array will be typed with the proper key union type. */ keys() { return this.pipe(o => Object.keys(o)); } /** * Maps one of this Object values, by key. * This is similar to remove('key').add('key', newValue) but is less error prone. * This can change the type of the object. */ mapValue(key, mapFunction) { return this.pipe(o => (Object.assign(Object.assign({}, o), { [key]: mapFunction(o[key]) }))); } /** * Maps this Object's values. * This is mostly useful for objects with a single value type. */ mapValues(mapFunction) { return this.toArray().reduce({}, (result, [key, value]) => { result[key] = mapFunction(value); return result; }); } /** * Removes a key/value from this object and return a new object (and type) * To delete a (nullable) key from an object while preserving its type, use "update()" instead. */ remove(keyToRemove) { const result = this._clone(); delete result[keyToRemove.toString()]; return new ObjectWrapper(result); } /** * Creates an Array with all these object's values. */ values() { return this.pipe(Object.values); } /** * Converts this Object to an Array of tuples. * Similar to Object.entries() but retains the type of keys. */ toArray() { return this.pipe(Object.entries); } /** * Transforms this Object to a Map where the keys are the string typed keys of this Object. */ toMap() { return this.pipe(o => new Map(Object.entries(o))); } } let pipe; export function setObjectPipe(_pipe) { pipe = _pipe; }