Skip to content

Commit

Permalink
Merge pull request #46 from datacamp/feat/add-messaging-utils
Browse files Browse the repository at this point in the history
Add counting helpers
  • Loading branch information
hermansje authored Sep 9, 2019
2 parents 4511e4c + e58f16e commit 4ad0320
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 24 deletions.
26 changes: 2 additions & 24 deletions protowhat/selectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import inspect
import importlib

from protowhat.utils_messaging import get_ord


class Selector(NodeVisitor):
def __init__(self, target_cls, target_cls_name=None, strict=True, priority=None):
Expand Down Expand Up @@ -162,27 +164,3 @@ def from_module(cls, mod):
}
dispatcher = cls(mod.AstNode, nodes=ast_nodes, ast_mod=mod)
return dispatcher


def get_ord(num):
assert num > 0, "use strictly positive numbers in get_ord()"
nums = {
1: "first",
2: "second",
3: "third",
4: "fourth",
5: "fifth",
6: "sixth",
7: "seventh",
8: "eight",
9: "ninth",
10: "tenth",
}
if num in nums:
return nums[num]
else:
return (
{1: "{}st", 2: "{}nd", 3: "{}rd"}.get(
num if (num < 20) else (num % 10), "{}th"
)
).format(num)
48 changes: 48 additions & 0 deletions protowhat/utils_messaging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
def get_ord(num):
assert num > 0, "use strictly positive numbers in get_ord()"
nums = {
1: "first",
2: "second",
3: "third",
4: "fourth",
5: "fifth",
6: "sixth",
7: "seventh",
8: "eight",
9: "ninth",
10: "tenth",
}
if num in nums:
return nums[num]
else:
return (
{1: "{}st", 2: "{}nd", 3: "{}rd"}.get(
num if (num < 20) else (num % 10), "{}th"
)
).format(num)


def get_times(num):
nums = {1: "once", 2: "twice"}
if num in nums:
return nums[num]
else:
return "%s times" % get_num(num)


def get_num(num):
nums = {
0: "no",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
}
if num in nums:
return nums[num]
else:
return str(num)
24 changes: 24 additions & 0 deletions tests/test_utils_messaging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import pytest

from protowhat.utils_messaging import get_ord, get_times, get_num


@pytest.mark.parametrize(
"input, output", [(1, "first"), (2, "second"), (3, "third"), (11, "11th")]
)
def test_get_ord(input, output):
assert get_ord(input) == output


@pytest.mark.parametrize(
"input, output", [(1, "one"), (2, "two"), (3, "three"), (11, "11")]
)
def test_get_num(input, output):
assert get_num(input) == output


@pytest.mark.parametrize(
"input, output", [(1, "once"), (2, "twice"), (3, "three times"), (11, "11 times")]
)
def test_get_times(input, output):
assert get_times(input) == output

0 comments on commit 4ad0320

Please sign in to comment.