Skip to content

Instantly share code, notes, and snippets.

@Kampfkarren
Created March 7, 2021 04:01
Show Gist options
  • Save Kampfkarren/4830de6375edb5fe1e3b5c96caac2a8e to your computer and use it in GitHub Desktop.
Save Kampfkarren/4830de6375edb5fe1e3b5c96caac2a8e to your computer and use it in GitHub Desktop.
local function curryWithNumberOfArgs(callback, numArgs)
local function curried(...)
local passedArgs = table.pack(...)
if passedArgs.n > numArgs then
error("too many arguments passed to curried function (called after already ran)")
elseif passedArgs.n == numArgs then
return callback(...)
end
return function(...)
local allArgs = { unpack(passedArgs) }
local newArgs = table.pack(...)
for index = 1, newArgs.n do
table.insert(allArgs, newArgs[index])
end
return curried(unpack(allArgs))
end
end
return curried
end
local function curryUnknownArgs(callback)
return function(...)
local passedArgs = table.pack(...)
return function(...)
local allArgs = { unpack(passedArgs) }
local newArgs = table.pack(...)
for index = 1, newArgs.n do
table.insert(allArgs, newArgs[index])
end
return callback(unpack(allArgs))
end
end
end
local function curry(callback, numArgs)
if numArgs == nil then
return curryUnknownArgs(callback)
else
return curryWithNumberOfArgs(callback, numArgs)
end
end
return curry
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local curry = require(ReplicatedStorage.Libraries.curry)
return function()
local function add(a, b, c)
return a + b + c
end
it("should properly curry when passed each argument individually", function()
expect(curry(add, 3)(1)(2)(3)).to.equal(6)
end)
it("should properly curry when passed argument in packs", function()
expect(curry(add, 3)(1)(2, 3)).to.equal(6)
end)
it("should assume the second call time is the last one if no number of arguments are given", function()
expect(curry(add)(1)(2, 3)).to.equal(6)
end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment