// Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.

module.exports = function(landscape) {
  let actions = new Map();
  let tickCount = 0;
  let thingToDo = [];

  return {
    "tick": () => new Promise(function(resolve, reject) {
      try {
        tickCount += 1;

        if (actions.has(tickCount)) {
          let thing = thingToDo.pop();
          landscape[thing.method].apply(landscape, thing.args);
        }

        resolve();

      } catch(error) {
        reject(error);
      }
    }),

    "at": function(when, method) {
      thingToDo.push({
        "when": when,
        "method": method,
        "args": [...arguments].slice(2)
      });

      actions.set(when, {
        "when": when,
        "method": method,
        "args": [...arguments].slice(2)
      });
    }
  };
};

@@ -265,30 +265,8 @@
 = 0;
-%0A  let thingToDo = %5B%5D;
 %0A%0A  
@@ -433,22 +433,29 @@
 g = 
-thingToDo.pop(
+actions.get(tickCount
 );%0A 
@@ -611,16 +611,16 @@
    %7D),%0A%0A
+
     %22at%22
@@ -650,130 +650,8 @@
 ) %7B%0A
-      thingToDo.push(%7B%0A        %22when%22: when,%0A        %22method%22: method,%0A        %22args%22: %5B...arguments%5D.slice(2)%0A      %7D);%0A%0A
     

Remove unneeded thingToDo array