Last active
December 20, 2015 09:09
-
-
Save keesey/6106226 to your computer and use it in GitHub Desktop.
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
module aop | |
{ | |
export function after<R>( | |
f: (...args: any[]) => R, | |
advice: (result: R, ...args: any[]) => any | |
): (...args: any[]) => R | |
{ | |
return function() | |
{ | |
var result = f.apply(this, arguments), | |
adviceArgs: any[] = [ result ], | |
i = 0, | |
n = arguments.length; | |
for (; i < n; ++i) | |
{ | |
adviceArgs.push(arguments[i]); | |
} | |
advice.apply(this, adviceArgs); | |
return result; | |
}; | |
} | |
export function before<R>( | |
f: (...args: any[]) => R, | |
advice: (...args: any[]) => any | |
): (...args: any[]) => R | |
{ | |
return function() | |
{ | |
advice.apply(this, arguments); | |
return f.apply(this, arguments); | |
}; | |
} | |
/** | |
* Wraps a single-argument function and caches its results. | |
* | |
* @param f | |
* A function that takes a single input argument and yields some kind of output. | |
* @param keyer | |
* A function that translates input arguments to unique string keys. | |
* If omitted, <code>String()</code> is used. | |
* If the input object causes tthis function to yield <code>null</code> or an empty string, | |
* the result will not be cached. | |
* @returns | |
* A function that behaves like <code>f</code> but caches results for quick retrieval. | |
* @see useID() | |
* @author Mike Keesey | |
*/ | |
export function cache<I, O>(f: (input: I) => O, keyer?: (input: I) => string): (input: I) => O | |
{ | |
var cache: { [key: string]: O; } = {}; | |
if (typeof keyer !== 'function') | |
{ | |
keyer = (input: I) => String(input); | |
} | |
return function(input: I) | |
{ | |
var key = keyer(input); | |
if (typeof key !== 'string' || key.length === 0) | |
{ | |
return f(input); | |
} | |
var output = cache[key]; | |
if (output === undefined) | |
{ | |
output = cache[key] = f(input); | |
} | |
return output; | |
}; | |
} | |
export function filter<R>( | |
f: (...args: any[]) => R, | |
advice: (result: R) => R | |
): (...args: any[]) => R | |
{ | |
return function() | |
{ | |
return advice.call(this, f.apply(this, arguments)); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment