Skip to content

Instantly share code, notes, and snippets.

@stevethedev
Created April 15, 2018 16:23
Show Gist options
  • Select an option

  • Save stevethedev/752015aae16e2d935ad36c3b5759a286 to your computer and use it in GitHub Desktop.

Select an option

Save stevethedev/752015aae16e2d935ad36c3b5759a286 to your computer and use it in GitHub Desktop.
Tick Sort - A useless sorting algorithm for Node.js
/**
* @author Steven Jimenez <steven@stevethedev.com>
*/
'use strict';
async function tickSort(array) {
let smallest = Infinity;
for (let i = 0; i < array.length; ++i) {
if (smallest > array[i]) {
smallest = array[i];
}
}
const values = array.splice(0, array.length);
await Promise.all(values.map((value) => new Promise((resolve) => {
return tickSort.schedule(resolve, array, value, value - smallest);
})));
return array;
}
tickSort.schedule = function schedule(resolve, array, value, wait) {
if (wait > 0) {
return process.nextTick(() => schedule(resolve, array, value, --wait));
}
array.push(value);
return resolve();
};
(async () => {
const array = [1, 3, 8, -4, 6, 2, 7, 5, -1, 0, -3, -8, 4, -6, -2, -7, -5];
console.log(array);
await tickSort(array);
console.log(array);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment