Exemple #1
0
def next_token(current=None):
    """Generates the next token based on a current token

    : param current: the previous token to the one that needs to be generated
    """
    if not current:
        return ALPHABET[0] * START_URL_TOKEN_LENGTH
    else:

        # Check the length
        if len(current) < START_URL_TOKEN_LENGTH:
            raise LinkShortenerLengthError()

        result = list(current)
        #Check every char from left to right
        for index in range(len(current) - 1, -1, -1):

            char = current[index]

            # Reset this token to
            if char == ALPHABET[len(ALPHABET) - 1]:
                result[index] = ALPHABET[0]
            # Take the next character
            else:
                result[index] = ALPHABET[ALPHABET.index(char) + 1]
                break

        # Join all the chars to get the final result
        result = "".join(result)

        # Maximun of combinations reached? add one more!
        # We know because the number is reseted to the start number
        if result == len(current) * ALPHABET[0]:
            result = ALPHABET[1] + result

        return result
Exemple #2
0
def token_to_counter(token):
    """Translates an alphabet token to a decimal numeric number

    :param token: The token string
    """

    if not isinstance(token, str):
        token = str(token)

    #Remove left 0's
    token = token.lstrip("0")

    #split each character and reverse
    token = list(token)
    token.reverse()

    result = 0

    #Translate
    #(Xn * (length ^ n)) + (Xn-1 * (length ^ n-1)) ... (X0 * (length ^ 0))
    for it, char in enumerate(token):
        result += ALPHABET.index(char) * (len(ALPHABET) ** it)

    return result