simontonsoftware / s-libs

A collection of libraries for any of javascript, rxjs, or angular.
MIT License
43 stars 5 forks source link

Creating an async Generator-based version of micro-dash #73

Closed benallfree closed 5 months ago

benallfree commented 2 years ago

Hey there again,

I'm working on a cooperative multitasking system meant to manage jobs and time-slice soas not to jank UI threads or server-side processes.

I'm to the point of writing helper methods like map/reduce/forEach and realized I'm basically implementing an async, Generator-based version of micro-dash.

I ended up pulling the micro-dash lib into my code to see how it handles. The changes look like this:

export function times<T>(n: number, iteratee: (index: number) => T): T[] {
  const result: T[] = [];
  for (let i = 0; i < n; ++i) {
    result[i] = iteratee(i);
  }
  return result;
}

becomes

export async function times<T>(
  n: number,
  iteratee: (index: number) => T
): Promise<T[]> {
  const result: T[] = []
  push(function* () {
    for (let i = 0; i < n; ++i) {
      result[i] = iteratee(i)
      yield
    }
  })
  return result
}

where push is my function that pushes the job onto the stack. It runs the function generator until receiving the done signal, but pauses every so often to return control to the event loop.

Basically this type of change touches every micro-dash function that iterates over arrays/collections/objects in any way.

So one thought I had was that this could possibly be better suited as a fork of micro-dash where all the necessary functions are async with a configurable push primitive. The default one would just execute the generator until done, but then it could be swapped with other implementations to enable cooperative multitasking.

For now I'm just giving you a heads up about an interesting derivation of micro-dash. The new version can live in my project for the time being, and I'll make sure the test suite continues to work with async modifications.

ersimont commented 2 years ago

Fancy! If you publish it and would like a link let me know. 😃

Sorry for the delay - I was on vacation so I'm catching up with things.

ersimont commented 5 months ago

Just cleaning up a few old, open tickets that don't have action items for me