- commit
- 765d892fd140057f8a5d4a7d9cfa6901d1ac9d44
- parent
- 8cd2d6d7aaf3a681207f79808d8770f9b10f4edf
- Author
- Tobias Bengfort <tobias.bengfort@posteo.de>
- Date
- 2024-09-07 07:17
refactor: decleartive functions
Diffstat
| M | sheet/sheet.py | 27 | ++++++++++++++------------- |
1 files changed, 14 insertions, 13 deletions
diff --git a/sheet/sheet.py b/sheet/sheet.py
@@ -1,3 +1,4 @@ -1 1 import math 1 2 2 3 from .expression import ParseError 3 4 from .expression import parse @@ -21,6 +22,13 @@ class Bar: 21 22 return a * BLOCKS[-1] + BLOCKS[b] + (width - a - 1) * BLOCKS[0] 22 23 23 24 -1 25 FUNCTIONS = { -1 26 'sum': (sum, 'range'), -1 27 'power': (math.pow, 2), -1 28 'bar': (Bar, 1), -1 29 } -1 30 -1 31 24 32 def iter_range(cell1, cell2): 25 33 x1, y1 = cell1 26 34 x2, y2 = cell2 @@ -73,26 +81,19 @@ class Sheet: 73 81 def call_function( 74 82 self, name: str, args: list[tuple], _commas: list[str] 75 83 ) -> float|int|str|Bar:76 -1 if name.lower() == 'sum':-1 84 fn, nargs = FUNCTIONS[name.lower()] -1 85 if nargs == 'range': 77 86 if len(args) != 1 or args[0][0] != 'range': 78 87 raise ValueError(args) 79 88 _, ref1, ref2 = args[0]80 -1 return sum(-1 89 return fn( 81 90 to_number(self.get_value(ref)) 82 91 for ref in iter_range(ref1[1], ref2[1]) 83 92 )84 -1 elif name.lower() == 'power':85 -1 if len(args) != 2:86 -1 raise ValueError(args)87 -1 base = to_number(self.evaluate(args[0]))88 -1 exp = to_number(self.evaluate(args[1]))89 -1 return base ** exp90 -1 elif name.lower() == 'bar':91 -1 if len(args) != 1:92 -1 raise ValueError(args)93 -1 return Bar(to_number(self.evaluate(args[0])))94 93 else:95 -1 raise NameError(name)-1 94 if len(args) != nargs: -1 95 raise ValueError(args) -1 96 return fn(*[to_number(self.evaluate(a)) for a in args]) 96 97 97 98 def evaluate(self, expr: tuple) -> float|int|str|Bar: 98 99 if expr[0] in ['int', 'float', 'str']: