Euge Euge - 1 year ago 44
Javascript Question

ES6: Conditional use of spread operator

I would like to write an expression which takes the value of the

query
parameter and generates a new object which contains everything in
query
and the default
$sort
value, but only if
$sort
is not already present.

I feel like I should use the the spread operator
...
to do this, but don't know how I could use it in this instance.

The below code does not work as it always returns
{$sort: {priority: -1, createdAt: -1}}

Ideally it should print out what's in the comments next to the
console.log
statements:

'use strict'
const funcUnderTest = (query) => ({
query: /^sort/.test(query) ? query : {$sort: {priority: -1, createdAt: -1}}
})

console.log(funcUnderTest(null)) // Should be { query: {$sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({}))) // Should be { query: {$sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({forCandidate: 123}))) // Should be { query: {forCandidate: 123, $sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({$sort: {name:1}}))) // Should be { query: {$sort: {name: 1}}}
console.log(funcUnderTest(({forCandidate: 123, $sort: {name:1}}))) // Should be { forCandidate: 123, query: {$sort: {name: 1}}}

Answer Source

You can use Object.assign for this.

I'm going to assume your last example output is a mistake (should be { query: {$sort: {name: 1}, forCandidate: 123}}) because it's inconsistent with your other expected outputs.

'use strict'
const funcUnderTest = (query) => ({
  query: Object.assign({$sort: {priority: -1, createdAt: -1}}, query || {})
})

console.log(funcUnderTest(null)) // Should be { query: {$sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({}))) // Should be { query: {$sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({forCandidate: 123}))) // Should be { query: {forCandidate: 123, $sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({$sort: {name:1}}))) // Should be { query: {$sort: {name: 1}}}
console.log(funcUnderTest(({forCandidate: 123, $sort: {name:1}}))) // Should be { forCandidate: 123, query: {$sort: {name: 1}}}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download