function mapFields()

in packages/sqrl/src/ast/Ast.ts [113:140]


function mapFields(source: Ast, fields: string[], callback: (Ast) => Ast): Ast {
  /***
   * This is responsible for running the callback on all the children fields. It's smart in that
   * if no changes are made it returns the source object.
   */
  let changed = false;
  const out = {};
  fields.forEach((field) => {
    if (source.hasOwnProperty(field) && source[field] !== null) {
      if (Array.isArray(source[field])) {
        out[field] = source[field].map((entry) => {
          const rv = mapAst(entry, callback);
          changed = changed || rv !== entry;
          return rv;
        });
      } else {
        out[field] = mapAst(source[field], callback);
        changed = changed || out[field] !== source[field];
      }
    }
  });

  if (changed) {
    return Object.assign({}, source, out);
  } else {
    return source;
  }
}