wjvander
wjvander

Reputation: 601

Return destructed argument in JavaScript

Scenario: I have an object that I want to save, before saving I want to an ID to the object and after saving return the object with it's ID.

Let's assume I have the following basic function:

let create = (someObj) => {
  if (!someObj.id)
    someObject.id = 'myNewIdForThisObject';

  ... // persisting happens here
  return someObj;
}

Now that works just fine, but some people are calling this function not providing an object, so I want to prevent that like so:

let mandatory = () {
  throw new Error('Missing argument');
}

let create = (someObj = mandatory()) => {
  if (!someObj.id)
    someObject.id = 'myNewIdForThisObject';

  ... // persisting happens here
  return someObj;
}

Ok so that is great, but now they do provide an object but with no name (I know, sad panda). So I can make the name property mandatory as well by destructing the argument:

let mandatory = () {
  throw new Error('Missing argument');
}

let create = ({name = mandatory()} = mandatory()) => {
 ...
}

That also means I can have the ID in the object like so:

let create = ({id = 'myNewIdForThisObject', name = mandatory()} = mandatory()) => {
  ... //persistence happens here
  // here I would like to return the parameter with it's ID
  // without rebuilding the object
}

What I would like to know is how do I return the destructed argument from the function without rebuilding the object inside the function.

I cannot simply return arguments[0], because of the defaults being used it will not return what gets assigned, only what was passed in.

Is there a way to name the destructed object to simply return it?

Upvotes: 1

Views: 537

Answers (1)

PeterMader
PeterMader

Reputation: 7275

No, I don't think it's possible to use destructuring on an argument and give the argument a name. Does the following not work for you?

let create = (someObj = mandatory()) => {
  const {id = 'myNewIdForThisObject', name = mandatory()} = someObj;
  someObj.id = id;
  return someObj;
}

Upvotes: 3

Related Questions