Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a valid recursive function?

I found a recursive expression in a library very confused. The code is here : https://github.com/tappleby/redux-batched-subscribe/blob/master/src/index.js#L22

export function batchedSubscribe(batch) {
  if (typeof batch !== 'function') {
    throw new Error('Expected batch to be a function.');
  }

  const listeners = [];

  function subscribe(listener) {
    listeners.push(listener);

    return function unsubscribe() {
      const index = listeners.indexOf(listener);
      listeners.splice(index, 1);
    };
  }

  function notifyListenersBatched() {
    batch(() => listeners.slice().forEach(listener => listener()));
  }

  return next => (...args) => {
    const store = next(...args);
    const subscribeImmediate = store.subscribe;

    function dispatch(...dispatchArgs) {
      const res = store.dispatch(...dispatchArgs);
      notifyListenersBatched();
      return res;
    }

    return {
      ...store,
      dispatch,
      subscribe,
      subscribeImmediate
    };
  };
}

Specifically this part:

return next => (...args) => {
  const store = next(...args);
  const subscribeImmediate = store.subscribe;

  function dispatch(...dispatchArgs) {
    const res = store.dispatch(...dispatchArgs);
    notifyListenersBatched();
    return res;
  }

  return {
    ...store,
    dispatch,
    subscribe,
    subscribeImmediate
  };
};

How is this not infinite recursion?

like image 710
Story Maple Avatar asked Jun 04 '26 18:06

Story Maple


1 Answers

How is this not infinite recursion?

There is absolutely no recursion here. The syntax next => (...args) => … does not translate to

return function next(...args) {
    const store = next(...args);
    …

but rather to

return function(next) {
    return function(...args) {
        const store = next(...args);
        …

So unless the caller of that function does something weird like var f = batchedSubscribe(…); f(f)(f)…;, it won't call itself.

like image 136
Bergi Avatar answered Jun 06 '26 08:06

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!