/**
 * 节流处理
 * @param fn 需节流方法
 * @param wait 等待时间
 */
export default (fn, wait = 2000, options = {leading : true, trailing : false}) => {
    let timeout, context, args;
    let previous = 0;

    const later = () => {
        previous = !options.leading ? 0 : Date.now();
        timeout = null;
        fn.apply(context, args);
        if (!timeout) context = args = null;
    };

    const throttled = function(...params) {
        const now = new Date().getTime();
        if (!previous && !options.leading) previous = now;
        
        const remaining = wait - (now - previous);
        context = this;
        args = params;

        if (remaining <= 0 || remaining > wait) {
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            previous = now;
            fn.apply(context, args);
            if (!timeout) context = args = null;
        } else if (!timeout && options.trailing) {
            timeout = setTimeout(later, remaining);
        }
    };

    return throttled;
}