index.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // @ts-nocheck
  2. // 来自kux大佬的神之一手
  3. // 原地址 https://ext.dcloud.net.cn/plugin?id=23291
  4. export type ControlCommand = 'continue' | 'break' | null;
  5. export type ControllableWhileReturn = {
  6. start: () => void;
  7. abort: () => void;
  8. execContinue: () => 'continue';
  9. execBreak: () => 'break';
  10. };
  11. export type Controller = {
  12. abort: () => void;
  13. };
  14. export function controllableWhile(
  15. condition : () => boolean,
  16. body: (controller: Controller) => ControlCommand
  17. ): ControllableWhileReturn {
  18. let isActive = true;
  19. const controller: Controller = {
  20. abort: () => {
  21. isActive = false;
  22. }
  23. };
  24. const execContinue = () => 'continue';
  25. const execBreak = () => 'break';
  26. return {
  27. start: () => {
  28. // #ifdef APP-ANDROID
  29. UTSAndroid.getDispatcher('io').async((_) => {
  30. // #endif
  31. while (isActive && condition()) {
  32. const result = body(controller);
  33. if (result == 'break') {
  34. controller.abort();
  35. break;
  36. } else if (result == 'continue') {
  37. continue;
  38. }
  39. }
  40. // #ifdef APP-ANDROID
  41. }, null);
  42. // #endif
  43. },
  44. abort: controller.abort,
  45. execContinue: execContinue,
  46. execBreak: execBreak
  47. } as ControllableWhileReturn;
  48. }