0

Here I created hashmap array and created one function.

var rule = 
{
"c": "d",
"a": "o",
"t": "g",
"h": "a",
"1":"@",
"e": "n",
"n": "t"
}
function convert(str) {
return [...str].map(d => rule[d]).join('')
}
console.log(convert("cat1hen"))

It display output as "dog@ant".But I want different output.Everytime there is expected output as "@",I want to swap "@" to swap its value with next array element.

It means output should be "doga@nt" instead of "dog@ant".Here position of @ is swapped with its next array element i.e "a". The position should be swapped only when expected output is "@".

1 Answer 1

2

You can add a second argument to you .map() call for the index (i) and then swap the values if @ occurs:

See code comments for further details:

var rule = {
  "c": "d",
  "a": "o",
  "t": "g",
  "h": "a",
  "1": "@",
  "e": "n",
  "n": "t"
}

function convert(str) {
  let strArr = [...str];
  return strArr.map((d, i, arr) => {
    if (rule[d] == '@') { // If current letter maps to '@'
      return rule[arr[i + 1]]; // Set the current letter to the next one 
    } else if (rule[arr[i - 1]] == '@') { // If the previous letter mapped to '@'
      return '@'; // Set the current letter to the '@' SAME AS: return rule[strArr[i - 1]]
    }
    return rule[d];
  }).join('')
}
console.log(convert("cat1hen"))

Sign up to request clarification or add additional context in comments.

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.