{"size": 2036, "ext": "js", "max_stars_repo_path": "getInstance.js", "max_stars_repo_name": "ircam-jstools/node-libpd", "max_stars_repo_stars_event_min_datetime": "2018-12-14T13:40:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-29T05:47:30.000Z", "max_issues_repo_path": "getInstance.js", "max_issues_repo_name": "b-ma/node-libpd", "max_issues_repo_issues_event_min_datetime": "2019-01-08T19:36:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-11T17:13:51.000Z", "max_forks_repo_path": "getInstance.js", "max_forks_repo_name": "b-ma/node-libpd", "max_forks_repo_forks_event_min_datetime": "2018-12-17T04:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-01T14:58:16.000Z"}
{"max_stars_count": 12, "max_issues_count": 2, "max_forks_count": 3, "avg_line_length": 26.4415584416, "max_line_length": 90, "alphanum_fraction": 0.6345776031}
const nodelibpd = require('bindings')('nodelibpd');

function getInstance() {
  // singleton
  const pd = new nodelibpd.NodePd();

  let listenersChannelMap = {};

  // global receive function that dispatch to subscriptions
  const dispatch = function(channel, value) {
    const listeners = listenersChannelMap[channel];

    // as a message can still arrive from pd after `unsubscribe` have been
    // called because of the inter-processs queue, we have to check that
    // listeners still exists
    if (listeners && listeners.length > 0) {
      listeners.forEach(function(listener) { listener(value); });
    }
  };

  let initialized = false;

  pd.init = (options = {}) => {
    if (!initialized) {
      initialized = pd._initialize(options, dispatch);
    }

    return initialized;
  }

  // allow both syntax:
  // pd.openPatch(path.join(patchesPath, 'my-patch.pd')); // js friendly
  // pd.openPatch('my-patch.pd', patchesPath); // pd native API for backward compatibility
  pd.openPatch = function(...args) {
    if (args.length === 1) {
      const filename = path.basename(args[0]);
      const dirname = path.dirname(args[0]);
      return pd._openPatch(filename, dirname);
    } else {
      const [filename, dirname] = args;
      return pd._openPatch(filename, dirname);
    }
  }

  pd.subscribe = function(channel, callback) {
    if (!listenersChannelMap[channel]) {
      listenersChannelMap[channel] = [];
      pd._subscribe(channel);
    }

    listenersChannelMap[channel].push(callback);
  }

  pd.unsubscribe = function(channel, callback = null) {
    const listeners = listenersChannelMap[channel];

    if (Array.isArray(listeners)) {
      if (callback !== null) {
        const index = listeners.indexOf(callback);

        if (index !== -1) {
          listeners.splice(index, 1);
        }
      }

      if (callback === null || listeners.length === 0) {
        pd._unsubscribe(channel);
        delete listenersChannelMap[channel];
      }
    }
  }

  return pd
}

module.exports = getInstance;
