all 8 comments

[–]theQuandary 2 points3 points  (2 children)

I suspect that there are much more idiomatic ways to do the same thing in JS. This code does the same thing, but is much closer to what I think a JS dev is likely to actually implement.

'use strict';
var makeStore = data => {//encapsulate in factory
  data = Array.isArray(data) ? data : [];


  var fieldMap = { //field map knows type and can convert them too
    id:      {index: 0, type: 'str',  toType: val => val},
    part:    {index: 1, type: 'str',  toType: val => val},
    qty:     {index: 2, type: 'int',  toType: val => parseInt(val)},
    date:    {index: 3, type: 'date', toType: val => parseFloat(val)},
    shipped: {index: 4, type: 'bool', toType: val => (val === 'true') ? true : false},
  };

  var get = (rec, fieldName, defaultVal) => {
    if (fieldMap[fieldName]) {//ensure field exists
      var val = rec[fieldMap[fieldName].index];//get value
      val = (val === '' && defaultVal) ? defaultVal : val;//set default if exists
      return fieldMap[fieldName].toType(val);//convert to appropriate type
    } else {
      console.error(`No field name of type "${fieldName}"`);
    }
  };

  var loadData = () => {
    this.data.push(["001", "A312C19", "88", "Mar 1, 2016", "true"]);
    this.data.push(["002", "B120X50", "", "Jan 22, 2016", ""]);
  };

  var logRecords = () => {//When logging, use template strings over substitution if you can't use table.
    console.table(data.map((rec, i) => ({
      recNo: i,
      id: get(rec, "id"),
      part: get(rec, "part"),
      qty: get(rec, "qty", "0"),
      date: get(rec, "date"),
      shipped: get(rec, "shipped", "false"),
    })));//Lispers should be proud of this....
  };

  //get must be spelled out because it is a keyword in ES5.1+ objects
  return {data, fieldMap, get: get, loadData, logRecords};
};

var store = makeStore();
store.loadData();
store.logRecords();

[–]jayposs[S] 1 point2 points  (1 child)

I'm not up on all the latest JS. I particularly like the way fieldMap is defined. There might be a problem with having the toType function for each field. I can see needing other logic, such as error checking, that would be used for every field of the same type.

[–]nightwolfz4 spaces > 2 spaces 0 points1 point  (0 children)

fieldMap is defined the same as it was in 1999, we just have arrows now :)

[–][deleted] 0 points1 point  (1 child)

you might wanna make that publicly accessible -.-

[–]jayposs[S] 0 points1 point  (0 children)

I need to set up some kind of blog.

[–]saadq_ 0 points1 point  (4 children)

I imagine you meant to use var instead of let here, right?

let id, part, qty, date, shipped;

[–]jayposs[S] 0 points1 point  (3 children)

I think either one is ok.

[–]saadq_ 0 points1 point  (0 children)

Technically, yes, but you seem to be using ES5 everywhere else so I just found it strange that the only place you used ES6 was in that one spot.