Skip to content
This repository has been archived by the owner on Nov 20, 2024. It is now read-only.

Commit

Permalink
Implement Array.partition (closes #18)
Browse files Browse the repository at this point in the history
  • Loading branch information
cxmeel committed Mar 15, 2024
1 parent 90fa4c9 commit 2f376ce
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Array/init.luau
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ local array = {
is = require("./is"),
last = require("./last"),
map = require("./map"),
partition = require("./partition"),
pop = require("./pop"),
push = require("./push"),
reduce = require("./reduce"),
Expand Down
33 changes: 33 additions & 0 deletions src/Array/partition.luau
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
--[=[
@within Array
Filters an array into two arrays based on a filter function. The first array contains all elements that pass the filter, and the second array contains all elements that fail the filter.
```lua
local even, odd = partition({ 1, 2, 3, 4, 5 }, function(value)
return value % 2 == 0
end)
-- even: { 2, 4 }
-- odd: { 1, 3, 5 }
```
]=]
local function partition<T>(
array: { T },
filterer: (value: T, index: number) -> boolean
): ({ T }, { T })
local pass = {}
local fail = {}

for index, value in array do
if filterer(value, index) then
table.insert(pass, value)
else
table.insert(fail, value)
end
end

return pass, fail
end

return partition

0 comments on commit 2f376ce

Please sign in to comment.