Commit d4d0c1a1 authored by Jonas Schäfer's avatar Jonas Schäfer

Add function to calculate unique prefix of two strings

parent 1b974d2d
......@@ -17,6 +17,7 @@ import subprocess
import time
import string
import logging
import itertools
from slixmpp import JID, InvalidJID, Message
from poezio.poezio_shlex import shlex
......@@ -468,3 +469,22 @@ def safeJID(*args, **kwargs) -> JID:
exc_info=True,
)
return JID('')
def unique_prefix_of(a: str, b: str) -> str:
"""
Return the unique prefix of `a` with `b`.
Corner cases:
* If `a` and `b` share no prefix, the first letter of `a` is returned.
* If `a` and `b` are equal, `a` is returned.
* If `a` is a prefix of `b`, `a` is returned.
* If `b` is a prefix of `a`, `b` plus the first letter of `a` after the
common prefix is returned.
"""
for i, (ca, cb) in enumerate(itertools.zip_longest(a, b)):
if ca != cb:
return a[:i+1]
# both are equal, return a
return a
......@@ -11,7 +11,7 @@ from poezio.common import (_datetime_tuple as datetime_tuple, get_utc_time,
get_local_time, shell_split, _find_argument_quoted
as find_argument_quoted, _find_argument_unquoted as
find_argument_unquoted, parse_str_to_secs,
parse_secs_to_str, safeJID)
parse_secs_to_str, safeJID, unique_prefix_of)
def test_utc_time():
delta = timedelta(seconds=-3600)
......@@ -63,3 +63,22 @@ def test_parse_secs_to_str():
def test_safeJID():
assert safeJID('toto@titi/tata') == JID('toto@titi/tata')
assert safeJID('toto@…') == JID('')
def test_unique_prefix_of__no_shared_prefix():
assert unique_prefix_of("a", "b") == "a"
assert unique_prefix_of("foo", "bar") == "f"
assert unique_prefix_of("foo", "") == "f"
def test_unique_prefix_of__equal():
assert unique_prefix_of("foo", "foo") == "foo"
def test_unique_prefix_of__a_prefix():
assert unique_prefix_of("foo", "foobar") == "foo"
def test_unique_prefix_of__b_prefix():
assert unique_prefix_of("foobar", "foo") == "foob"
def test_unique_prefix_of__normal_shared_prefix():
assert unique_prefix_of("foobar", "foobaz") == "foobar"
assert unique_prefix_of("fnord", "funky") == "fn"
assert unique_prefix_of("asbestos", "aspergers") == "asb"
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment