Created
August 11, 2020 16:17
-
-
Save nyancodeid/270c07334677f8dea541ef795cd81c42 to your computer and use it in GitHub Desktop.
Sorting in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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