'use strict';

var Immutable = require('immutable');
var path = require('./path');

var mapPatch = function(map, patches) {
  return map.withMutations(function(updateMap) {
    patches.map(function(patch){
      var pathArray = patch.get('path').split('/').slice(1).map(path.unescape);
      var op = patch.get('op');

      if(op === 'add' || op === 'replace'){
        updateMap.setIn(pathArray, patch.get('value'));
      }
      else if(op === 'remove'){
        updateMap.removeIn(pathArray)
      }
    });
  });
};

var sequencePatch = function (sequence, patches) {
  return sequence.withMutations(function (updateSeq) {
    patches.map(function(patch){
      var pathArray = patch.get('path').split('/').slice(1).map(toInt);
      var op = patch.get('op');

      if(op === 'add' || op === 'replace'){
        updateSeq.setIn(pathArray, patch.get('value'));
      }
      else if(op === 'remove'){
        updateSeq.removeIn(pathArray)
      }
    });
  });
};

var toInt = function(n) {
  return parseInt(n);
};

module.exports = function(immutableObject, patches){
  if(patches.count() === 0){ return immutableObject; }

  if(Immutable.Iterable.isKeyed(immutableObject)){
    return mapPatch(immutableObject, patches);
  }
  else{
    return sequencePatch(immutableObject, patches);
  }
};
@@ -992,22 +992,25 @@
 (n) %7B%0A  
-return
+var int =
  parseIn
@@ -1015,16 +1015,47 @@
 Int(n);%0A
+  return isNaN(int) ? n : int;%0A
 %7D;%0A%0Amodu

fix bug patch in maps nested in sequences