user4434001
user4434001

Reputation:

Need explanation of some magic numbers

i found this piece of code in the internet

var b = '12-0-17-2-4-11-14';
var xxx = b.split('-').map(function (x) {
  var x = Number(x); 
  return String.fromCharCode(x < 26 ? 97 + x : 39 + x);
}).join('');
console.log(xxx);

being:

0 = "a";
b = "1";
c = "2";
d = "3";

The output of this code will be 'Marcelo', cause

12 = "M", 0 = "a",  17 = "r", 2 = "c", 4 = "e", 11 = "l", 14 = "o";

I understand until transform all the strings into numbers, but the rest a im not catching

What the fromCharCode(x < 26 ? 97 + x : 39 + x) is doing? This pieace of code is responsible for match the numbers with the alphabet.

Can someone explain me?

Upvotes: 3

Views: 56

Answers (3)

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

(x < 26 ? 97 + x : 39 + x) 

just a calculation for forming alphabets out of the numbers.

if the value of x(i.e each number in the string) is less than 26, thus if can be mapped to alphabet(alphabets are 26 right?), then return the char code for that alphabet, else return the charcode for capital alphabet

Upvotes: 1

Silviu Burcea
Silviu Burcea

Reputation: 5348

It converts a number to its ASCII representation.

The 'A' char has 65 decimal value, the 'a' char has 97 decimal value.

You can see an ASCII table here: http://www.asciitable.com/

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72857

That little calculation in fromCharCode is used to map a zero-indexed alphabet (0:a,1:b,...25:z,26:A...) to their proper Character codes:

var output = '';

for(var i = 0; i < 52; i++){
    output += String.fromCharCode(i < 26 ? 97 + i : 39 + i);
}
alert(output);

As you can see here: enter image description here Charcodes 65-90 are A-Z, 97-122 are a-z.

So, the first half of the alphabet (x < 26), has 97 added to it's index, while the second half (x >= 26), has 65-26 added, which is 39.

Upvotes: 2

Related Questions