I have the following function:
const arrayOfStrings = n => new Array(n)
.fill(new Array(2 * n - 1).fill(' '))
.map((e, i) => e
.fill(i, i, e.length - i)
.join(''));
I expect when invoked like this arrayOfStrings(3), I expect it to return the following:
[
'00000',
' 111 ',
' 2 '
]
However it doesn't, instead it returns this:
[
'00000',
'01110',
'01210'
]
Or if I remove the .join('') from within the map and return e still as an array it returns this:
[
[0,1,2,1,0],
[0,1,2,1,0],
[0,1,2,1,0]
]
What I believe is going on:
fillcalled insidemapis running on every child array element in the mapped parent array on each iteration.- When
joinis present the the target child array (e) is returned as a string from each iteration, leaving one fewer arrays for thefillto be called on on the next iteration ofmap. - When
joinis absent the all threeeelements remain arrays andfillis run on every child array on every iteration.
The Question
I'm not concerned particularly with how to get my desired outcome. What I want to know is why calling fill inside map behaves in this way?
Thanks