Below is a piece of Ruby code I am rewriting in JavaScript. I understand that it packs the array as '8-bit unsigned (unsigned char)', and then unpacks it as '16-bit unsigned, VAX (little-endian) byte order', but my attempts to make it work in JavaScript have failed.
I was wondering if the ||= has any impact on the values in the array?
I would also like to know how the packing and unpacking influences the values in the array? Does it only change 0x01 into 0x0100?
@_tree_left ||= [
0x01, 0x01, 0x03, 0x01, 0x05, 0x01, 0x07, 0x01, 0x0B, 0x01, 0x0D, 0x01,
0xF9, 0x00, 0xFB, 0x00, 0xFD, 0x00, 0x00, 0x01
].pack('C*').unpack('v*')
2 Answers 2
||= is a classic Ruby idiom meaning:
v = v || second_expression
If the first expression evaluates to false or nil it means second one will be executed.
Comments
The ||= is just shorthand for:
@_tree_left = @_tree_left || [ ... ].pack('C*').unpack('v*')
The first time the statement is executed, @_tree_left will be nil, and so it will be assigned the value of the right hand expression. If executed a second time, then as long as @_tree_left has any kind of a value left, it will not be changed.
It's a bit easier to see if simplified.
@a # => nil
@a = @a || 123 # => 123
@a = @a || 456 # => 123, no change this time
The rest of the expression is storing and retrieving a specific binary string.
It can be easily duplicated in JavaScript. It's just combining every two values in the array. So it's computing:
b[0] = a[0] + (a[1] << 8)
b[1] = a[2] + (a[3] << 8)
. . .