Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions babel/plural.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,9 @@ def to_javascript(rule: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRu
function. This function depends on no external library:

>>> to_javascript({'one': 'n is 1'})
"(function(n) { return (n == 1) ? 'one' : 'other'; })"
"(function(n) { n = Math.abs(n); return (n == 1) ? 'one' : 'other'; })"

Negative numbers use their absolute value, as in :class:`PluralRule`.

Implementation detail: The function generated will probably evaluate
expressions involved into range operations multiple times. This has the
Expand All @@ -191,7 +193,7 @@ def to_javascript(rule: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRu
:raise RuleError: if the expression is malformed
"""
to_js = _JavaScriptCompiler().compile
result = ['(function(n) { return ']
result = ['(function(n) { n = Math.abs(n); return ']
for tag, ast in PluralRule.parse(rule).abstract:
result.append(f"{to_js(ast)} ? {tag!r} : ")
result.append('%r; })' % _fallback_tag)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_plural.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def test_plural_other_is_ignored():

def test_to_javascript():
src = plural.to_javascript({'one': 'n is 1'})
assert src == "(function(n) { return (n == 1) ? 'one' : 'other'; })"
assert src == "(function(n) { n = Math.abs(n); return (n == 1) ? 'one' : 'other'; })"


def test_to_python():
Expand Down Expand Up @@ -114,7 +114,7 @@ def test_plural_within_rules():
p = plural.PluralRule({'one': 'n is 1', 'few': 'n within 2,4,7..9'})
assert repr(p) == "<PluralRule 'one: n is 1, few: n within 2,4,7..9'>"
assert plural.to_javascript(p) == (
"(function(n) { "
"(function(n) { n = Math.abs(n); "
"return ((n == 2) || (n == 4) || (n >= 7 && n <= 9))"
" ? 'few' : (n == 1) ? 'one' : 'other'; })"
)
Expand Down