epiqueras epiqueras - 1 month ago 23
Javascript Question

Buffer Use Explanation

I found this ingenious caesar cipher solution on codefights. I'm trying to understand what the buffer is doing here.

b=Buffer
caesarian = (m, n) =>
"" + b([...b(m)].map(x => (n % 26 + x + 7) % 26 + 97))


Can empty strings concatenate with typed arrays like that?

Answer

Iterating a Node.js Buffer yields its data one byte at a time. For a Buffer (with the default encoding of utf8) that contains alphanumeric characters, that's the same thing getting each char's ASCII code:

[...Buffer("hello")] // [ 104, 101, 108, 108, 111 ]

(n % 26 + x + 7) % 26 + 97) is the Caeser cipher arithmetic - I guess you're familiar with this part.

So, this part of the code interprets the String as an array ASCII codes and transforms them to their corresponding outputs:

[...b(m)].map(x => (n % 26 + x + 7) % 26 + 97))

You can initialise a Buffer with an array of byte values:

Buffer([97]) // <Buffer 61>

You can get the String representation of any JavaScript object by concatentating it with another String, so "" + b([97]) is the same as Buffer([97]).toString(). Buffer#toString interprets the stored bytes as unicode characters:

"" + Buffer([97]) // 'a'

Therefore the point of the outer b is to turn the manipulated ASCII codes back into alphanumeric characters for display.

Comments