Walid Bousseta
Walid Bousseta

Reputation: 1469

JavaScript TextEncoder / TextDecoder equivalent in python

I wanted to get the same results we got by using TextEncoder and TextDecoder on javascript but couldn't find real code solution the soluction I found doesn't give me the real same results.

exp:

const textencoder = new TextEncoder();
console.log(textencoder.encode('$'));
//[36]

const textdecoder = TextDecoder();
console.log(textdecoder.decode(new Uint8Array([36]));
// $

Upvotes: 2

Views: 539

Answers (1)

Walid Bousseta
Walid Bousseta

Reputation: 1469

after a many tries and search, I got the solution form a friend and I decided to share it with you, may someone need it some day;

class TextEncoder():
    def __init__(self):
        pass
    
    def encode(self, text):
        """
        exp:
            >>> textencoder = TextEncoder()
            >>> textencoder.encode('$')
            >>> [36]
        """
        if isinstance(text, str):
            encoded_text = text.encode('utf-8')
            byte_array = bytearray(encoded_text)
            return list(byte_array)
        else:
            raise TypeError(f'Expecting a str but got {type(text)}')

class TextDecoder():
    def __init__(self):
        pass
    
    def decode(self, array):
        """
        exp:
            >>> textdecoder = TextDecoder()
            >>> textdecoder.decode([36])
            >>> $
        """
        if isinstance(array, list):
            return bytearray(array).decode('utf-8')
        elif isinstance(array, bytearray):
            return array.decode('utf-8')
        else:
            raise TypeError(f'expecting a list or bytearray got: {type(array)}')

Upvotes: 2

Related Questions