UNPKG

@sanity/desk-tool

Version:

Tool for managing all sorts of content in a structured manner

106 lines (105 loc) 3.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TwoEndedArray = void 0; function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /** * The two ended array supports pushing both at the beginning and * at the end while preserving indicies. */ class TwoEndedArray { constructor() { _defineProperty(this, "_postive", []); _defineProperty(this, "_negative", []); } addToEnd(elem) { elem.index = this._postive.length; this._postive.push(elem); } addToBeginning(elem) { // Prefer to place things at the positive side if possible. if (this.length == 0) { this.addToEnd(elem); return; } elem.index = -(this._negative.length + 1); this._negative.push(elem); } mergeAtEnd(value, merger) { if (this.length === 0) { this.addToEnd(value); return; } var idx = this.lastIdx; var result = merger(this.get(idx), value); if (Array.isArray(result)) { this.set(idx, result[0]); this.addToEnd(result[1]); } else { this.set(idx, result); } } mergeAtBeginning(value, merger) { if (this.length === 0) { this.addToEnd(value); return; } var idx = this.firstIdx; var result = merger(value, this.get(idx)); if (Array.isArray(result)) { this.set(idx, result[1]); this.addToBeginning(result[0]); } else { this.set(idx, result); } } removeFromEnd() { if (this._postive.length === 0) { this._negative.shift(); } else { this._postive.pop(); } } has(idx) { if (idx >= 0) { return idx < this._postive.length; } return -(idx + 1) < this._negative.length; } get(idx) { if (idx >= 0) { return this._postive[idx]; } return this._negative[-(idx + 1)]; } set(idx, value) { if (idx >= 0) { value.index = idx; this._postive[idx] = value; } else { value.index = idx; this._negative[-(idx + 1)] = value; } } get lastIdx() { // Note: This also works correctly when _positive is empty (it returns -1) return this._postive.length - 1; } get last() { return this.get(this.lastIdx); } get firstIdx() { // Note: This also works correctly when _negative is empty (it returns 0) return -this._negative.length; } get first() { return this.get(this.firstIdx); } get length() { return this._postive.length + this._negative.length; } } exports.TwoEndedArray = TwoEndedArray;