Skip to content

Commit

Permalink
add enumerate() & support __pairs
Browse files Browse the repository at this point in the history
  • Loading branch information
starwing committed Jan 26, 2021
1 parent 8c6556f commit 0aba030
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -138,6 +138,7 @@ Slicing:
- `slice(first, last, iter)`

Transforms:
- `enumerate(iter)`
- `map(func, iter)`
- `flatmap(func, iter)`
- `scan(func, init, iter)`
Expand Down
31 changes: 28 additions & 3 deletions iter.lua
Expand Up @@ -146,6 +146,8 @@ local function newiter(v, state, init)
elseif t == "nil" then
return new_stateless(nil_iter)
end
local mt = getmetatable(v)
if mt and mt.__pairs then return new_stateful(pairs(v)) end
error(format('attempt to iterate a %s value', t))
end

Expand Down Expand Up @@ -391,6 +393,28 @@ end, "split", "span", "splitAt", "split_at")

-- transforms

local function enum_reset(self, other)
Iter.reset(self, other)
self.idx = other and other.idx or 0
return self
end

local function enum_collect(self, key, ...)
if not key then return end
self.idx = self.idx + 1
return self.idx, key, ...
end

local function enum_next(self)
return enum_collect(self, self[1]())
end

local function enumerate(base)
local self = new_stateful(enum_reset, enum_next)
self[1] = base
return self
end

local function map_collect(func, key, ...)
if key ~= nil then return func(key, ...) end
end
Expand Down Expand Up @@ -551,9 +575,10 @@ local function groupby(func, base)
return self
end

export1(map, "map")
export1(flatmap, "flatmap", "flat_map", "flatMap")
export2(scan, "scan", "accumulate", "reductions")
export0(enumerate, "enumerate")
export1(map, "map")
export1(flatmap, "flatmap", "flat_map", "flatMap")
export2(scan, "scan", "accumulate", "reductions")
export1(group, "group")
export1(groupby, "groupby", "group_by", "groupBy")
export1(function(func, base)
Expand Down

0 comments on commit 0aba030

Please sign in to comment.