Yesterday I've read the question Algorithm to create costum Template/Code from String. Because the question was not formulated that well it was downvoted just instantly. However, the question itself was in my opinion not that bad, so I decided to ask a hopefully better version of this question again.
Ok, Im wondering how's the string encryption e.g. of the new Spotify codes is working. See the image below:
I would be super interested in the extent to which it is possible to implement something like this pattern-encryption in javascript.
The Spotify codes - I've already mentioned above - are structured in a row that is divided into different sized bars.
So let's say there is a row that is divided into 24 bars and all of the bars can have the size '3', '5', '7' or '9'.
string = 'hello' --> pattern = '3,3,5,7,9,3,7,9,9,3,3,5,3,9,5,3,3,7,5,9,3,9,3,9'
What's a good method / easy way to translate a string (lets say 5 characters) into a unique pattern, that afterwards is also convertible back and read as a string?
This is my code I've developed till now, but in this code I used a key-array that includes 10 different possibilities (--> bar sizes) , but I just like to us 4 different sizes.
Explanation:
I' converting my string 'hello' to binary format and splitting the string up into groups of maximum 3 to get something like this: ['001', '110', '0'].
Afterwards I'm using the result array above and find the matches in my Key-array below and get the indexes (10 different indexed --> 10 different possibilities) and use them as bar-sizes.
But, There MUST BE a way more efficient method to translate a string into a unique pattern. I hope somebody can help me improve my small algorithm. Thanks a million in advance.
var key = ['0', '1', '000','001','010','100','110','101','011','111']
String.prototype.encode = function() {
var code = this, result = [],encryped_string=[]
for (var i=0; i<code.length;i++) result.push(code[i].charCodeAt(0).toString(2).match(/.{1,3}/g));
for (var i=0; i<result.length; i++) for (var j=0; j<result[i].length; j++) encryped_string.push(key.indexOf(result[i][j]))
return encryped_string
}
var code = 'hello';
console.log(code.encode())