Skip to content

Instantly share code, notes, and snippets.

@davidalves1
Last active October 10, 2023 14:32
Show Gist options
  • Save davidalves1/8962fb688774b7dc1eb9040824c9d60b to your computer and use it in GitHub Desktop.
Save davidalves1/8962fb688774b7dc1eb9040824c9d60b to your computer and use it in GitHub Desktop.
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), {})
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