Skip to content

Instantly share code, notes, and snippets.

@nyancodeid
Created August 11, 2020 16:17
Show Gist options
  • Select an option

  • Save nyancodeid/270c07334677f8dea541ef795cd81c42 to your computer and use it in GitHub Desktop.

Select an option

Save nyancodeid/270c07334677f8dea541ef795cd81c42 to your computer and use it in GitHub Desktop.

Revisions

  1. nyancodeid created this gist Aug 11, 2020.
    47 changes: 47 additions & 0 deletions javascript-sort.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    /**
    * @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();