UNPKG

ensure-key

Version:

Safe member access with initial value assignment.

19 lines (14 loc) 1 kB
// Safe member access with initial value: // -------------------------------------- // import './Ensure'; // const registry = {}; // registry.ensure('abc', {}).ensure('items', []).push(123); // --> { abc: { items: [ 123 ] } } declare interface Object { /** Safe member access (adds the specified key if not present and assigns the specified initial value). Returns the member's value. */ ensure<TValue>(memberKey: any, initialValue: TValue): TValue; } Object.prototype.ensure = function <TValue>(memberKey: any, initialValue?: TValue): TValue { return this.hasOwnProperty(memberKey) ? this[memberKey] : (this[memberKey] = initialValue); }; /** Best to hide this method from enumeration with for (var m in obj), since some environments run into problems when custom methods suddenly appear on objects (e.g. Office integration in SharePointOnline): */ Object.defineProperty(Object.prototype, "ensure", { enumerable: false, writable: false, configurable: false });