Euge
Euge

Reputation: 51

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}}}

Upvotes: 2

Views: 1604

Answers (2)

Euge
Euge

Reputation: 51

Thanks to @JLRishe 's answer, and understanding that Object.assign is the same as using spread syntax except that since it's non-mutative there is no need for the {} after the ||, here is the version with spread syntax.

'use strict'

const funcUnderTest = (query) => ({
  query:
    {
      $sort: {priority: -1, createdAt: -1},
      ...query
    }
})

console.log(funcUnderTest(null))
console.log(funcUnderTest(({})))
console.log(funcUnderTest(({forCandidate: 123})))
console.log(funcUnderTest(({$sort: {name:1}})))
console.log(funcUnderTest(({forCandidate: 123, $sort: {name:1}})))

Upvotes: 2

JLRishe
JLRishe

Reputation: 101662

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}}}

Upvotes: 6

Related Questions