0

Is there anyway to go form this

var stateDat = {
ME: ['Maine',1328361],
etc.
};

To this

var stateDatHistory = {
1:[
  ME: ['Maine',1328361],
  etc.
  ],
2:[
  ME: ['Maine',1328361],
  etc.
  ],
etc
};

Dynamically in a function? For example, this doesn't work…

turn = 1;

function start(){
stateDatHistory[turn].push(stateDat);
stateDat['ME'][1]= stateDat['ME'][1] - 500; //changing population
turn++;
}
1
  • Array literals can't have ME: inside them Commented May 14, 2012 at 18:35

1 Answer 1

1

The history part of it could be an array of objects. So...

var stateDatHistory = [
   { ME: ['Maine', 1328361] }
];

Or if you needed to reference every 'step' in the history by a key, it could be a object with array values containing objects...

var stateDatHistory = {
    1: [
        { ME: ['Maine', 12334] }
    ]
}

In the latter case, the "start" code would be something like...

turn = 1

function start() {
    if (typeof stateDatHistory[turn] === 'undefined') {
        stateDatHistory[turn] = [];
    }
    stateDatHistory[turn].push(stateDat);
    stateDat['ME'][1]= stateDat['ME'][1] - 500; //changing population
    turn++;
}

Having said all that, I feel inclined to mention that using an object to contain all of this state data would be a good decision. Consider for example...

// Define our manager
var stateDatManager = function() { };
(function(instance) {

    instance.init = function() {
        // Setup internal state
        this.history = {};
        this.turn = 0;
        this.initialized = true;
    };

    instance.start = function(turn, data) {
        if (!this.initialized) { this.init(); }
        this.turn = turn;
        this.addToHistory(data);
    };

    instance.addToHistory(data) {
        if (typeof this.history[this.turn] === 'undefined') {
            this.history[this.turn] = [];
        }
        this.history[this.turn].push(data);
    };

    instance.advanceTurn() {
        this.turn += 1;
    };

}(stateDatManager.prototype));

// Use it
var manager = new stateDatManager();
manager.start(1, [
    { ME: ['Maine', 1328361] }
]);

// Move to the next turn...
manager.advanceTurn();

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

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.