Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created August 20, 2019 22:27
Show Gist options
  • Save freddi301/3021cbe7ec9788978b8eea40cf79cc1a to your computer and use it in GitHub Desktop.
Save freddi301/3021cbe7ec9788978b8eea40cf79cc1a to your computer and use it in GitHub Desktop.
Fiber (react fibers outside react) immutable version
type FiberFunction<Args extends any[], Return> = (
cell: CellFunction
) => (...args: Args) => Return;
type FiberInstance<Args extends any[], Return> = (
...args: Args
) => [Return, FiberInstance<Args, Return>];
type FiberFactory = <Args extends any[], Return>(
fiber: FiberFunction<Args, Return>,
cells: any[]
) => FiberInstance<Args, Return>;
const fiberFactory: FiberFactory = (fiberFunction, cells) => (...args) => {
let index = 0;
const newCells: any[] = [];
const cell: CellFunction = callback =>
(newCells[index] = callback(cells[index++]));
const result = fiberFunction(cell)(...args);
return [result, fiberFactory(fiberFunction, newCells)];
};
export const fiber = <Args extends any[], Return>(
fiberFunction: FiberFunction<Args, Return>
) => fiberFactory(fiberFunction, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment