Skip to content

Commit

Permalink
Add list length function
Browse files Browse the repository at this point in the history
  • Loading branch information
tekknolagi committed Nov 24, 2023
1 parent c55f1f7 commit 4e43d1b
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions scrapscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -1833,6 +1833,17 @@ def test_stdlib_serialize_expr(self) -> None:
Bytes(value=b"d4:leftd4:type3:Int5:valuei1ee2:op3:ADD5:rightd4:type3:Int5:valuei2ee4:type5:Binope"),
)

def test_stdlib_listlength_empty_list_returns_zero(self) -> None:
self.assertEqual(self._run("$$listlength []", STDLIB), Int(0))

def test_stdlib_listlength_returns_length(self) -> None:
self.assertEqual(self._run("$$listlength [1,2,3]", STDLIB), Int(3))

def test_stdlib_listlength_with_non_list_raises_type_error(self) -> None:
with self.assertRaises(TypeError) as ctx:
self._run("$$listlength 1", STDLIB)
self.assertEqual(ctx.exception.args[0], "listlength Expected List, but got Int")


class BencodeTests(unittest.TestCase):
def test_bencode_int(self) -> None:
Expand Down Expand Up @@ -2006,11 +2017,18 @@ def jsondecode(obj: Object) -> Object:
return make_object(data)


def listlength(obj: Object) -> Object:
if not isinstance(obj, List):
raise TypeError(f"listlength Expected List, but got {type(obj).__name__}")
return Int(len(obj.items))


STDLIB = {
"$$add": NativeFunction(lambda x: NativeFunction(lambda y: Int(unpack_int(x) + unpack_int(y)))),
"$$fetch": NativeFunction(fetch),
"$$jsondecode": NativeFunction(jsondecode),
"$$serialize": NativeFunction(lambda obj: Bytes(serialize(obj))),
"$$listlength": NativeFunction(listlength),
}


Expand Down

0 comments on commit 4e43d1b

Please sign in to comment.