-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathmaxPriorityQueue.js
More file actions
66 lines (60 loc) · 1.77 KB
/
maxPriorityQueue.js
File metadata and controls
66 lines (60 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @copyright 2020 Eyas Ranjous <eyas.ranjous@gmail.com>
* @license MIT
*/
const { PriorityQueue } = require('./priorityQueue');
/**
* @class MaxPriorityQueue
* @extends PriorityQueue
*/
class MaxPriorityQueue extends PriorityQueue {
constructor(options, values) {
// Handle legacy options format ({ compare: fn })
if (options && typeof options === 'object' && typeof options.compare === 'function') {
const compareFunction = (a, b) => options.compare(a, b) <= 0 ? -1 : 1;
super(compareFunction, values);
} else {
// Current format (direct compare function)
const getCompareValue = options;
if (getCompareValue && typeof getCompareValue !== 'function') {
throw new Error('MaxPriorityQueue constructor requires a callback for object values');
}
// Create a MaxHeap-compatible compare function
const compare = (a, b) => {
const aVal = typeof getCompareValue === 'function' ? getCompareValue(a) : a;
const bVal = typeof getCompareValue === 'function' ? getCompareValue(b) : b;
return aVal < bVal ? 1 : -1;
};
super(compare, values);
}
}
/**
* Adds a value to the queue
* @public
* @param {number|string|object} value
* @returns {MaxPriorityQueue}
*/
enqueue(value) {
super.enqueue(value);
return this;
}
/**
* Adds a value to the queue
* @public
* @param {number|string|object} value
* @returns {MaxPriorityQueue}
*/
push(value) {
return this.enqueue(value);
}
}
/**
* Creates a priority queue from an existing array
* @public
* @static
* @returns {MaxPriorityQueue}
*/
MaxPriorityQueue.fromArray = function fromArray(values, options) {
return new MaxPriorityQueue(options, values);
};
exports.MaxPriorityQueue = MaxPriorityQueue;