Skip to content

Commit

Permalink
Merge 81e6c48 into b9431fe
Browse files Browse the repository at this point in the history
  • Loading branch information
odino committed Sep 21, 2020
2 parents b9431fe + 81e6c48 commit efb989f
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
9 changes: 9 additions & 0 deletions docs/types/array.md
Expand Up @@ -350,6 +350,15 @@ a.shift() # 1
a # [2, 3]
```
### shuffle()
Shuffles elements in the array:
``` py
a = [1, 2, 3, 4]
a.shuffle() # [3, 1, 2, 4]
```
### some(f)
Returns true when at least one of the elements in the array
Expand Down
10 changes: 10 additions & 0 deletions evaluator/builtin_functions_test.go
Expand Up @@ -385,6 +385,16 @@ func TestReverse(t *testing.T) {
testBuiltinFunction(tests, t)
}

func TestShuffle(t *testing.T) {
tests := []Tests{
{`(1..1000).shuffle().str() != (1..1000).str();`, true},
{`(1..1000).shuffle().len() == (1..1000).len();`, true},
{`(1..1000).shuffle().sort().str() == (1..1000).str();`, true},
}

testBuiltinFunction(tests, t)
}

func TestPush(t *testing.T) {
tests := []Tests{
{`[1, 2].push("a");`, []interface{}{1, 2, "a"}},
Expand Down
22 changes: 22 additions & 0 deletions evaluator/functions.go
Expand Up @@ -9,6 +9,7 @@ import (
"io/ioutil"
"math"
"math/big"
mrand "math/rand"
"os"
"os/exec"
"os/user"
Expand Down Expand Up @@ -367,6 +368,11 @@ func getFns() map[string]*object.Builtin {
Types: []string{object.ARRAY_OBJ, object.STRING_OBJ},
Fn: reverseFn,
},
// shuffle([1,2,3])
"shuffle": &object.Builtin{
Types: []string{object.ARRAY_OBJ},
Fn: shuffleFn,
},
// push([1,2,3], 4)
"push": &object.Builtin{
Types: []string{object.ARRAY_OBJ},
Expand Down Expand Up @@ -1948,6 +1954,22 @@ func reverseFn(tok token.Token, env *object.Environment, args ...object.Object)
}
}

// shuffle([1,2,3])
func shuffleFn(tok token.Token, env *object.Environment, args ...object.Object) object.Object {
err := validateArgs(tok, "shuffle", args, 1, [][]string{{object.ARRAY_OBJ}})

if err != nil {
return err
}

array := args[0].(*object.Array)

mrand.Seed(time.Now().UnixNano())
mrand.Shuffle(len(array.Elements), func(i, j int) { array.Elements[i], array.Elements[j] = array.Elements[j], array.Elements[i] })

return array
}

// push([1,2,3], 4)
func pushFn(tok token.Token, env *object.Environment, args ...object.Object) object.Object {
err := validateArgs(tok, "push", args, 2, [][]string{{object.ARRAY_OBJ}, {object.NULL_OBJ,
Expand Down

0 comments on commit efb989f

Please sign in to comment.