DEV Community

Discussion on: Algorithms Are Monsters (but don't be afraid)

Collapse
 
pentacular profile image
pentacular • Edited

It might be worth considering a different approach to finding the maximum.

const length = (input) => input.length;
const lengths = (inputs) => inputs.map(length);
const maxLength = (inputs) => Math.max(...lengths(inputs));

I'm not convinced that it is a better approach than what you're doing now, but it can be nice to think about decomposing the solution into parts with clearer meanings.

Actually, if you look at your code, you make an assumption that makes this unnecessary.

 newString = '*' + picture[i] + '*'

This will fail to work if the length of picture[i] varies with i.

Which means that you can find the correct length by using picture[0].length + 2.

So, think about either padding each row of picture out to the maximum length, or don't bother finding the global maximum, since you don't make proper use it of anyhow. :)

Which can reduce the solution down to something like this:

const addBorder = (picture) => {
  const rowLength = picture[0].length + 2;
  const rowOfStars = '*'.repeat(rowLength);
  return [
    rowOfStars,
    ...picture.map(row => `*${row}*`),
    rowOfStars
  ];
}
Collapse
 
kahawaiikailana profile image
Kailana Kahawaii

Great alternative! Thank you!