Skip to content

Instantly share code, notes, and snippets.

@marco-martins
Forked from jspdown/$memoize
Created March 3, 2016 10:00
Show Gist options
  • Save marco-martins/3281eda2b7de8a4fe4fe to your computer and use it in GitHub Desktop.
Save marco-martins/3281eda2b7de8a4fe4fe 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