Scripts (JS) Snippet: collection functions and helpers

These functions make writing scripts a lot quicker...

/**
 * Return an array of the results of running func on each item in coll e.g.
 *   map(DOpus.vars, function(v, i) {
 *     return v + '=' + v.value;
 *   }
 */
function map(coll, func) {
  var res = [];
  for (var e = new Enumerator(coll), idx = 0, item = e.item(); !e.atEnd(); e.moveNext(), idx += 1, item = e.item()) {
    res.push(func(item, idx));
  }
  return res;
}

/**
 * Get a property from each item e.g.
 *   extract(DOpus.listers, 'title')
 *   extract(clickData.func.sourcetab.selected, 'realpath')
 */
function extract(coll, prop) {
  return map(coll, function(v) {
    return v[prop];
  })
}

/**
 * Run func on each item in coll e.g.
 *   each(clickData.func.sourcetab.all, function(v, i) {
 *     DOpus.Output((v.is_dir ? 'D ' : '  ') + v.display_name);
 *   }
 */
function each(coll, func) {
  map(coll, func);
  return coll;
}

/**
 * Get a descriptive property for an object.
 */
function info(obj) {
  return obj.title || obj.name || obj.style || obj.fontname || String(obj);
}

/**
 * Write a collection of items to the script log.
 */
function list(coll) {
  each(coll, function(v, i) {
    DOpus.Output(i + ': ' + info(v));
  });
}

/**
 * Return string value path with quotes if all is true or if the path contains a space
 */
function quotePath(path, all) {
  path = String(path);
  all = typeof all === "boolean" ? all : false;
  return all || path.indexOf(' ') !== -1 ? ('"' + path + '"') : path;
}
1 Like