Lua IteratorWrapper

Date: 2024-08-16
local yield = coroutine.yield;

-- Helper functie om een nieuwe IteratorWrapper te maken
local function createWrapper(iter, generator)
    return setmetatable({
        iter = coroutine.wrap(function()
            for value in iter do
                generator(value)
            end
        end)
    }, IteratorWrapper)
end

-- Defineer de IteratorWrapper class
IteratorWrapper = {}
IteratorWrapper.__index = IteratorWrapper

function IteratorWrapper.new(iterable)
    local self = setmetatable({}, IteratorWrapper)
    self.iter = coroutine.wrap(function()
        for _, v in ipairs(iterable) do
            yield(v)
        end
    end)
    return self
end

function IteratorWrapper:map(f)
    return createWrapper(self.iter, function(value)
        yield(f(value))
    end)
end

function IteratorWrapper:filter(predicate)
    return createWrapper(self.iter, function(value)
        if predicate(value) then
            yield(value)
        end
    end)
end

function IteratorWrapper:take(n)
    local count = 0
    return createWrapper(self.iter, function(value)
        if count < n then
            yield(value)
            count = count + 1
        end
    end)
end

function IteratorWrapper:first()
    return self.iter() -- Haalt direct het eerste item uit de iterator
end

function IteratorWrapper:toArray()
    local result = {}
    for x in self.iter do
        table.insert(result, x)
    end
    return result
end

-- Functie om van een lijst een IteratorWrapper te maken
function from(iterable)
    return IteratorWrapper.new(iterable)
end

local numbers = { 1, 2, 3, 4, 5 }
local firstResult = from(numbers)
    :map(function(x) return x * 2 end)
    :filter(function(x) return x > 5 end)
    :first()

print(firstResult) -- Output: 6

local result = from(numbers)
    :map(function(x) return x * 2 end)
    :filter(function(x) return x > 5 end)
    :take(2)
    :toArray()

for _, v in ipairs(result) do
    print(v) -- Output: 6, 8
end

88650cookie-checkLua IteratorWrapper