Created
March 7, 2021 04:01
-
-
Save Kampfkarren/4830de6375edb5fe1e3b5c96caac2a8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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