Skip to content

Instantly share code, notes, and snippets.

@jspdown
Last active May 11, 2016 21:15
Show Gist options
  • Save jspdown/9474347486afc3113a10 to your computer and use it in GitHub Desktop.
Save jspdown/9474347486afc3113a10 to your computer and use it in GitHub Desktop.
Simple "in-function" memoize for AngularJs
;(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