1

I'd like to reduce this code using the spread syntax to remove the for loop, any ideas?

function shiftChar() {
  let aCharArray = prompt("Enter a word").split("");
  for (let i = 0; i < aCharArray.length; i++) {
    aCharArray[i] = String.fromCharCode(aCharArray[i].charCodeAt(0) + 1);
  }
  alert(aCharArray);
}

This doesn't work

function shiftChar() {
  let aCharArray = prompt("Enter a word").split("");
  aCharArray = String.fromCharCode(...aCharArray.charCodeAt(0) + 1);
  alert(aCharArray);
}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Neodark7
  • 23
  • 2
  • 5

3 Answers3

3

Spread syntax (it's not an operator!) is not a replacement for loops, it's a replacement for apply.

You can do

const string = prompt("Enter a word");
const charCodes = [];
for (let i = 0; i < aCharArray.length; i++) {
    aCharCodes[i] = aString.charCodeAt(i) + 1;
}

though and then use

String.fromCharCode(...charCodes)

instead of

String.fromCharCode.apply(String, charCodes)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

A minified solution not using spread:

function shiftChar() {
    alert(
      prompt("Enter a word").split("")
      .map(letter => String.fromCharCode(letter.charCodeAt(0) + 1));
    );
}

A (strange) minified solution using spread:

function shiftChar() {
    alert(
      [...prompt("Enter a word")].map(letter => ( 
        String.fromCharCode(letter.charCodeAt(0) + 1)
      )
    );
}
stukilgore
  • 101
  • 3
1

For every element in your array you are doing some manipulation, charCodeAt(0) + 1, so it is probably best you use map.

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

You can use the spread syntax in order to update the contents of your variable aCharArray from the array.

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments

function shiftChar() {
  let aCharArray = prompt("Enter a word").split("").map(x => x.charCodeAt(0) + 1);
  aCharArray = String.fromCharCode(...aCharArray);
  alert(aCharArray);
}
Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
guijob
  • 4,413
  • 3
  • 20
  • 39