Skip to content

Instantly share code, notes, and snippets.

@Fray117
Created October 19, 2023 06:48
Show Gist options
  • Save Fray117/f78b9607b8b6b0f718e58cc7c16cdfbf to your computer and use it in GitHub Desktop.
Save Fray117/f78b9607b8b6b0f718e58cc7c16cdfbf to your computer and use it in GitHub Desktop.
import { faker } from '@faker-js/faker'
export type User = {
fullName?: string
title?: string
deputy?: string
department?: string
visible?: boolean
}
export type UserCreate = {
fullName: string
title?: string
deputy?: string
department?: string
visible?: boolean
}
export type UserUpdate = {
fullName?: string
title?: string
deputy?: string
department?: string
visible?: boolean
}
export function createRandomUser(): User {
return {
fullName: faker.datatype.boolean() ? faker.person.fullName() : undefined,
title: faker.datatype.boolean() ? faker.person.jobTitle() : undefined,
deputy: faker.datatype.boolean() ? faker.person.jobArea() : undefined,
department: faker.datatype.boolean() ? faker.commerce.department() : undefined,
visible: faker.datatype.boolean() ? faker.datatype.boolean() : undefined,
}
}
export function mockRequest(userDto: User) {
const schema = {
fullName: userDto.fullName,
title: userDto.title,
deputy: userDto.deputy,
department: userDto.department,
visible: userDto.visible,
}
const updateSchema = {}
for (const key in userDto) {
if (userDto[key]) updateSchema[key] = userDto[key]
}
return {
create: schema,
update: updateSchema,
}
}
export function mockRequestClean(userDto: User) {
const schema = {
fullName: userDto.fullName,
title: userDto.title,
deputy: userDto.deputy,
department: userDto.department,
visible: userDto.visible,
}
return {
create: schema,
// https://stackoverflow.com/a/38340730/11163784 (ES6/ES2015)
update: Object.keys(schema)
.filter((k) => schema[k] != null)
.reduce((a, k) => ({ ...a, [k]: schema[k] }), {}),
// update: Object.fromEntries(
// Object.entries(schema).filter(([_, value]) => value),
// ),
}
}
export default function measurement() {
console.time('ForLoop')
for (let index = 0; index < 1000; index++) {
mockRequest(createRandomUser())
}
console.timeEnd('ForLoop')
console.time('ObjectKeys')
for (let index = 0; index < 1000; index++) {
mockRequestClean(createRandomUser())
}
console.timeEnd('ObjectKeys')
}
measurement()
@Fray117
Copy link
Author

Fray117 commented Oct 19, 2023

Minimal Benchmark Setup

ForLoop: 30.688ms
ObjectKeys: 23.802ms

This benchmark would likely accurate for the environment server due to threading and anything, however this is not encouraged as final benchmark result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment