1

I am currently working on a project where some records for wpm are displayed. It currently works so that if any elements in the array are undefined it sets them to "" so that on output they are not displayed. My version is clunky and too big, and I was wondering how I would make it smaller with a function.

Code:

var fifteenSecond = `Your 15s highscore: ${maxesTime[15]}wpm`
var thirtySecond = `Your 30s highscore: ${maxesTime[30]}wpm`
var sixtySecond = `Your 60s highscore: ${maxesTime[60]}wpm`

  if (maxesTime[15] === undefined) {
    fifteenSecond = ""
  } else if (maxesTime[30] === undefined) {
    thirtySecond = ""
  } else if (maxesTime[60] === undefined) {
    sixtySecond = ""
  }

console.log(`${sixtySecond}}\n${thirtySecond}\n${fifteenSecond}`);

Thanks in advance,

Any and every answer is greatly appreciated

2 Answers 2

2

You could simply use a for to check every property i in maxesTime. In this way if you add a new "max time" (e.g. "45"), you don't have to change your code.

let maxesTime = {
  '15': 100,
  '30': null,
  '45': undefined,
  '60': 400
};
for (let i in maxesTime) {
  if (maxesTime[i]) {
    console.log(`Your ${i}s highscore: ${maxesTime[i]}wpm`);
  }
}

Sign up to request clarification or add additional context in comments.

Comments

2

Here is my aproach:

function getRecord(seconds, maxesTime) {
  return maxesTime[seconds] ? 
    `Your ${seconds}s highscore: ${maxesTime[seconds]}wpm`
    : '';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.