skip to Main Content

For testing purposes, I wrote a function that generates user objects. The function has parameters with default values, but we can customize it if necessary. User objects may grow large, f.e. these can have 30 properties each, and I don’t want to update function parameters every time plus it looks messy.

Maybe there is better way to do it?

const defaultUser ={
  id: 'test_id',
  last_time: '17:59:00',
  slide_id: 'slide ID',
  name: 'AA1',
  address: 'blabala',
  number_of_houses: 500,
  age: 20,
  active: false,
  children: {
    boy: [],
    girl: []
  },
} 
const generateUSer = ({id:defaultUser.id, last_time=defualtUser.last_time, .....and all the props }={})=>{
return{
id,
last_time,
... and all the props
}
}


const user = generateUSer();
cosnt second_user = generateUSer({name:'test_2'}) 

2

Answers


  1. Try to remove id generation from your defaultUser inside the generateUser() cause it will be cleaner to understand that each user have unique id. Overall, I can suggest improving you generateUser() this way:

    const generateUser = (customProps = {}) => {
      const id = customProps.id || uuid();
      return { ...defaultUser, ...customProps, id };
    };
    

    Spread operator will do the job of annoying reprint of each property and increase the code readability. If you’re not interested in unique ids, just ignore the step with id.

    Login or Signup to reply.
  2. You could do something like this:

    function generateUser(options={}) {
        return {...defaultUser, ...options}
    }
    

    This will make a copy of defaultUser and extend it with your options.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search