Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. import { any } from "prop-types";
  2.  
  3. type Cell = { initialized: boolean; state: any; next: any };
  4.  
  5. export function Cell(): Cell {
  6. return { initialized: false, state: null, next: null };
  7. }
  8.  
  9. export type CellFunction = <State, Initial>(
  10. callback: (state: State | Initial) => State,
  11. init: () => Initial
  12. ) => State;
  13.  
  14. export type CellFunctionTypeIntance<State, Initial> = (
  15. callback: (state: State | Initial) => State,
  16. init: () => Initial
  17. ) => State;
  18.  
  19. export type Fiber<Action, Return> = (
  20. action: Action,
  21. cell: CellFunction
  22. ) => Return;
  23.  
  24. export function makeFiber<Action, Return>(fiber: Fiber<Action, Return>) {
  25. return fiber;
  26. }
  27.  
  28. export function fiberRunner<Action, Return>(
  29. fiber: Fiber<Action, Return>,
  30. rootCell: Cell
  31. ) {
  32. let currentCell = rootCell;
  33. function cell(callback: (state: any) => any, init: () => any) {
  34. if (!currentCell.initialized) {
  35. currentCell.initialized = true;
  36. currentCell.state = init();
  37. currentCell.next = Cell();
  38. }
  39. const newState = callback(currentCell.state);
  40. currentCell.state = newState;
  41. currentCell = currentCell.next;
  42. return newState;
  43. }
  44. const next = (action: Action) => {
  45. const result = fiber(action, cell);
  46. currentCell = rootCell;
  47. return result;
  48. };
  49. return next;
  50. }
  51.  
  52. export function runFiber<Action, Return>(
  53. fiber: Fiber<Action, Return>,
  54. rootCell: Cell,
  55. action: Action
  56. ) {
  57. let currentCell = rootCell;
  58. function cell(callback: (state: any) => any, init: () => any) {
  59. if (!currentCell.initialized) {
  60. currentCell.initialized = true;
  61. currentCell.state = init();
  62. currentCell.next = Cell();
  63. }
  64. const newState = callback(currentCell.state);
  65. currentCell.state = newState;
  66. currentCell = currentCell.next;
  67. return newState;
  68. }
  69. const result = fiber(action, cell);
  70. return result;
  71. }
  72.  
  73. export function cloneCell(original: Cell | null): Cell {
  74. if (!original) {
  75. return (null as any) as Cell;
  76. }
  77. const cloned = Cell();
  78. cloned.initialized = original.initialized;
  79. cloned.state = original.state;
  80. cloned.next = cloneCell(original.next);
  81. return cloned;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement