Skip to content

Commit

Permalink
Refactor decorators
Browse files Browse the repository at this point in the history
Because the CryptMachine removes non-alphabet characters,
we can delete the functionality in all decorators
  • Loading branch information
tigertv committed Jul 5, 2021
1 parent e527c43 commit 5fca340
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 19 deletions.
4 changes: 2 additions & 2 deletions secretpy/cmdecorators/lowercase.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
class LowerCase(AbstractMachineDecorator):

def encrypt(self, text):
return self._machine.encrypt(text.lower())
return self._machine.encrypt(text).lower()

def decrypt(self, text):
return self._machine.decrypt(text.lower())
return self._machine.decrypt(text).lower()
19 changes: 8 additions & 11 deletions secretpy/cmdecorators/save_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,18 @@ def decrypt(self, text):

def __crypt(self, text, func):
# make lower case and save indexes
upcases = [i for i, char in enumerate(text) if char.isupper()]
txt = list(text)
for i in upcases:
txt[i] = txt[i].lower()
upcases = [i for i, c in enumerate(text) if c.isupper()]
txt = text.lower()

# remove non-alphabet characters and save indexes
# prepare alphabet
alphabet = self._machine.get_alphabet()
coords = {c: i for i, letters in enumerate(alphabet) for c in letters}
chars = [i for i, char in enumerate(txt) if char not in coords]
for i in reversed(chars):
del txt[i]
alpha = {c: 1 for letters in alphabet for c in letters}

# save indexes of non-alphabet characters
chars = [i for i, c in enumerate(txt) if c not in alpha]

# execute function
res = func("".join(txt))
res = list(res)
res = list(func(txt))

# restore non-alphabet characters
for i in chars:
Expand Down
6 changes: 2 additions & 4 deletions secretpy/cmdecorators/uppercase.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
class UpperCase(AbstractMachineDecorator):

def encrypt(self, text):
res = self._machine.encrypt(text.lower())
return res.upper()
return self._machine.encrypt(text).upper()

def decrypt(self, text):
res = self._machine.decrypt(text.lower())
return res.upper()
return self._machine.decrypt(text).upper()
4 changes: 2 additions & 2 deletions secretpy/cryptmachine.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ def __crypt(self, text, func):
# prepare alphabet
alpha = {c: 1 for letters in self.__alphabet for c in letters}
# filter text by alphabet
text = "".join(filter(lambda c: c in alpha, text.lower()))
return func(text, self.__key, self.__alphabet)
txt = "".join(filter(lambda c: c in alpha, text.lower()))
return func(txt, self.__key, self.__alphabet)

0 comments on commit 5fca340

Please sign in to comment.