简体   繁体   中英

Comparator in a Priority Queue: Javascript

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.

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();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM