1

I'm still trying to practice making my code smaller. I know there's gotta be a better way to write this out using a loop. Can someone help me out?

Template.project.helpers({
  cell1: function() {
    return Session.get('cell1');
  },
  cell2: function() {
    return Session.get('cell2');
  },
  cell3: function() {
    return Session.get('cell3');
  },
  cell4: function() {
    return Session.get('cell4');
  },
  cell5: function() {
    return Session.get('cell5');
  },
  cell6: function() {
    return Session.get('cell6');
  },
  cell7: function() {
    return Session.get('cell7');
  },
  cell8: function() {
    return Session.get('cell8');
  },
  cell9: function() {
    return Session.get('cell9');
  }
});
7
  • 1
    There probably is, if it were clear what you want to do. An anonymous object, wrapped in parentheses -- none of these functions can ever be called. Commented Dec 3, 2015 at 16:06
  • 1
    since the code is 99% alike, why not a common method that is cell: function (index) { Session.get('cell' + index); } Commented Dec 3, 2015 at 16:09
  • Question is probably better suited for codereview.stackexchange.com Commented Dec 3, 2015 at 16:10
  • 1
    @epascarello CR wants full, working code for review and possible improvement. This would be rejected without first being edited into something useful. Commented Dec 3, 2015 at 16:13
  • What is this code actually? A parameter list for a function call? Commented Dec 3, 2015 at 16:14

2 Answers 2

1

Try this:

var cells = {};
for (i = 1; i <= 9; i++) {
  cells["cell" + i] = function(cell) {
      return function() {
        Session.get("cell" + cell);
      }
  }(i);
}

The only tricky part is that if you don't include that secondary function, with its own closure, your function will use the outer closure and the value of cell will be 9 in all cases.

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

1 Comment

this was close, the cells["cell" + cell] needed to be cells["cell" + i], thanks!
0

I would take a function, because of the object needs a string for the access and that is exacly what the function needs as well.

function getSession(s) {
    Session.get(s);
}

The difference is, the object has for any possible sting an own property and it stores only the call with the given property. As long as there are not other dependent code in the objects methods, i would not use it in the OP's style.

If the object should work like a filter, that only some strings are allowed to use, then i would take this solution:

function getSession(s) {
    ~['cell1', 'cell2', 'cell3', 'cell4', 'cell5'].indexOf(s) && Session.get(s);
}

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.