Skip to content

Instantly share code, notes, and snippets.

@idrm
Created November 26, 2014 14:28
Show Gist options
  • Save idrm/a91dc7a4cfb381dca24e to your computer and use it in GitHub Desktop.
Save idrm/a91dc7a4cfb381dca24e to your computer and use it in GitHub Desktop.
Create imoment, an immutable version of moment.js.
;(function() {
var moment = this.moment;
var IMoment = function(m) {
this._m = m;
};
var m = moment();
var mproto = Object.getPrototypeOf(m);
for (var name in mproto) {
(function(name) {
var fn = m[name];
IMoment.prototype[name] = function () {
var m = this._m;
if (arguments.length > 0 || (name == 'utc' || name == 'local'))
m = m.clone();
var args = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg instanceof IMoment)
args.push(arg._m);
else
args.push(arg);
}
var r = fn.apply(m, args);
if (moment.isMoment(r))
return new IMoment(r);
else
return r;
}
})(name);
}
this.imoment = function() {
return new IMoment(moment(arguments));
};
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment