Home > Enterprise >  beginner javascript algorithm: method forEach?
beginner javascript algorithm: method forEach?

Time:12-15

I'm doing this javascript algorithm challenge which has this array ['cat', 'game', 'socks'] and it has an image of what it must return:

[
  "******cat******",
  "*******game*******",
  "********socks********"
]

as you see, 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:

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)

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)

  • Related