Last active
May 11, 2016 21:15
-
-
Save jspdown/9474347486afc3113a10 to your computer and use it in GitHub Desktop.
Simple "in-function" memoize for AngularJs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function (angular) { | |
'use strict'; | |
angular | |
.module('ng-utils', []) | |
.factory('$memoize', memoize); | |
function memoize() { | |
return function (target) { | |
return function () { | |
var args = Array.prototype.slice.call(arguments), | |
hash = '', | |
argsLength = args.length, | |
current = null; | |
if (typeof target.memoize === 'undefined') | |
target.memoize = {}; | |
while (argsLength--) { | |
current = args[argsLength]; | |
if (current === Object(current)) { | |
hash += JSON.Stringify(current) | |
} else { | |
hash += current; | |
} | |
} | |
if (!(hash in target.memoize)) | |
target.memoize[hash] = target.apply(this, args); | |
return target.memoize[hash]; | |
}; | |
}; | |
} | |
})(angular); | |
/* | |
* USAGE: | |
* | |
* angular | |
* .module('example', ['ng-utils']) | |
* .factor('Search', ['$http', '$memoize', function ($http, $memoize) { | |
* | |
* return $memoize(search); | |
* | |
* function search(name) { | |
* return $http.get(config.endpoint, { | |
* params: { keyword: keywords } | |
* }); | |
* } | |
* }); | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment