Skip to content

Commit

Permalink
fix: preserve data immutability and improve count interpolation
Browse files Browse the repository at this point in the history
- Create new data table for default count value
- Move count default handling to treatNode
- Update tests to verify count interpolation
- Maintain immutability of input data table

Cherry-picked from kikito/i18n.lua#35
  • Loading branch information
flexiondotorg committed Jan 12, 2025
1 parent 8af64cc commit 16c57c3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
15 changes: 13 additions & 2 deletions i18n/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ local function pluralize(t, locale, data)
return t[plural_form]
end

local function treatNode(node, data)
local function treatNode(node, loc, data)
if isArray(node) then
local iter = {ipairs(node)}
node = {}
Expand All @@ -107,7 +107,18 @@ local function treatNode(node, data)
elseif type(node) == 'string' then
return interpolate(node, data)
elseif isPluralTable(node) then
return interpolate(pluralize(node, loc, data), data)
-- Make sure that count has a default of 1
local newdata
if data.count == nil then
newdata = {}
for key, value in pairs(data) do
newdata[key] = value
end
newdata.count = 1
else
newdata = data
end
return interpolate(pluralize(node, loc, newdata), newdata)
end
return node
end
Expand Down
11 changes: 6 additions & 5 deletions spec/i18n_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -95,20 +95,21 @@ describe('i18n', function()
before_each(function()
i18n.setLocale('fr')
i18n.set('fr.message', {
one = "Une chose.",
one = "%{count} chose.",
other = "%{count} choses."
})
end)

it('Ça marche', function()
assert.equal("Une chose.", i18n('message', {count = 1}))
assert.equal("Une chose.", i18n('message', {count = 1.5}))
assert.equal("1 chose.", i18n('message', {count = 1}))
-- Note: should actually be '1,5 chose.'
assert.equal("1.5 chose.", i18n('message', {count = 1.5}))
assert.equal("2 choses.", i18n('message', {count = 2}))
assert.equal("Une chose.", i18n('message', {count = 0}))
assert.equal("0 chose.", i18n('message', {count = 0}))
end)

it('defaults to 1', function()
assert.equal("Une chose.", i18n('message'))
assert.equal("1 chose.", i18n('message'))
end)
end)

Expand Down

0 comments on commit 16c57c3

Please # to comment.