@graffy/common
Version:
Common libraries that used by various Graffy modules.
72 lines (56 loc) • 2.92 kB
JavaScript
import _extends from "@babel/runtime/helpers/esm/extends";
function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
import { find, isBranch } from '../node';
export default function add(base, diff) {
var changed = false;
var index = 0;
for (var _iterator = _createForOfIteratorHelperLoose(diff), _step; !(_step = _iterator()).done;) {
var node = _step.value;
var cmp = compare(node);
var nodeIsBranch = isBranch(node);
index = find(base, cmp, index);
var item = base[index];
var itemIsBranch = isBranch(item);
if (!item || cmp(item)) {
// This node doesn't exist in the base, insert it.
base.splice(index, 0, clone(node));
changed = true;
continue;
}
if (nodeIsBranch && itemIsBranch) {
changed = add(item.children, node.children) || changed;
} else if (nodeIsBranch || itemIsBranch) {
throw new Error('add.branch_leaf_mismatch');
} else {
item.value += node.value;
} // If this item was decremented to zero, remove it.
var size = itemIsBranch ? item.children.length : item.value;
if (!size) {
base.splice(index, 1);
changed = true;
}
}
return changed;
}
function compare(node) {
return function (item) {
var v = compareValue(item.key, node.key) || compareValue(item.end, node.end) || compareValue(item.limit, node.limit);
return v;
};
}
function compareValue(a, b) {
if (a === b) return 0;
return a < b ? -1 : 1;
}
/*
We clone to ensure that the original query (passed as diff) never gets modified, even after successive adds.
*/
function clone(node) {
var copy = _extends({}, node);
if (node.children) copy.children = node.children.map(function (child) {
return clone(child);
});
return copy;
}