My favorite sorting algorithm is the Timeout Sort. It’s perfect when you’re not in a hurry and don’t have any really big numbers in your array. I first encountered this gem probably on LinkedIn I was immediately impressed by its simplicity and effectiveness.
function timeoutSort(numbers) {
for (const n of numbers) {
setTimeout(() => {
console.log(n);
}, n);
}
}
const numbers = [5, 40, 21, 8, 1, 4];
timeoutSort(numbers);
Inspired by this masterpiece, I decided to explore the topic further and contribute to computer science history with some other delightfully dysfunctional algorithms.
Promise Race Sort
An interesting, more complicated, and even less performant variation of the Timeout Sort algorithm is the Promise Race Sort.
The .race() method returns the first promise that resolves or rejects, so we can use it to sort numbers by iterating through the array and removing the fastest promise after each iteration. Another working masterpiece of inefficiency.
async function promiseRaceSort(numbers) {
const promises = numbers.map(n => ({
value: n,
promise: new Promise(resolve => setTimeout(() => resolve(n), n)),
}));
const sorted = [];
while (promises.length > 0) {
const racePromises = promises.map(p => p.promise);
const winner = await Promise.race(racePromises);
sorted = [...sorted, winner];
const index = promises.findIndex(p => p.value === winner);
promises = promises.filter((_, i) => i !== index);
}
return sorted;
}
const numbers = [5, 40, 21, 8, 1, 4];
promiseRaceSort(numbers).then(sorted => console.log(sorted));
CSS Grid Sort
But why stop at JavaScript when we can use CSS Grid to sort numbers? The idea is simple: we create a grid with the numbers as div content and use the order property to sort the divs visually. Unfortunately, the order is purely visual because the divs are still added to the DOM in their original array order.
I tried to find a CSS selector that could target the visual order of the divs in the grid and print that order to the console, but I failed miserably. If anyone knows how to pull this off, please enlighten me.
function cssGridSort(numbers) {
const container = document.createElement("div");
container.style.display = "grid";
numbers.forEach(n => {
const div = document.createElement("div");
div.textContent = n;
div.style.order = n;
container.appendChild(div);
});
document.body.appendChild(container);
}
const numbers = [5, 40, 21, 8, 1, 4];
cssGridSort(numbers);