Skip to content

Instantly share code, notes, and snippets.

@vorce
Created Aug 18, 2019
Embed
What would you like to do?
Some functional utilities
-- functional programming utilities
-- usage: local fn = require "fn"
NAME = "fn"
local M = { }
-- Invokes the reducer function for each element in the collection with the accumulator.
-- The initial value of the accumulator is initial. The function is invoked for each
-- element in the enumerable with the accumulator. The result returned by the
-- function is used as the accumulator for the next iteration. The function
-- returns the last accumulator.
-- This function is a building block for a lot of other utilities.
local function reduce(collection, initial, reducer)
local accumulator = initial
for k, v in pairs(collection) do
accumulator = reducer({key = k, value = v}, accumulator)
end
return accumulator
end
-- returns the collection with its items transformed by the mapper function
-- mapper example:
-- local doubleUp = function (kv)
-- return kv.value * 2
-- end
local function map(collection, mapper)
return reduce(collection, {}, function (kv, acc)
table.insert(acc, mapper(kv))
return acc
end)
end
-- return a collection containing only items where the predicate function returns true
-- predicate example:
-- local isEven = function (kv)
-- return (k.value % 2) == 0
-- end
local function filter(collection, predicate)
return reduce(collection, {}, function (kv, acc)
if predicate(kv) then
table.insert(acc, kv.value)
end
return acc
end)
end
-- opposite of filter
local function reject(collection, predicate)
return reduce(collection, {}, function (kv, acc)
if not predicate(kv) then
table.insert(acc, kv.value)
end
return acc
end)
end
M.reduce = reduce
M.map = map
M.filter = filter
M.reject = reject
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment