Dimabytes
Dimabytes

Reputation: 536

How to write less in "new"

Construction like "this.uuid = uuid..." and etc seems ugly. How can I write it better?

Seems like this is not the best way.

function account({
  uuid,
  email,
  pass,
  device_id,
  max_rep = 10,
  max_like = 10,
  max_comm = 10,
  max_sub = 10
}) {
  this.uuid = uuid;
  this.email = email;
  this.pass = pass;
  this.device_id = device_id;
  this.max_rep = max_rep;
  this.max_like = max_like;
  this.max_com = max_comm;
  this.max_sub = max_sub;
}

a = new account({
  uuid: '12',
  email: "[email protected]",
  pass: "123",
  device_id: "444"
})

b = new account({
  uuid: '13',
  email: "[email protected]",
  pass: "456",
  device_id: "777"
})

console.log(a,b)

Upvotes: 0

Views: 55

Answers (2)

symlink
symlink

Reputation: 12209

Create a new object in the function, then assign its properties and return:

function account(obj) {
  const act = {};
  
  for (let [key, value] of Object.entries(obj)){
     act[key] = value;
  }
  ["max_rep", "max_like", "max_comm", "max_sub"].forEach((prop) => {
    act[prop] = obj[prop] ? obj[prop] : 10;
  })

  return act;
}

const a = account({
  uuid: '12',
  email: "[email protected]",
  pass: "123",
  device_id: "444",
  max_rep: "123"
})

const b = account({
  uuid: '13',
  email: "[email protected]",
  pass: "456",
  device_id: "777"
})

console.log(a, b)

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191976

You can destructure the props, then generate an object from the props, and assign it to this:

function account({
  uuid,
  email,
  pass,
  device_id,
  max_rep = 10,
  max_like = 10,
  max_comm = 10,
  max_sub = 10
}) {
  Object.assign(this, {
    uuid,
    email,
    pass,
    device_id,
    max_rep,
    max_like,
    max_comm,
    max_sub
  });
}

const a = new account({
  uuid: '12',
  email: "[email protected]",
  pass: "123",
  device_id: "444"
})

const b = new account({
  uuid: '13',
  email: "[email protected]",
  pass: "456",
  device_id: "777"
})

console.log(a)

console.log(b)

Upvotes: 2

Related Questions