DEV Community

Discussion on: Daily Challenge #2 - String Diamond

Collapse
 
wolverineks profile image
Kevin Sullivan
const reverse = xs => xs.reduce((result, current) => [current, ...result], []);

const padding = width => " ".repeat(width);
const emptyRows = width => Array(width).fill(null);
const stars = count =>
  Array(count)
    .fill(null)
    .map(() => "*")
    .join(" ");
const topRows = width => reverse(bottomRows(width));
const centerRow = width => stars(width);
const bottomRows = width =>
  emptyRows(width - 1).map(
    (_, index) => `${padding(index + 1)}${stars(width - (index + 1))}`,
  );

export const stringDiamond = width => {
  if (width % 2 === 0) return null;
  if (width <= 0) return null;
  return [...topRows(width), centerRow(width), ...bottomRows(width)].join(`\n`);
};