Skip to content

Commit

Permalink
Merge pull request #39 from caseywebdev/master
Browse files Browse the repository at this point in the history
Drastically improve perf with memoize
  • Loading branch information
timrwood committed Oct 17, 2013
2 parents 27a8858 + 803d2e2 commit 26763da
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions moment-timezone.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@
this.timeRule = +timeRule;
this.offset = parseMinutes(offset);
this.letters = letters || '';
this.date = memoize(this.date);
this.weekdayAfter = memoize(this.weekdayAfter);
this.lastWeekday = memoize(this.lastWeekday);
}

Rule.prototype = {
Expand Down Expand Up @@ -135,6 +138,7 @@
function RuleSet (name) {
this.name = name;
this.rules = [];
this.lastYearRule = memoize(this.lastYearRule);
}

RuleSet.prototype = {
Expand Down Expand Up @@ -252,6 +256,7 @@
this.offset = parseMinutes(offset);
this.ruleSet = ruleSet;
this.letters = letters;
this.lastRule = memoize(this.lastRule);

for (i = 0; i < untilArray.length; i++) {
untilArray[i] = +untilArray[i];
Expand All @@ -265,10 +270,7 @@
},

lastRule : function () {
if (!this._lastRule) {
this._lastRule = this.rule(this.until);
}
return this._lastRule;
return this.rule(this.until);
},

format : function (rule) {
Expand All @@ -288,6 +290,9 @@
this.name = normalizeName(name);
this.displayName = name;
this.zones = [];
this.zoneAndRule = memoize(this.zoneAndRule, function (mom) {
return +mom;
});
}

ZoneSet.prototype = {
Expand Down Expand Up @@ -328,6 +333,16 @@
Global Methods
************************************/

function memoize (fn, keyFn) {
var cache = {};
return function (first) {
var key = keyFn ? keyFn.apply(this, arguments) : first;
return key in cache ?
cache[key] :
(cache[key] = fn.apply(this, arguments));
};
}

function addRules (rules) {
var i, j, rule;
for (i in rules) {
Expand Down

0 comments on commit 26763da

Please sign in to comment.