function buildView()

in src/compat/database/list/changes.ts [43:90]


function buildView(current, action) {
  const { payload, prevKey, key } = action;
  const currentKeyPosition = positionFor(current, key);
  const afterPreviousKeyPosition = positionAfter(current, prevKey);
  switch (action.type) {
    case 'value':
      if (action.payload && action.payload.exists()) {
        let prevKey = null;
        action.payload.forEach(payload => {
          const action = { payload, type: 'value', prevKey, key: payload.key };
          prevKey = payload.key;
          current = [...current, action];
          return false;
        });
      }
      return current;
    case 'child_added':
      if (currentKeyPosition > -1) {
        // check that the previouskey is what we expect, else reorder
        const previous = current[currentKeyPosition - 1];
        if ((previous && previous.key || null) !== prevKey) {
          current = current.filter(x => x.payload.key !== payload.key);
          current.splice(afterPreviousKeyPosition, 0, action);
        }
      } else if (prevKey == null) {
        return [action, ...current];
      } else {
        current = current.slice();
        current.splice(afterPreviousKeyPosition, 0, action);
      }
      return current;
    case 'child_removed':
      return current.filter(x => x.payload.key !== payload.key);
    case 'child_changed':
      return current.map(x => x.payload.key === key ? action : x);
    case 'child_moved':
      if (currentKeyPosition > -1) {
        const data = current.splice(currentKeyPosition, 1)[0];
        current = current.slice();
        current.splice(afterPreviousKeyPosition, 0, data);
        return current;
      }
      return current;
    // default will also remove null results
    default:
      return current;
  }
}