1
0
mirror of https://github.com/dzeiocom/libs.git synced 2025-07-02 12:19:17 +00:00

feat: introduce objectRemap function

This commit introduces a new function `objectRemap` in `object-util` package. It takes an object as input and applies the provided mapping function to each key-value pair. It produces a new object with transformed keys and values.

The `objectRemap` function is more advanced than `objectMap` as it transforms an object back into another object. It works on objects and arrays. If multiple keys are the same, only the last value will be set by default, but enabling the `strict` option will throw an error if the same key is set twice.

This commit also updates the import statement in tests for this new function.

Signed-off-by: Avior <f.bouillon@aptatio.com>
This commit is contained in:
2023-03-14 10:54:46 +01:00
parent 7cc3ca98c1
commit fd24924d10
2 changed files with 61 additions and 1 deletions

View File

@ -1,6 +1,6 @@
/// <reference types="jest" />
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()
})
})