Added overloaded support for array * int
Some checks failed
Build / build (push) Successful in 10m20s
Test / build (push) Has been cancelled

This commit is contained in:
Chuck Smith
2024-03-24 11:47:31 -04:00
parent 803d717379
commit c9d96236dd
4 changed files with 68 additions and 0 deletions

View File

@@ -527,6 +527,25 @@ func (vm *VM) executeBinaryOperation(op code.Opcode) error {
switch {
// [1] * 3
case left.Type() == object.ARRAY_OBJ && right.Type() == object.INTEGER_OBJ:
leftVal := left.(*object.Array).Elements
rightVal := int(right.(*object.Integer).Value)
elements := leftVal
for i := rightVal; i > 1; i-- {
elements = append(elements, leftVal...)
}
return vm.push(&object.Array{Elements: elements})
// 3 * [1]
case left.Type() == object.INTEGER_OBJ && right.Type() == object.ARRAY_OBJ:
leftVal := int(left.(*object.Integer).Value)
rightVal := right.(*object.Array).Elements
elements := rightVal
for i := leftVal; i > 1; i-- {
elements = append(elements, rightVal...)
}
return vm.push(&object.Array{Elements: elements})
// " " * 4
case left.Type() == object.STRING_OBJ && right.Type() == object.INTEGER_OBJ:
leftVal := left.(*object.String).Value

View File

@@ -343,6 +343,17 @@ func TestArrayLiterals(t *testing.T) {
runVmTests(t, tests)
}
func TestArrayDuplication(t *testing.T) {
tests := []vmTestCase{
{"[1] * 3", []int{1, 1, 1}},
{"3 * [1]", []int{1, 1, 1}},
{"[1, 2] * 2", []int{1, 2, 1, 2}},
{"2 * [1, 2]", []int{1, 2, 1, 2}},
}
runVmTests(t, tests)
}
func TestHashLiterals(t *testing.T) {
tests := []vmTestCase{
{