Skip to content

Commit

Permalink
std/stream: Add zip. (#188)
Browse files Browse the repository at this point in the history
  • Loading branch information
DeedleFake committed Jun 27, 2019
1 parent 495aa7f commit f0eaaa4
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
56 changes: 55 additions & 1 deletion std/stream/middle.go
@@ -1,6 +1,9 @@
package stream

import "github.com/DeedleFake/wdte"
import (
"github.com/DeedleFake/wdte"
"github.com/DeedleFake/wdte/wdteutil"
)

// Map is a WDTE function with the following signature:
//
Expand Down Expand Up @@ -246,3 +249,54 @@ func Limit(frame wdte.Frame, args ...wdte.Func) wdte.Func {
})
})
}

// Zip is a WDTE function with the following signatures:
//
// (zip s1) ...
// zip ...
//
// Zip returns a Stream which yields the streams that it is given
// simultaneuously as arrays. In other words,
//
// zip (a.stream [1; 2; 3]) (a.stream ['a'; 'b'; 'c'])
//
// will yield
//
// [1; 'a']
// [2; 'b']
// [3; 'c']
//
// The order of the yielded arrays matches the order that the streams
// are given in. If one of the streams ends before the other ones, End
// will be yielded for that stream after that point.
func Zip(frame wdte.Frame, args ...wdte.Func) wdte.Func {
frame = frame.Sub("zip")

if len(args) < 2 {
return wdteutil.SaveArgs(wdte.GoFunc(Zip), args...)
}

streams := make([]Stream, 0, len(args))
for _, arg := range args {
streams = append(streams, arg.Call(frame).(Stream))
}

return NextFunc(func(frame wdte.Frame) (wdte.Func, bool) {
frame = frame.Sub("zip")

r := make(wdte.Array, 0, len(streams))
var more bool
for _, stream := range streams {
n, ok := stream.Next(frame)
if !ok {
r = append(r, end{})
continue
}

r = append(r, n)
more = true
}

return r, more
})
}
1 change: 1 addition & 0 deletions std/stream/stream.go
Expand Up @@ -49,6 +49,7 @@ var Scope = wdte.S().Map(map[wdte.ID]wdte.Func{
"enumerate": wdte.GoFunc(Enumerate),
"repeat": wdte.GoFunc(Repeat),
"limit": wdte.GoFunc(Limit),
"zip": wdte.GoFunc(Zip),

"end": End(),
"collect": wdte.GoFunc(Collect),
Expand Down
9 changes: 9 additions & 0 deletions wdte_test.go
Expand Up @@ -16,6 +16,7 @@ import (
wdteio "github.com/DeedleFake/wdte/std/io"
_ "github.com/DeedleFake/wdte/std/math"
_ "github.com/DeedleFake/wdte/std/rand"
"github.com/DeedleFake/wdte/std/stream"
_ "github.com/DeedleFake/wdte/std/stream"
_ "github.com/DeedleFake/wdte/std/strings"
)
Expand Down Expand Up @@ -567,6 +568,14 @@ func TestStream(t *testing.T) {
wdte.Number(0), wdte.Number(1), wdte.Number(2),
},
},
{
name: "Zip",
script: `let s => import 'stream'; s.zip (s.range 2) (s.range 1 2) -> s.collect;`,
ret: wdte.Array{
wdte.Array{wdte.Number(0), wdte.Number(1)},
wdte.Array{wdte.Number(1), stream.End()},
},
},
{
name: "Drain",
script: `
Expand Down

0 comments on commit f0eaaa4

Please sign in to comment.