TIL Why is TextEncoder a class
POSTED ON:
TAGS: oop javascript
I saw this AskJS post off of reddit and made me think:
new TextEncoder().encode().
instantiating a class for a single function call makes me think I’m doing something wrong. It takes no arguments, has no callbacks. It seems like it could have been a function... Anybody know why it’s this way?
TextEncoder is part of the Encoding API.
The Encoding API provides a mechanism for handling text in various character encodings, including legacy non-UTF-8 encodings.
The API provides four interfaces:
TextDecoder
,TextEncoder
,TextDecoderStream
andTextEncoderStream
.
via the MDN: https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API
And TextEncoder has two instance methods:
textEncoder.encode()
and TextEncoder.encodeInto()
The TextEncoder.encode() method takes a string as input, and returns a Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.
What the poster is asking is why are we doing this instead of a standalone function?
const encoder = new TextEncoder();
const view = encoder.encode("€");
console.log(view); // Uint8Array(3) [226, 130, 172]
The hypothesis? #
via RemoteCombination122:
The original intention with making
.encode
a member on a TextEncoder class was likely to make a predefined destination for future textEncoding methods using other formats in the future.
via ShortFuse:
The most probable reason for keeping the class is to keep syntax parity with TextDecoder which does support more formats than UTF-8:
The encoding spec:
https://encoding.spec.whatwg.org/#interface-textencoder
The decoding Spec:
https://encoding.spec.whatwg.org/#interface-textdecoder
And via Ferrybig:
Internal state is needed.
For TextDecoder, each input byte generates 0 or more characters. If you are decoding a stream, you need something to store the state in. This is because every character exists from multiple bytes. The current streaming approach allows you to decode big multiple GB streams without having to enough to fully represent the input and output in memory at the same time
It's kinda a BS answer IMO, since you can do this with closure? But whatever. The OOP nerds can fight me.
Related TILs
Tagged: oop