-1

Here,we created Hashmap with keys and value.Then we use array.map to get our result. i.e If we input "cat",we will get output as "dog".I didnt get how spread syntax is used.

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

function output(str) {
return [...str].map(d => rule[d]).join('')
}

console.log(output('cat')) 
Suman Basnet
  • 65
  • 2
  • 10

5 Answers5

0

spread syntax on a string turns it into an array consisting of its characters. This works because strings are iterable collections. http://es6-features.org/#SpreadOperator

lluisrojass
  • 439
  • 1
  • 3
  • 12
0

It takes an iterable and returns each item of the iterable by using the spread syntax ....

In this case, a string is splitted to an array of characters.

['c', 'a', 't']

The same result could be achieved, if you use Array.from, which has a built-in mapping parameter.

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

function output(str) {
    return Array.from(str, d => rule[d]).join('');
}

console.log(output('cat')) ;
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

In your case the spread operator spreads the string "cat" into an array of characters containing ['c','a','t']

Then it iterates over this array to provide the output string matches the values. There you get the string "dog" as output!

Lucifer
  • 645
  • 6
  • 14
0

You would not be able to apply map to the string directly, as String does not have such a method. With the spread syntax you get an array of individual characters, and then map can be applied to that array.

It is in fact better practice to use Array.from instead, because it does not create the intermediate array and still allows you to execute a function on each character (using the second argument):

Array.from(str, d => rule[d]).join('')
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Break it down:

[...str]

Gives: ['c', 'a', 't'];

In this case, the spread syntax breaks up the string into an array. Where each index represents a letter from the string.

.map(d => rule[d])

Converts the above array to:

['d', 'o', 'g']

As it goes through each value and uses the javascript object to get its value: (so 'c' maps to 'd' as rule['c'] = 'd', 'a' maps to 'o', etc...)

.join('')

Converts the above array to a string dog

Thus, doing:

console.log(output('cat'))

Gives: "dog"

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64