import { Set } from 'immutable';
import {
  pathToRef,
  refToPath,
  isRef
} from './utils';

const joinRefs = (node, path = [], options) => {
  const {
    vistedPaths,
    state,
    lastState,
    lastTree,
    refs,
    force = false
  } = options;

  if (!force && state.getIn(path) === lastState.getIn(path)) {
    return lastTree.getIn(path);
  }

  if (lastState.size) {
    vistedPaths.push(pathToRef(path));
  }

  if (Set.isSet(node)) {
    return node;
  }

  if (isRef(node)) {
    const keyPath = refToPath(node);
    if (refs[node]) {
      refs[node].paths = refs[node].paths.add(pathToRef(path))
      return refs[node].result;
    }

    const result = joinRefs(state.getIn(keyPath), keyPath, options);
    refs[node] = { key: keyPath, paths: Set.of(pathToRef(path)), result };
    return result;
  }

  if (typeof node === 'object') {
    return node.map((d, k) => {
      return joinRefs(d, [...path, k], options);
    });
  }

  return node;
};

const joinDependencies = ({state, key, options}) => {
  const ref = options.refs[key];
  if (!ref) {
    return state;
  }

  ref.result = joinRefs(state.getIn(ref.key), ref.key, {
    ...options,
    force: true
  });

  return ref.paths.reduce((result, pathKey) => {
    const path = refToPath(pathKey);
    return joinDependencies({
      state: result.setIn(path, ref.result),
      key: pathToRef(path.slice(0, -1)),
      options
    });
  }, state);
};

export default options => {
  const state = joinRefs(options.state, [], options);
  return options.vistedPaths.reduce((result, path) => {
    return joinDependencies({
      state: result,
      key: path,
      options
    });
  }, state);
};

@@ -88,21 +88,24 @@
 tils';%0A%0A
-const
+function
  joinRef
@@ -105,19 +105,16 @@
 joinRefs
- = 
 (node, p
@@ -131,19 +131,16 @@
 options)
- =%3E
  %7B%0A  con
@@ -958,21 +958,24 @@
 de;%0A%7D;%0A%0A
-const
+function
  joinDep
@@ -983,19 +983,16 @@
 ndencies
- = 
 (%7Bstate,
@@ -1006,19 +1006,16 @@
 ptions%7D)
- =%3E
  %7B%0A  con
@@ -1420,79 +1420,42 @@
 %7D;%0A%0A
-export default options =%3E %7B%0A  const state = joinRefs(options.
+function updateDependencies(
 state,
- %5B%5D,
  opt
@@ -1459,17 +1459,18 @@
 options)
-;
+ %7B
 %0A  retur
@@ -1516,29 +1516,22 @@
 ath) =%3E 
-%7B
+(
 %0A    
-return 
 joinDepe
@@ -1595,30 +1595,160 @@
 tions%0A    %7D)
-;%0A  %7D, state
+%0A  ), state);%0A%7D;%0A%0Aexport default options =%3E %7B%0A  const state = joinRefs(options.state, %5B%5D, options);%0A  return updateDependencies(state, options
 );%0A%7D;%0A

Extract extra function 'updateDependencies'