I have a function which has to change characters from one array to the characters from another. It is kind of simple encryption. I have:
var plainArray = ['A','B','C',...,'Z'];
var cipherArray = ['a','b','c',...,'z'];
function rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet)
already working.
Now I have to write a function which will change given word into encrypted word.
function encrypt(plainText, signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet)
{
var encryptedString = signalCharacter;
//i is what will hold the results of the encrpytion until it can be appended to encryptedString
var i;
// rotate array to signal character position
var rotateArray = rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet);
for (var count = 0; count < plainText.length; count++)
{
plainAlphabet = plainText.charAt(count);
i = cipherAlphabet[plainAlphabet];
encryptedString = encryptedString + rotateArray[i];
}
return encryptedString;
}
This function returns signal character and then a string of errors. Do you know what is wrong?
You are overwriting plainAlphabet with one character, thus discarding the alphabet. I guess that's not what you want.
However, you only posted the signature of rotateToPosition and not the actual code of it, so I cannot test my solution.
function encrypt(plainText, signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet) {
var encryptedString = signalCharacter;
//i is what will hold the results of the encrpytion until it can be appended to encryptedString
var i;
// rotate array to signal character position
var rotateArray = rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet);
for (var count = 0; count < plainText.length; count++)
{
var plainLetter = plainText.charAt(count);
i = cipherAlphabet[plainLetter];
encryptedString = encryptedString + rotateArray[i];
}
return encryptedString;
}
Related
I'm trying to generate a UserID out of userAgent and Date Function. I also wanted to understand callback function (which I still didn't get (JS Noob)). Therefore I built the following example:
var storage = window.localStorage;
var storageUserId = storage.getItem("userID");
var text = "";
function userID(callback){
var agent = window.navigator.userAgent;
var now = new Date();
try{
callback(agent, now);
}catch(e){}
}
function hasher(agent,now){
var hash = 0;
var arr = [];
for(var i = 0; i < arguments.length; i++){
var pars = arguments[i];
for(var j = 0; j < pars.length; j++){
var charI = pars.charCodeAt(j);
hash = ((hash<<5)-hash)+charI;
hash = hash & hash; // Convert to 32bit integer
hash = hash.toString();
}
}
console.log(hash + "|" + hash);
}
userID(hasher);
The result should look like this "9834917834|8293479273" (example numbers to show format). First number hashed agent second number hashed date. I got the hash logic form here: http://mediocredeveloper.com/wp/?p=55
Maybe there is a better way to do this :)
I really appreciate your help!
Thanks a lot!
Best,
Anton
You should extract the hashing loop into a new function:
function hash(str){
var hash = 0;
for(const char of str){
const charCode = char.charCodeAt(0);
hash = ((hash<<5)-hash)+charCode;
}
hash = hash & hash; // Convert to 32bit integer
return hash.toString();
}
So to get the hash you want to you just need to call it twice:
function getUserID(){
return hash(window.navigator.userAgent) + "|" + hash("" + new Date);
}
(PS: you know that new Date will change every millisecond?)
Unable to split same string for two times.What i am doing wrong?
// my original string
var str = "Left,Right-broken at left side";
var ary = "Left,Right-broken at left side";
//getting text after - (working fine)
var res = str.split("-").pop();
$('#disc_comm_tlside_ed').empty();
$('#disc_comm_tlside_ed').val(res);
// with this i can get text before -once again i need to splt by comma only
var myarrays= str.substr(0, str.indexOf('-'));
//even this also returning original string
var splt = ary.split(',');
// alert(splt) when i alert this getting full string
for(var i = 0; i < splt.length; i++)
{
//alert(myarray[i]);
$(this).find("option[value ='"+myarray[i]+"']").attr("selected",true);
$('.batch_ed').multiselect('rebuild');
}
Finally returning original string!!
Need to get text before-and split text separated by ,
need to get left and right only as array
Edit: adding the code snippet posted in the comment.
var elements = "";
var batchnoe= "";
$.each(data.response.frc_disloc, function (a,b){
batchnoe = '.batch_ed';
$(batchnoe).each(function(i, obj) {
var batch_splt = b.frac_side;
var myarray = batch_splt.split(',');
for(var i = 0; i < myarray.length; i++) {
$(this).find("option[value ='"+myarray[i]+"']").attr("selected",true); $('.batch_ed').multiselect('rebuild');
}
});
});
please check console logs for the output.
// my original string
var str = "Left,Right-broken at left side";
var ary = "Left,Right-broken at left side";
//getting text after - (working fine)
var res = str.split("-").pop();
$('#disc_comm_tlside_ed').empty();
$('#disc_comm_tlside_ed').val(res);
// with this i can get text before -once again i need to splt by comma only
var myarrays= str.substr(0, str.indexOf('-'));
//even this also returning original string
var splt = myarrays.split(',');
console.log(splt);
// alert(splt) when i alert this getting full string
for(var i = 0; i < splt.length; i++)
{
console.log(splt[i]);
$(this).find("option[value ='"+splt[i]+"']").attr("selected",true);
//$('.batch_ed').multiselect('rebuild');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="disc_comm_tlside_ed"></div>
Could any one please help me in generating the Square wave as the output when i give the input in 0's and 1's by using the java script.
it means when we give the input 10101010
the output should be increment the wave and decrementing ....
Here's a function in JavaScript that inverts a "square wave", passed as a string.
var squareWave = function (s) {
var start = !parseInt(s[0]);
var r = [];
var len = s.length;
for (var i = 0; i < len; i++) {
r.push(start ? "1" : "0");
start = !start;
}
return r.join("");
}
Testing the function
squareWave("101010101");
// returns "010101010"
squareWave("010101010");
// returns "101010101"
I have 2 strings with some chars. One of them is with "mashed" characters, and the other one is with ordered characters which have some sense. For example:
wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!
Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT
So as you may see - the first one have equivalent of symbols which are the same for the equal symbol in the second one.
And the task is - to create somehow kind of alphabet from them, because I have third one string wich have to be "decoded". (wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!).
And the tricky part here is - that if I'm pretty sure for the first two strings that they're absolutely equal like a number of chars, so about the new one - is completely different number of symbols, but they consisting in the "alphabet"
And here is my current code for creation of the "alphabet":
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
var myenc = {};
var mynewenc = {};
for (i = 0; i < enc.length; i+=1) {
var encoded = new Array(enc[i]);
var decoded = new Array(dec[i]);
myenc[enc[i]] = dec[i];
};
console.log(myenc);
And now - how I have to decode, the new one string, using this "alphabet"?
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
function make_dictionary(enc, dec){
o = new Object();
if(enc.length == dec.length){
for(i=0; i<enc.length; i++){
o[enc[i]] = dec[i];
}
}
else{
console.log('error');
}
return o;
}
function translate(newenc, dictionary, fill){
var newstring = '';
for(i=0; i<newenc.length; i++){
if(typeof dictionary[newenc[i]] !== 'undefined'){
newstring += dictionary[newenc[i]];
}
else{
newstring += fill;
}
}
return newstring;
}
var d = make_dictionary(enc, dec);
console.log(d);
var string = translate(enc, d, '_');
console.log(string);
var string = translate(newenc, d, '_');
console.log(string);
Here's one way that you can approach it (as I understand the question):
// Create your dictionary
var dict = {};
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!".split('');
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT".split('');
// Populate your dictionary
for (var i = 0; i < enc.length; i++) {
dict[enc[i]] = dec[i];
}
// You can use your dictionary like this
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!".split('');
// Returns your translated string
newenc.map(function(e) {
return dict[e];
}).join('');
However for this method you'll have to deal with characters that are defined in newenc that are not defined in your enc (such as T). I tried to do the best I could given the situation and rules that you've described, hope this helps!
If I understand well, you can try using this code.
It is finding the appropriate encoded letter in your enc variable and if the letter is found, it is replacing it with the corresponding letter from your dec variable.
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
for (i = 0; i < newenc.length; i++) {
for (j = 0; j < enc.length; j++) {
if (enc[j] == newenc[i])
newenc[i] = dec[j];
}
};
console.log(newenc);
At the end your variable newenc may contain your decoded string.
I have this function which decrypts encrypted message. First letter in the encrypted text is a signal character.
function decryptWord(cipherText, indexCharacter, plainAlphabet, cipherAlphabet)
{
var signalCharacter = cipherText.charAt(0);
var decryptedString;
cipherAlphabet = rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet);
for (var count = 1; count<cipherText.length; count++)
{
var singleLetter = cipherText.charAt(count);
var i = cipherAlphabet.indexOf(singleLetter);
decryptedString = decryptedString + plainAlphabet[i];
}
return decryptedString;
}
I'm looking for word JAVASCRIPT as a result but i get 'undefinedJAVASCRIPT' is that because when the first loop is being carried out there is no value assigned to decryptedString? is there a way to go around it? Thanks.
Exactly right, try initialising decryptedString to "".