function add()

in src/utils/json-patch.js [119:153]


function add(document, path, value) {
  let parent = null;
  let node = document;
  let lastToken = null;

  // walk through the pointer, keeping track of the parent token/node
  for (const { node: next, token } of walk(document, path)) {
    parent = node;
    node = next;
    lastToken = token;
  }

  // if there is no parent, the pointer is invalid since we cannot add anything
  // in that scenario
  if (!parent) {
    throw new InvalidPointerError(path);
  }

  if (Array.isArray(parent)) {
    // if the pointer references an index to an array, try to add the new value
    // into the array
    try {
      const index = parseArrayIndex(lastToken, parent);
      parent.splice(index, 0, value);
    } catch (e) {
      throw new InvalidPointerError(path);
    }
  } else {
    // otherwise, either overwrite the existing item or add a new one if it did
    // not already exist
    Object.assign(parent, { [lastToken]: value });
  }

  return document;
}