Skip to content

Conversation

@pikax
Copy link
Owner

@pikax pikax commented Mar 29, 2020

Execute function on a webWorker, heavily inspired by https://github.com/alewin/useWorker ❤️

WorkerFunction

Execute function on a worker

  • Promised based
  • Cancel
  • Multi service workers
  • Timeout support
  • Import external scripts
const bubleSort = input => {
  let swap;
  let n = input.length - 1;
  const sortedArray = input.slice();
  do {
    swap = false;
    for (let index = 0; index < n; index += 1) {
      if (sortedArray[index] > sortedArray[index + 1]) {
        const tmp = sortedArray[index];
        sortedArray[index] = sortedArray[index + 1];
        sortedArray[index + 1] = tmp;
        swap = true;
      }
    }
    n -= 1;
  } while (swap);

  return sortedArray;
};

defineComponent({
  setup() {
    const numbers = [...Array(50000)].map(() =>
      Math.floor(Math.random() * 1000000)
    );

    const { exec, loading, result } = useWorkerFunction(bubleSort);

    // on execution `result` will have the sorted numbers, or you can `await sort()`
    const sort = () => exec(numbers);

    return {
      sort,
      loading,
      result
    };
  }
});

Worker

@pikax pikax added the composable New composable label Mar 29, 2020
@pikax pikax marked this pull request as ready for review April 6, 2020 20:25
@pikax pikax merged commit e4c9da9 into master Apr 6, 2020
@pikax pikax deleted the feat/webWorkerFunction branch April 6, 2020 20:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

composable New composable

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants