Skip to content

Instantly share code, notes, and snippets.

@htsign
Created November 27, 2019 01:25
Show Gist options
  • Save htsign/d7cd6a70032e9e754f1c9cac2ad4b0ce to your computer and use it in GitHub Desktop.
Save htsign/d7cd6a70032e9e754f1c9cac2ad4b0ce to your computer and use it in GitHub Desktop.
iterator chunked*[T](xs: openArray[T], size: int, yieldRest = true): seq[T] =
var
i: int
let
last = xs.high
for j in countup(0, xs.len, size + 1):
i = j
if i + size > last: break
yield xs[i .. i + size]
if yieldRest:
yield xs[i .. ^1]
iterator windowed*[T](xs: openArray[T], size: int): seq[T] =
for i in 0 .. xs.len - size:
yield xs[i ..< i + size]
iterator pairwise*[T](xs: openArray[T]): (T, T) =
for x in xs.windowed(2):
yield (x[0], x[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment