Skip to content

Instantly share code, notes, and snippets.

@nyancodeid
Created August 11, 2020 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyancodeid/270c07334677f8dea541ef795cd81c42 to your computer and use it in GitHub Desktop.
Save nyancodeid/270c07334677f8dea541ef795cd81c42 to your computer and use it in GitHub Desktop.
Sorting in Javascript
/**
* @function
* @template T
* @param {T} item
* @return {Promise.<T>}
*/
const sortItem = function (item) {
return new Promise((resolve, reject) => {
setTimeout(() => {
this.store(item);
}, item);
});
};
/**
* @function
* @template T
* @param {T[]} items
* @return {Promise.<T[]>}
*/
const sortItems = function (items) {
return new Promise((resolve) => {
const sorted = [];
items.forEach(
sortItem.bind({
store: function (item) {
sorted.push(item);
if (sorted.length == items.length) {
resolve(sorted);
}
},
})
);
});
}
async function main() {
const items = [10, 5, 20, 20, 50, 100, 1, 200, 30];
const sorted = await sortItems(items);
console.log(items); // [ 10, 5, 20, 20, 50, 100, 1, 200, 30 ]
console.log(sorted); // [ 1, 5, 10, 20, 20, 30, 50, 100, 200 ]
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment