对方法进行反跳,但继续合并和记忆参数

cou*_*011 2 javascript function memoization debouncing

我有一个这样定义的方法

updateHook(obj) {
  // update the item
}
// https://www.npmjs.com/package/throttle-debounce
const update = debounce(updateHook, 2000);
Run Code Online (Sandbox Code Playgroud)

我想合并所有参数并在 2 秒内多次调用该方法时调用它一次,例如

update({ name: 'abc' }); // first call
update({ city: 'def' }); // second call
update({ cell: 123 }); // third call
.... ~2 seconds
// should send one call to update with all the params merged like
update({ name: 'abc', city: 'def', cell: 123 });
Run Code Online (Sandbox Code Playgroud)

注意:不需要使用 debounce,要求是我只想调用具有合并参数的方法(如果该方法在 2 秒的时间段内被多次调用)。

Yos*_*shi 5

您可以编写自己的高阶函数,使用合并的参数调用给定的函数(请参见merge下面的示例)。

这里最大的问题是(IMO)该merge函数对将传递哪些参数做出了非常强烈的假设。
您需要自己判断是否需要高度通用或非常具体的实现。

const {debounce} = throttleDebounce;

const merge = (fn) => {
    let merge = {};

    return (obj) => {
        merge = {...merge, ...obj};
        fn(merge);
    };
};

const updateHook = (obj) => {
    console.log(obj);
}

const update = merge(debounce(2000, updateHook));

update({ name: 'abc' });
update({ city: 'def' });
update({ cell: 123 });
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/throttle-debounce@3.0.1/umd/index.js"></script>
Run Code Online (Sandbox Code Playgroud)


另一个问题是可能需要在某个时候重置合并功能。如果这与去抖超时相关,那么您可能需要一个专门的去抖工厂

const {debounce} = throttleDebounce;

const updateHook = (obj) => {
    console.log(obj);
}

const mergedDebounce = (delay, callback) => {
    let merged = {};

    const debounced = debounce(delay, () => {
        callback(merged);
        merged = {};
    });

    return (obj) => {
        merged = {...merged, ...obj};
        debounced(merged);
    };
};

const update = mergedDebounce(2000, updateHook);

update({ name: 'abc' }); // first call
update({ city: 'def' }); // second call
update({ cell: 123 }); // third call

setTimeout(() => {
    update({ foo: 42 }); // fourth call
}, 2500);
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/throttle-debounce@3.0.1/umd/index.js"></script>
Run Code Online (Sandbox Code Playgroud)