Reputation: 3605
I'm new to Javascript and thus this question, I understand arrow functions. However this syntax completely confuses me. This is an implementation of a PriorityQueue which takes a function comparator as a callback, this is the syntax,
class PriorityQueue {
constructor({ comparator = (a, b) => a - b, initialValues = [] } = {}) {
this.comparator = comparator;
this.data = initialValues;
this.heapify();
}
I don't understand what this line means,
{ comparator = (a, b) => a - b, initialValues = [] } = {}
The complete code is here, should you need it, https://github.com/jeantimex/javascript-problems-and-solutions/blob/master/src/common/priority-queue.js
But can someone please help me understand that line of code. Thanks in anticipation.
Upvotes: 3
Views: 1336
Reputation: 370729
The constructor expects zero or one argument, which, if provided, should be an object.. If the argument is not provided, it defaults to an empty object. Then, it checks the (possibly empty) object for the properties comparator
and initialValues
. If those properties exist on the object, they are extracted into those variable names (comparator
and initialValues
) - otherwise, those variable names are assigned the default values, (a, b) => a - b
for comparator
and []
for initialValues
.
Eg
new PriorityQueue()
results in a PriorityQueue
with .comparator
of (a, b) => a - b
and initialValues
of []
, whereas
new PriorityQueue({ comparator: (a, b) => a.localeCompare(b) })
results in a PriorityQueue
with .comparator
of (a, b) => a.localeCompare(b)
and initialValues
of []
.
If properties other than comparator
or initialValues
are in the passed argument, they are ignored.
Written verbosely, without default parameters:
class PriorityQueue {
constructor(obj) {
if (obj === undefined) {
obj = {};
}
if (obj.comparator === undefined) {
obj.comparator = (a, b) => a - b;
}
if (!obj.initialValues === undefined) {
obj.initialValues = [];
}
// main constructor body starts here
this.comparator = obj.comparator;
this.data = obj.initialValues;
this.heapify();
}
Upvotes: 3