Pre-release
Adventure.js Docs Downloads
Score: 0 Moves: 0
// cloneWorld.js

/*global adventurejs A*/
"use strict";

/**
 * Clone the game world for save / restore functions.
 * @memberOf adventurejs
 * @method adventurejs#cloneWorld
 * @param {Object} source
 * @returns {Object} Returns a copy of the source world.
 */
adventurejs.cloneWorld = function Adventurejs_cloneWorld(source) {
  console.warn("cloneWorld");
  this.game.log("log", "high", `cloneWorld()`, "CopyOperations");

  var dest = {};

  var starttime = new Date().getTime();

  for (var object in source) {
    if ("undefined" === typeof source[object].class) {
      dest[object] = source[object];
    } else {
      dest[object] = new adventurejs[source[object].class](
        source[object].id,
        this.game_name
      );
      for (var prop in source[object]) {
        var stringified;

        //if( false === source[ object ].hasOwnProperty( prop ) ) continue;

        if ("string" === typeof source[object][prop]) {
          dest[object][prop] = source[object][prop];
          continue;
        }

        // functions need to be converted to string then reconstituted with eval()
        if ("function" === typeof source[object][prop]) {
          // this version does stringify then parse - unsure its necessary
          //stringified = JSON.stringify( source[ object ][ prop ].toString() );
          //dest[ object ][ prop ] = eval( '(' + JSON.parse(stringified) + ')' );

          // alt version that converts to string but doesn't stringify
          stringified = source[object][prop].toString();
          dest[object][prop] = eval("(" + stringified + ")");

          continue;
        }

        // if it's an object, we might need to recurse, so use clone()
        if ("object" === typeof source[object][prop]) {
          dest[object][prop] = A.clone.call(this.game, source[object][prop]);
          continue;
        }

        // not a string, not a function, do ordinary stringify
        stringified = JSON.stringify(source[object][prop]);
        if ("undefined" !== typeof stringified) {
          dest[object][prop] = JSON.parse(stringified);
        }
      }
    }
  } // for( var object

  this.game.log(
    "log",
    "high",
    "cloneWorld() took " +
      (new Date().getTime() - starttime) / 1000 +
      " seconds.",
    "CopyOperations"
  );

  //console.warn( dest );
  return dest;
};

// another cloning tool
// http://www.eslinstructor.net/jsonfn/

// might also try lodash