From 0598ec0062dc6a9bbaebc7142bff8a079275111f Mon Sep 17 00:00:00 2001 From: Dani Palou Date: Thu, 22 Jun 2023 11:30:15 +0200 Subject: [PATCH] MOBILE-4368 core: Implement CoreObject.consumeKey utility --- src/core/singletons/object.ts | 14 ++++++++++++++ src/core/singletons/tests/object.test.ts | 16 ++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/core/singletons/object.ts b/src/core/singletons/object.ts index e89b0e0ff..a0e0ee4ac 100644 --- a/src/core/singletons/object.ts +++ b/src/core/singletons/object.ts @@ -30,6 +30,20 @@ export type CoreObjectWithoutUndefined = Pretty<{ */ export class CoreObject { + /** + * Returns a value of an object and deletes it from the object. + * + * @param obj Object. + * @param key Key of the value to consume. + * @returns Whether objects are equal. + */ + static consumeKey(obj: T, key: K): T[K] { + const value = obj[key]; + delete obj[key]; + + return value; + } + /** * Check if two objects have the same shape and the same leaf values. * diff --git a/src/core/singletons/tests/object.test.ts b/src/core/singletons/tests/object.test.ts index c0ce0d302..64702ef10 100644 --- a/src/core/singletons/tests/object.test.ts +++ b/src/core/singletons/tests/object.test.ts @@ -16,6 +16,22 @@ import { CoreObject } from '@singletons/object'; describe('CoreObject singleton', () => { + it('consumes object keys', () => { + const object = { + foo: 'a', + bar: 'b', + baz: 'c', + }; + + const fooValue = CoreObject.consumeKey(object, 'foo'); + const bazValue = CoreObject.consumeKey(object, 'baz'); + + expect(fooValue).toEqual('a'); + expect(bazValue).toEqual('c'); + expect(object.bar).toEqual('b'); + expect(Object.keys(object)).toEqual(['bar']); + }); + it('compares two values, checking all subproperties if needed', () => { expect(CoreObject.deepEquals(1, 1)).toBe(true); expect(CoreObject.deepEquals(1, 2)).toBe(false);