|
| 1 | +import java.util.*; |
| 2 | +import java.util.function.Consumer; |
| 3 | +import java.util.function.Function; |
| 4 | +import java.util.function.Supplier; |
| 5 | +import java.util.stream.Collectors; |
| 6 | + |
| 7 | +public class React { |
| 8 | + |
| 9 | + public static class Cell<T> { |
| 10 | + |
| 11 | + T value; |
| 12 | + |
| 13 | + public T getValue() { |
| 14 | + return value; |
| 15 | + } |
| 16 | + |
| 17 | + final Collection<ComputeCell<T>> dependentCells = new ArrayList<>(); |
| 18 | + } |
| 19 | + |
| 20 | + public static class InputCell<T> extends Cell<T> { |
| 21 | + |
| 22 | + InputCell(T initialValue) { |
| 23 | + this.value = initialValue; |
| 24 | + } |
| 25 | + |
| 26 | + public void setValue(T newValue) { |
| 27 | + this.value = newValue; |
| 28 | + dependentCells.forEach(cell -> cell.propagateUpdate()); |
| 29 | + dependentCells.forEach(cell -> cell.fireCallbacks()); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public static class ComputeCell<T> extends Cell<T> { |
| 34 | + |
| 35 | + private T lastFiredValue; |
| 36 | + |
| 37 | + private final Supplier<T> formula; |
| 38 | + |
| 39 | + final Collection<Consumer<T>> callbacks = new ArrayList<>(); |
| 40 | + |
| 41 | + ComputeCell(Supplier<T> formula) { |
| 42 | + this.formula = formula; |
| 43 | + this.value = formula.get(); |
| 44 | + this.lastFiredValue = value; |
| 45 | + } |
| 46 | + |
| 47 | + private void propagateUpdate() { |
| 48 | + value = formula.get(); |
| 49 | + dependentCells.forEach(cell -> cell.propagateUpdate()); |
| 50 | + } |
| 51 | + |
| 52 | + private void fireCallbacks() { |
| 53 | + if (!Objects.equals(value, lastFiredValue)) { |
| 54 | + callbacks.forEach(callback -> callback.accept(value)); |
| 55 | + dependentCells.forEach(cell -> cell.fireCallbacks()); |
| 56 | + lastFiredValue = value; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + public void addCallback(Consumer<T> callback) { |
| 61 | + callbacks.add(callback); |
| 62 | + } |
| 63 | + |
| 64 | + public void removeCallback(Consumer<T> callback) { |
| 65 | + callbacks.remove(callback); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public static <T> InputCell<T> inputCell(T initialValue) { |
| 70 | + return new InputCell<>(initialValue); |
| 71 | + } |
| 72 | + |
| 73 | + |
| 74 | + public static <T> ComputeCell<T> computeCell(Function<List<T>, T> function, List<Cell<T>> cells) { |
| 75 | + Supplier<T> formula = () -> { |
| 76 | + List<T> cellValues = cells.stream().map(Cell::getValue).collect(Collectors.toList()); |
| 77 | + return function.apply(cellValues); |
| 78 | + }; |
| 79 | + |
| 80 | + var computeCell = new ComputeCell<>(formula); |
| 81 | + cells.forEach(cell -> cell.dependentCells.add(computeCell)); |
| 82 | + return computeCell; |
| 83 | + } |
| 84 | +} |
0 commit comments