Kyclon
Kyclon

Reputation: 11

How can I shorten this?

I am looking to shorten my hard written code for a project I am currently working on. The problem is I don't know how to, because I am fairly new.

I've hardcoded, googled what else I can do, but nothing is helping me.

if (spins >= 3 && spins <= 5) {
  textSize(40);
  text("H", 20, 40);
}  if (spins >= 6 && spins <= 8) {
  textSize(40);
  text("HA", 20, 40);
}  if (spins >= 9 && spins <= 11) {
  textSize(40);
  text("HAP", 20, 40);
}  if (spins >= 12 && spins <= 14) {
  textSize(40);
  text("HAPP", 20, 40);
}  if (spins >= 15 && spins <= 17) {
  textSize(40);
  text("HAPPY", 20, 40);
}

Nothing is going wrong I just want to shorten it, it works perfectly as is, but I'm still trying to learn, and I'm way ahead of the class, but I can't find help from google or my peers.

Upvotes: 1

Views: 43

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

Note that the text string length directly corresponds to Math.floor(spins / 3) - use that to determine the length of the string to pass to text:

const strLen = Math.floor(spins / 3);
textSize(40);
text('HAPPY'.slice(0, strLen), 20, 40);

const getText = (spins) => {
  const strLen = Math.floor(spins / 3);
  console.log('HAPPY'.slice(0, strLen));
};
getText(3);
getText(4);
getText(5);
getText(6);
getText(14);
getText(15);

Upvotes: 2

Related Questions