Solo Dev Lessons - 2018 - May the 4th

On Wednesdays and Fridays, I meet with folks at Bitovi to discuss problems they are facing. I’m going to try to share the good bits:

Use getters to change data for a format better for the view.

Someone had data like:

[
  {step: 1, name: "wash dishes"},
  {step: 1, name: "clean floor"},
  {step: 2, name: "wash car"},
  {step: 2, name: "get gas"}
]

And they wanted the data to show up like:

  • step 1
    • wash dishes
    • clean floor
  • step 2
    • wash car
    • get gas

I suggested using a getter to prepare the data for the view:

get nestedSteps(){
  var steps = [];
  this.steps.forEach(function(steps, newStep){
    if(!steps.length){
      steps.push( {step: newStep.step, children: [newStep] }  );
    }
    if(step.step === steps[steps.length-1].step){
      steps[steps.length-1].push(step);
      return steps;
    } else {
     steps.push( {step: newStep.step, children: [newStep] }  );
    }
  })
  return steps;
}

View:

<ul>
{{#each(nestedSteps)}}
  <li>Step {{step}}
    <ul>
    {{#each(children)}}
      <li>{{name}}
    {{/each}}
    </ul>
  </li>
{{/each}}
</ul>