0

Given a JS literal object like:

var foo = {
    _stuff : {
        a:10,
        b:20,
        c:30,
        state
    }
}

and literal functions

addAB: function() {
    add(foo._stuff[a], foo._stuff[b]);
}

addAC: function() {
    add(foo._stuff[a], foo._stuff[c]);
}

add: function(bar, baz) {
    foo._stuff[bar] += foo._stuff[baz];
    state(foo._stuff[bar]);
}

state: function(value) {
   foo.state[value] = .... something complex ....
}

How can I get the following in one pass ?

add(AB); foo._stuff[a] should be 30, foo.state[foo._stuff[a]] is something new
add(AC); foo._stuff[a] should be 40, foo.state[foo._stuff[a]] is something new

As is add() will try to lookup foo._stuff[10] which clearly wont do what I want.

Yes I know there is redundancy with addAB() and addAC() but that is out of my control.

2
  • 4
    "Given a JS literal object like:" --- it's syntactically incorrect
    – zerkms
    Dec 31, 2012 at 21:46
  • For what you're talking about, the addAB and addAC functions should be calling add with 'a', 'b' and 'a', 'c', respectivly, not foo._stuff['a'], etc.
    – Paul S.
    Dec 31, 2012 at 21:50

3 Answers 3

2

Pass the index instead of the value, like this:

addAB: function() {
    add('a', 'b');
}

addAC: function() {
    add('a', 'c');
}
0
add: function(bar, baz) {
    if (arguments.length === 1) {
        this['add' + arguments[0]];
    } else {
      foo._stuff[bar] += foo._stuff[baz];
      state(foo._stuff[bar]);
    }
}

// assuming you are calling
var AB = 'AB', AC = 'AC';
add(AB); 
add(AC);

Otherwise, I have not a clue what you are asking.

0

I'm not sure if I totally follow what you want to accomplish, but your object literal is not valid syntax. I don't see why you want the _stuff property. And, you need to initialize the state property to some value, even if it's undefined. But, since you want to store values in the state property based on some property name, you should initialize state to be an object.

var foo = {
    a:10,
    b:20,
    c:30,
    state: {}
}

Your javascript:

addAB: function() {
    add('a', 'b');
}

addAC: function() {
    add('a', 'c');
}

add: function(propName0, propName1) {
    foo[propName0] += foo[propName1];
    state(propName0);
}

state: function(propName) {
    // state is initialized to an object, so can store properties in there now
   foo.state[propName] = .... something complex ....
}

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.