diff --git a/packages/object-util/__tests__/index.test.ts b/packages/object-util/__tests__/index.test.ts index 424745e..5e6fcb8 100644 --- a/packages/object-util/__tests__/index.test.ts +++ b/packages/object-util/__tests__/index.test.ts @@ -1,6 +1,6 @@ /// -import { isObject, objectClean, objectClone, objectEqual, objectKeys, objectLoop, objectMap, objectOmit, objectSet, objectSize, objectSort, objectValues } from '../src/ObjectUtil' +import { isObject, objectClean, objectClone, objectEqual, objectKeys, objectLoop, objectMap, objectOmit, objectRemap, objectSet, objectSize, objectSort, objectValues } from '../src/ObjectUtil' describe('Throw if parameter is not an object', () => { it('should works', () => { @@ -386,3 +386,30 @@ describe('Is Object Tests', () => { }) it('array is an object', () => expect(isObject([])).toBe(true)) }) + + +describe('object remap tests', () => { + it('should works on objects', () => { + expect(objectRemap({a: "pouet"}, (value, key) => { + return {key: key + 'a', value} + })).toEqual({aa: "pouet"}) + }) + it('should works on arrays', () => { + const pouet: [string] = ['pokemon'] + expect(objectRemap(pouet, (value, key: number) => { + return {key: key + 2, value} + })).toEqual({2: "pokemon"}) + }) + it('should replace value', () => { + expect(objectRemap({a: 'a', b: 'b'}, (value) => { + return {key: 'b', value} + })).toEqual({b: 'b'}) + }) + it('should throw an error in strict mode', () => { + expect(() => { + objectRemap({a: 'a', b: 'b'}, (value) => { + return {key: 'b', value} + }, {strict: true}) + }).toThrow() + }) +}) diff --git a/packages/object-util/src/ObjectUtil.ts b/packages/object-util/src/ObjectUtil.ts index 9e658b1..800a378 100644 --- a/packages/object-util/src/ObjectUtil.ts +++ b/packages/object-util/src/ObjectUtil.ts @@ -22,6 +22,38 @@ export function objectMap( + obj: BasicObject, + fn: (value: T, key: K, index: number) => {key: keyof J, value: J[typeof key]}, + options?: {strict?: boolean} +): J { + mustBeObject(obj) + const clone: J = {} as any + objectLoop(obj, (item, oldKey, index) => { + const { key, value } = fn(item, oldKey, index) + if (options?.strict && key in clone) { + throw new Error('objectRemap strict mode active, you can\'t remap the same key twice') + } + clone[key] = value + }) + return clone +} + /** * Loop through the object * @@ -296,6 +328,7 @@ export function mustBeObject(item: any): item is BasicObject { export default { objectMap, + objectRemap, objectLoop, objectToArray, objectKeys,