Last active
October 10, 2023 14:32
-
-
Save davidalves1/8962fb688774b7dc1eb9040824c9d60b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Accumulator { | |
[key: string]: any | |
} | |
interface CurrentItem { | |
[index: number]: string | |
} | |
const convertToSnakeCase = (key: string) => key.replace(/[A-Z]/g, '_$&') | |
.toLowerCase() | |
const convertToCamelCase = (key: string) => key.replace(/(_[a-z])/g, (a) => a.toUpperCase() | |
.replace(/_/, '')) | |
const baseParse = (cb: Function) => | |
(acc: Accumulator, { 0: key, 1: value }: CurrentItem) => Object.assign(acc, {[cb(key)]: value}) | |
export const parseRequestToDatabase = (response: object) => Object.entries(response) | |
.reduce(baseParse(convertToSnakeCase), {}) | |
export const parseDatabaseToResponse = (response: object) => Object.entries(response) | |
.reduce(baseParse(convertToCamelCase), {}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { parseDatabaseToResponse, parseRequestToDatabase } from './objectTransform'; | |
let testObj: {[key: string]: any} = {}; | |
for (let i = 0; i < 100; i++) { | |
testObj[`testUserName${i}`] = i * 10; | |
} | |
console.time('requestToDatabase') | |
const objToDatabase = parseRequestToDatabase(testObj) | |
console.timeEnd('requestToDatabase') | |
console.time('databaseToResponse') | |
parseDatabaseToResponse(objToDatabase) | |
console.timeEnd('databaseToResponse') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment