Changed funcs to treat tables as arrays by default

Changed the lume.set(), lume.merge() and lume.filter() functions to take
the argument `retainkeys` instead of `isarray`, and to treat the table
as an array by default (avoiding sparse arrays) instead of treating the
table as an associative array by default (retaining keys).
This commit is contained in:
rxi 2014-02-27 22:39:09 +00:00
parent eeadcd307d
commit 34b2013c71
2 changed files with 17 additions and 19 deletions

View File

@ -88,27 +88,27 @@ argument is not supplied the accumulator is initialised to `0`.
lume.reduce({1, 2, 3}, function(a, b) return a + b end) -- Returns 6
```
### lume.set(t, [, isarray])
### lume.set(t, [, retainkeys])
Returns a copy of the `t` table with all the duplicate values removed. If
`isarray` is true the table is treated as an array.
`retainkeys` is true the table is not treated as an array and retains its
original keys.
```lua
lume.set({2, 1, 2, "cat", "cat"}) -- Returns {1, 2, cat}
```
### lume.filter(t, fn [, isarray])
Iterates the table `t` and calls `fn` on each value. Returns a new table with
only the value which `fn` returned true. If `isarray` is true the table is
treated as an array, `isarray` is false by default.
### lume.filter(t, fn [, retainkeys])
Calls `fn` on each value of `t` table. Returns a new table with only the values
where `fn` returned true. If `retainkeys` is true the table is not treated as
an array and retains its original keys.
```lua
lume.filter({1, 2, 3, 4}, function(x) return x % 2 == 0 end, true)
-- Returns {2, 4}
```
### lume.merge(t, t2 [, isarray])
Merges all the values from the table `t2` into `t` in place. If `isarray` is
true the tables are treated as arrays, `isarray` is false by default. If
`isarray` is false and `t` and `t2` have a conflicting key, the value from `t2`
is used.
### lume.merge(t, t2 [, retainkeys])
Merges all the values from the table `t2` into `t` in place. If `retainkeys` is
true the table is not treated as an array and retains its original keys; if `t`
and `t2` have a conflicting key, the value from `t2` is used.
```lua
lume.merge({2, 3}, {4, 5}, true) -- Returns {2, 3, 4, 5}
```

View File

@ -110,29 +110,27 @@ function lume.reduce(t, fn, first)
end
function lume.set(t, isarray)
function lume.set(t, retainkeys)
local tmp = {}
for k, v in pairs(t) do tmp[v] = k end
local rtn = {}
for k, v in pairs(tmp) do
rtn[isarray and (#rtn + 1) or v] = k
end
for k, v in pairs(tmp) do rtn[retainkeys and v or (#rtn + 1)] = k end
return rtn
end
function lume.filter(t, fn, isarray)
function lume.filter(t, fn, retainkeys)
local rtn = {}
for k, v in pairs(t) do
if fn(v) then rtn[isarray and (#rtn + 1) or k] = v end
if fn(v) then rtn[retainkeys and k or (#rtn + 1)] = v end
end
return rtn
end
function lume.merge(t, t2, isarray)
function lume.merge(t, t2, retainkeys)
for k, v in pairs(t2) do
t[isarray and (#t + 1) or k] = v
t[retainkeys and k or (#t + 1)] = v
end
return t
end