import isIdentical from '../Array/isIdentical';

/**
 * Memoizes the return value of a function for the given arguments
 * Currently it stores only the result for the last call, it's really simple, fast and also saves memory.
 * It's different to the lodash (underscore) implementation, because that uses only the first
 * argument of the memoized function by default, and provides a way for advanced cache resolving.
 * A possible improvement can be in the future the possibility of optionally using a "map"
 * to store the results for every different input value (or limited number).
 * @param {function} fn
 * @returns {function(...[*]=)}
 * @throws TypeError If the given argument is not a function
 */
export const memoize = fn => {
    if (typeof fn !== 'function') {
        throw new TypeError('Memoize accepts only function as argument!');
    }
    let prevArgs = [];
    let value = undefined;
    return (...args) => {
        if (!isIdentical(args, prevArgs)) {
            value = fn(...args);
            prevArgs = args;
        }
        return value;
    };
};

export default memoize;
