Reputation: 1203
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');
}
});
Upvotes: 1
Views: 51
Reputation: 11730
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.
Upvotes: 1
Reputation: 386680
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);
}
Upvotes: 0