Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform a calculation on each object in my array, then output that array?

I'm trying to perform a calculation in Javascript (n^e mod n) for each element e in my array, then output that new array subsequently created. How would I do this? This is what I've figured out so far, but the code doesn't work.

This is what I've figured out so far, but the code doesn't work.

function encryptText() {
  var plaintext = document.getElementById('plaintext').value;
  var n = letterValue(String(plaintext));
  ciphertext = array()
  foreach(addon_array as key => col) {
    ciphertext[key] = Math.pow(col, e) % n;
  }
  document.getElementById("output3").innerHTML = "Encrypted text = " + ciphertext;
}

I hope to get an array of modified integers (the ciphertext) as a result. Thank you

like image 897
Olaf Willner Avatar asked Apr 28 '19 20:04

Olaf Willner


3 Answers

You can use Javascript's map() function on an array.

const arr = [1, 2, 3];
const newArr = arr.map(i => i * 2);

// should be [2, 4, 6]
console.log(newArr); 
like image 179
Daniel Cottone Avatar answered Sep 29 '22 02:09

Daniel Cottone


Use Javascript map function, like so:

function encryptText() {
  var plaintext = document.getElementById('plaintext').value;
  var n = letterValue(String(plaintext));
  ciphertext = addon_array.map((el) => Math.pow(el, e) % n);
  document.getElementById("output3").innerHTML = "Encrypted text = " + ciphertext;
}
like image 42
Guilherme Lemmi Avatar answered Sep 29 '22 01:09

Guilherme Lemmi


You are using php syntax in javascript :)

in js it should look like this

function encryptText() {
  var plaintext = document.getElementById('plaintext').value;
  var n = letterValue(String(plaintext));
  var ciphertext = []
  for(var key in addon_array) {
    let col = addon_array[key]
    ciphertext[key] = Math.pow(col, e) % n;
  }
  document.getElementById("output3").innerHTML = "Encrypted text = " + ciphertext;
}

But as mentioned before, in js better approach is to use Array.map function

function encryptText() {
  var plaintext = document.getElementById('plaintext').value;
  var n = letterValue(String(plaintext));
  var ciphertext = addon_array.map((el) => Math.pow(el, e) % n);
  document.getElementById("output3").innerHTML = "Encrypted text = " + ciphertext;
}

it should work if you sure, that addon_array is really Array, not an Object. Arrays in js are slightly different from php. Read more here

like image 25
zoryamba Avatar answered Sep 29 '22 02:09

zoryamba