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);
}
1
  • 2
    how about using .map? Commented Feb 27, 2018 at 15:48

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

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)
      )
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.