I'm doing this javascript algorithm challenge which has this array ['cat', 'game', 'socks']
and the function must return me this result:
[
"******cat******",
"*******game*******",
"********socks********"
]
(each word has a * more than the previous word, so not all words should be equal), Would you use forEach? or how would you do it?
CodePudding user response:
We can do it via Array.map() and String.repeat()
let data = ['cat', 'game', 'socks']
let result = data.map((d,i) => {
let s = `*`.repeat(i)
let e = `*****${s}\n*${d}*\n${s}*****`
return e
})
console.log(result)
CodePudding user response:
I was not going to originally submit an answer, but why not.
My approach would be using a for loop to iterate the list once and maintaining a string that gets incremented with a *
for every for
call.
In big-o notation, this would be an O(n) solution.
let data = ['cat', 'game', 'socks']
let buffer = '*****';
for(let i = 0; i < data.length; i ) {
data[i] = `${buffer}\n*${data[i]}*\n${buffer}`;
buffer = '*';
}
console.log(data)