UNPKG

twing

Version:

First-class Twig engine for Node.js

70 lines (69 loc) 2.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sortAsynchronously = void 0; const sortAsynchronously = (array, comparator) => { /** * return the median value among x, y, and z */ const getPivot = async (x, y, z, comparator) => { if (await comparator(x, y) < 0) { if (await comparator(y, z) < 0) { return y; } else if (await comparator(z, x) < 0) { return x; } else { return z; } } else if (await comparator(y, z) > 0) { return y; } else if (await comparator(z, x) > 0) { return x; } else { return z; } }; /** * Asynchronous quick sort. * * @see https://gist.github.com/kimamula/fa34190db624239111bbe0deba72a6ab * * @param array The array to sort * @param comparator The comparator function * @param left The index where the range of elements to be sorted starts * @param right The index where the range of elements to be sorted ends */ const quickSort = async (array, comparator, left = 0, right = array.length - 1) => { if (left < right) { let i = left; let j = right; let tmp; const pivot = await getPivot(array[i], array[i + Math.floor((j - i) / 2)], array[j], comparator); while (true) { while (await comparator(array[i], pivot) < 0) { i++; } while (await comparator(pivot, array[j]) < 0) { j--; } if (i >= j) { break; } tmp = array[i]; array[i] = array[j]; array[j] = tmp; i++; j--; } await quickSort(array, comparator, left, i - 1); await quickSort(array, comparator, j + 1, right); } return array; }; return quickSort(array, comparator); }; exports.sortAsynchronously = sortAsynchronously;