{"size": 912, "ext": "js", "max_stars_repo_path": "src/utils/injectRefStream.js", "max_stars_repo_name": "rerx/rerx", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/injectRefStream.js", "max_issues_repo_name": "rerx/rerx", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/injectRefStream.js", "max_forks_repo_name": "rerx/rerx", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.243902439, "max_line_length": 68, "alphanum_fraction": 0.5274122807}
import { BehaviorSubject } from 'rxjs/Rx';

export function injectRefStream(component, refStreamName = 'ref$') {
  const refs$ = new BehaviorSubject(component.refs);
  const emptyArray = [];
  const cache = {};

  component[refStreamName] = refs$;

  return new Proxy({}, {
    get(target, name) {
      if (name.charAt(name.length - 1) === '$') {
        const refName = name.substr(0, name.length - 1);
        const cachedStream = cache[refName];

        if (cachedStream) {
          return cachedStream;
        }

        const ref$ = refs$.map(refs => {
          const ref = refs[refName];
          if (ref) {
            return [ref];
          }

          return emptyArray;
        });

        cache[refName] = ref$;
        return ref$;
      }

      return function refHandler(ref) {
        const { refs } = component;
        refs[name] = ref;
        refs$.next(refs);
      }
    }
  });
}
