Spreadsheet #1
🦔 🦔 🦔
Let's make a spreadsheet. No looking at hints or cool algorithms. All bugs are intentional.
So, there's a very basic spreadsheet up above. In each cell, you can type a JavaScript expression and it will execute. You can refer to cells by the name that shows up when you hover your mouse cursor over a cell (A1
, B1
, A2
, B2
...).
So how do you make a spreadsheet, anyway?
I made a weird React hook that will give you:
- An object mapping cell IDs to formulas (just good old JS)
- An object mapping cell IDs to computed values
- A function to set a cell's value
That hook also has an effect that actually handles cell recalculation. When a formula changes:
- Make a cache that'll store computed outputs
- Convert all formulas to
AsyncFunction
s- Replace each cell reference with a retrieval of its cached result or queuing that cell reference's formula for execution and awaiting that execution's completion
- Execute all the
AsyncFunction
s and await for them to finish
Spreadsheets are directed graphs and this is just recursive depth-first graph traversal in disguise, I suppose. I honestly thought this part would be harder, but it actually was alright. I think there are better ways to do it than using JavaScript promises as a weird cache, though.
Some food for thought
- Can the computation/caching be done using React somehow, rather than JS?
- The whole spreadsheet gets redrawn on every change which is lame
- That makes sense given that there is one big blob of all the data that's created at the spreadsheet level rather than at the cell level
- Cycles produce
NaN
– would love to step through that with a debugger to figure out why- Cool that they don't just freeze up or whatever, though
- Do cells really have to just be cells?