How does this code break the string into parts?

Asked

Viewed 78 times

2

Through that question: How to remove all element from array except the first one in javascript.

I adapted the code to my need.

var rua = 'RUA NILO PEÇANHA';
const head = ([x, ...xs]) => x
const tail = ([x, ...xs]) => xs
console.log(`${head(rua).toUpperCase()}${tail(rua).join('').toLowerCase()}`)

I ended up choosing the code that has both counts head and tail.

I’ve never seen anything like: ([x, ...xs]) => x. I know that the Spread along with arrow functions(arrow functions).

Doubt:

  • Like a code like ([x, ...xs]) => x returned only the first letter and ([x, ...xs]) => xs returned all the rest?
  • 1

    But allow me one comment: the title of the question addresses one issue and the content others.

  • @Andersoncarloswoss that’s the Spread?

  • Spread, actually :D Yes, it is one of its uses

  • I won’t put it as an answer, because I don’t know the whole principle, but I’ll try to help with some information: Strings are strings, that is, they can be considered concatenated letter arrays. That’s the part I don’t know exactly how it works. ([x, ...xs]) => x basically takes an array with undefined values, and returns only the first value, x. The same goes for the other, takes all the values that are not the first, the xs.

1 answer

10


The functions head and tail make a "smart" use of the operator of spread and the fact that strings allow character-to-character access with the use of brackets.

When it is stated that their argument is [x, ...xs], we are saying that the function takes an array. When we pass a string, it is treated as an array of characters.

For example, if we call head passing by abcd:

head("abcd")

What the function receives internally is:

["a", ["b", "c", "d"]]

The first position of the array, x, is the first character. The rest will be stored in the second position of the array, which in turn is another array, xs. Notice that in your code there is a .join('') as a result of tail. That’s because tail returns array, which needs to be converted to string by join so that the method toUpperCase can be called then, since it only applies to strings.

  • Cleared the doubts, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.