@@ -219,6 +219,29 @@ export let drain = pq => {
219219 List.reverse(drainRec([]))
220220}
221221
222+ /**
223+ * Constructs a new priority queue initialized with the elements in the array
224+ * using a custom comparator function, which is used to determine priority of
225+ * elements. The comparator function takes two elements and must return 0 if
226+ * both share priority, a positive number if the first has greater priority,
227+ * and a negative number if the first has less priority.
228+ *
229+ * @param array: An array of values used to initialize the priority queue
230+ * @param comp: A comparator function used to assign priority to elements
231+ * @returns A priority queue containing the elements from the array
232+ *
233+ * @since v0.5.4
234+ */
235+ export let fromArray = (array, comp) => {
236+ let size = Array.length(array)
237+ let array = Array.map(x => Some(x), array)
238+ let heap = { size, array, comp }
239+ for (let mut i = size - 1; i >= 0; i -= 1) {
240+ siftDown(i, heap)
241+ }
242+ heap
243+ }
244+
222245/**
223246 * Constructs a new priority queue initialized with the elements in the list
224247 * using a custom comparator function, which is used to determine priority of
@@ -233,9 +256,6 @@ export let drain = pq => {
233256 * @since v0.5.3
234257 */
235258export let fromList = (list, comp) => {
236- let heap = makeSized(List.length(list), comp)
237- List.forEach(val => {
238- push(val, heap)
239- }, list)
240- heap
259+ let array = Array.fromList(list)
260+ fromArray(array, comp)
241261}
0 commit comments