0
\$\begingroup\$

The problem statement is as follows: I have a database of name tag data. I want to display these name tags to the screen. Each item of information on a nametag has certain rules for its display.

Here I have encoded those rules for display into a function nameTagConvertToDisplay to show what I mean. This function is just a bunch of if statements, and I don't really like it. I feel like there is probably a class-based approach that is cleaner.

I'm not too concerned with the code inside the renderNameTags function because it's just boilerplate and not related to my actual problem. The function/class structure is really what I am looking for help on

https://jsfiddle.net/4ngzdxot/9/

interface NameTagDatum {
  name: string;
  job:  string;
  age: number;
}


let nameTagData = [
{name: "Joe", job: "QA Tester", age: 30},
{name: "Althea", job: "Senior Software Developer", age: 56}
]

function nameTagConvertToDisplay (nameTag, attribute) {
  if (attribute === "name") {
    return "My name is " + nameTag.name
  }
  if (attribute === "job") {
    return "My job is " + nameTag.job
  }
  if (attribute === "age") {
    if (nameTag.age > 40) {
        return "I am " + nameTag.age.toString() + " years young!"
    }
    else {
        return "I am " + nameTag.age.toString() + " years old"
    }
  }
}

function renderNameTags(nameTags: NameTagDatum[]) {
  let nameTagsToRender = []
  nameTags.forEach(nameTag => {
    let nameTagToRender = ""
  
    nameTagToRender += nameTagConvertToDisplay(nameTag, 'name') + "<br>"
    nameTagToRender += nameTagConvertToDisplay(nameTag, 'job') + "<br>"
    nameTagToRender += nameTagConvertToDisplay(nameTag, 'age') + "<br>"
    nameTagsToRender.push(nameTagToRender)
  })
  return nameTagsToRender.join("<br>")
}

document.querySelector("#app").innerHTML = renderNameTags(nameTagData);
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It's not clear if you are expected to create a function, but it seems unnecessary as framed.

interface NameTagDatum {
    name: string;
    job:  string;
    age: number;
}

let nameTagData = [
    {name: "Joe", job: "QA Tester", age: 30},
    {name: "Althea", job: "Senior Software Developer", age: 56}
]

function renderNameTags(nameTags: NameTagDatum[]): string {
    return nameTags.flatMap(nameTag => {
        return [
            `My name is ${nameTag.name}`,
            `My job is ${nameTag.job}`,
            `My age is ${nameTag.age} years ${nameTag.age > 40 ? 'old' : 'young!'}`
        ]
    }).join('<br>')
}

console.log(renderNameTags(nameTagData))
```
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.