Browse Source

KERNEL-14012 feat: core/structure文件夹

es6
zsmj 2 years ago
parent
commit
bceffd1a0a
  1. 572
      src/core/structure/aes.js
  2. 33
      src/core/structure/aspect.js
  3. 56
      src/core/structure/base64.js
  4. 47
      src/core/structure/cache.js
  5. 192
      src/core/structure/cellSizeAndPositionManager.js
  6. 66
      src/core/structure/heap.js
  7. 44
      src/core/structure/index.js
  8. 58
      src/core/structure/linkedHashMap.js
  9. 38
      src/core/structure/lru.js
  10. 105
      src/core/structure/prefixIntervalTree.js
  11. 93
      src/core/structure/queue.js
  12. 79
      src/core/structure/sectionManager.js
  13. 578
      src/core/structure/tree.js
  14. 49
      src/core/structure/vector.js

572
src/core/structure/aes.js

File diff suppressed because it is too large Load Diff

33
src/core/structure/aspect.js

@ -1,15 +1,14 @@
!(function () {
function aspect (type) {
function _aspect(type) {
return function (target, methodName, advice) {
var exist = target[methodName],
let exist = target[methodName],
dispatcher;
if (!exist || exist.target != target) {
dispatcher = target[methodName] = function () {
// before methods
var beforeArr = dispatcher.before;
var args = arguments, next;
for (var l = beforeArr.length; l--;) {
let beforeArr = dispatcher.before;
let args = arguments, next;
for (let l = beforeArr.length; l--;) {
next = beforeArr[l].advice.apply(this, args);
if (next === false) {
return false;
@ -17,10 +16,10 @@
args = next || args;
}
// target method
var rs = dispatcher.method.apply(this, args);
let rs = dispatcher.method.apply(this, args);
// after methods
var afterArr = dispatcher.after;
for (var i = 0, ii = afterArr.length; i < ii; i++) {
let afterArr = dispatcher.after;
for (let i = 0, ii = afterArr.length; i < ii; i++) {
next = afterArr[i].advice.call(this, rs, args);
if (rs === false) {
return false;
@ -39,13 +38,13 @@
dispatcher.target = target;
}
var aspectArr = (dispatcher || exist)[type];
var obj = {
let aspectArr = (dispatcher || exist)[type];
let obj = {
advice: advice,
_index: aspectArr.length,
remove: function () {
aspectArr.splice(this._index, 1);
}
},
};
aspectArr.push(obj);
@ -53,11 +52,7 @@
};
}
BI.aspect = {
before: aspect("before"),
after: aspect("after")
export const aspect = {
before: _aspect("before"),
after: _aspect("after"),
};
return BI.aspect;
})();

56
src/core/structure/base64.js

@ -1,17 +1,14 @@
!(function () {
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// private method for UTF-8 encoding
var _utf8_encode = function (string) {
const _utf8_encode = function (string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
let utftext = "";
for (var n = 0; n < string.length; n++) {
for (let n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
const c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
@ -30,10 +27,10 @@
};
// private method for UTF-8 decoding
var _utf8_decode = function (utftext) {
var string = "";
var i = 0;
var c = 0, c3 = 0, c2 = 0;
const _utf8_decode = function (utftext) {
let string = "";
let i = 0;
let c = 0, c3 = 0, c2 = 0;
while (i < utftext.length) {
@ -57,12 +54,15 @@
return string;
};
BI._.extend(BI, {
encode: function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
/**
* base64 encode
* @param input
* @returns {string}
*/
export function encode(input) {
let output = "";
let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
let i = 0;
input = _utf8_encode(input);
@ -88,14 +88,18 @@
}
return output;
},
}
// public method for decoding
decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
/**
* base64 decode
* @param input
* @returns {string}
*/
export function decode(input) {
let output = "";
let chr1, chr2, chr3;
let enc1, enc2, enc3, enc4;
let i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
@ -126,5 +130,3 @@
return output;
}
});
})();

47
src/core/structure/cache.js

@ -1,43 +1,42 @@
BI.Cache = {
export const Cache = {
_prefix: "bi",
setUsername: function (username) {
localStorage.setItem(BI.Cache._prefix + ".username", (username + "" || "").toUpperCase());
localStorage.setItem(Cache._prefix + ".username", (username + "" || "").toUpperCase());
},
getUsername: function () {
return localStorage.getItem(BI.Cache._prefix + ".username") || "";
return localStorage.getItem(Cache._prefix + ".username") || "";
},
_getKeyPrefix: function () {
return BI.Cache.getUsername() + "." + BI.Cache._prefix + ".";
return Cache.getUsername() + "." + Cache._prefix + ".";
},
_generateKey: function (key) {
return BI.Cache._getKeyPrefix() + (key || "");
return Cache._getKeyPrefix() + (key || "");
},
getItem: function (key) {
return localStorage.getItem(BI.Cache._generateKey(key));
return localStorage.getItem(Cache._generateKey(key));
},
setItem: function (key, value) {
localStorage.setItem(BI.Cache._generateKey(key), value);
localStorage.setItem(Cache._generateKey(key), value);
},
removeItem: function (key) {
localStorage.removeItem(BI.Cache._generateKey(key));
localStorage.removeItem(Cache._generateKey(key));
},
clear: function () {
for (var i = localStorage.length; i >= 0; i--) {
var key = localStorage.key(i);
for (let i = localStorage.length; i >= 0; i--) {
const key = localStorage.key(i);
if (key) {
if (key.indexOf(BI.Cache._getKeyPrefix()) === 0) {
if (key.indexOf(Cache._getKeyPrefix()) === 0) {
localStorage.removeItem(key);
}
}
}
},
keys: function () {
var result = [];
for (var i = localStorage.length; i >= 0; i--) {
var key = localStorage.key(i);
const result = [];
for (let i = localStorage.length; i >= 0; i--) {
const key = localStorage.key(i);
if (key) {
var prefix = BI.Cache._getKeyPrefix();
const prefix = Cache._getKeyPrefix();
if (key.indexOf(prefix) === 0) {
result[result.length] = key.substring(prefix.length);
}
@ -47,10 +46,10 @@ BI.Cache = {
},
addCookie: function (name, value, path, expiresHours) {
var cookieString = name + "=" + encodeURI(value);
let cookieString = name + "=" + encodeURI(value);
// 判断是否设置过期时间
if (expiresHours && expiresHours > 0) {
var date = new Date();
const date = new Date();
// expires是标准GMT格式时间,应该使用时间戳作为起始时间
date.setTime(date.getTime() + expiresHours * 3600 * 1000);
cookieString = cookieString + "; expires=" + date.toUTCString();
@ -61,17 +60,19 @@ BI.Cache = {
document.cookie = cookieString;
},
getCookie: function (name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg)) {return decodeURI(arr[2]);}
let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg)) {
return decodeURI(arr[2]);
}
return null;
},
deleteCookie: function (name, path) {
var date = new Date();
const date = new Date();
date.setTime(date.getTime() - 10000);
var cookieString = name + "=v; expires=" + date.toUTCString();
let cookieString = name + "=v; expires=" + date.toUTCString();
if (path) {
cookieString = cookieString + "; path=" + path;
}
document.cookie = cookieString;
}
},
};

192
src/core/structure/cellSizeAndPositionManager.js

@ -1,40 +1,40 @@
BI.CellSizeAndPositionManager = function (cellCount, cellSizeGetter, estimatedCellSize) {
export class CellSizeAndPositionManager {
constructor(cellCount, cellSizeGetter, estimatedCellSize) {
this._cellSizeGetter = cellSizeGetter;
this._cellCount = cellCount;
this._estimatedCellSize = estimatedCellSize;
this._cellSizeAndPositionData = {};
this._lastMeasuredIndex = -1;
};
}
BI.CellSizeAndPositionManager.prototype = {
constructor: BI.CellSizeAndPositionManager,
configure: function (cellCount, estimatedCellSize) {
configure(cellCount, estimatedCellSize) {
this._cellCount = cellCount;
this._estimatedCellSize = estimatedCellSize;
},
}
getCellCount: function () {
getCellCount() {
return this._cellCount;
},
}
getEstimatedCellSize: function () {
getEstimatedCellSize() {
return this._estimatedCellSize;
},
}
getLastMeasuredIndex: function () {
getLastMeasuredIndex() {
return this._lastMeasuredIndex;
},
}
getSizeAndPositionOfCell: function (index) {
getSizeAndPositionOfCell(index) {
if (index < 0 || index >= this._cellCount) {
return;
}
if (index > this._lastMeasuredIndex) {
var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell();
var offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size;
const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell();
let offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size;
for (var i = this._lastMeasuredIndex + 1; i <= index; i++) {
var size = this._cellSizeGetter(i);
for (let i = this._lastMeasuredIndex + 1; i <= index; i++) {
const size = this._cellSizeGetter(i);
if (size == null || isNaN(size)) {
continue;
@ -42,7 +42,7 @@ BI.CellSizeAndPositionManager.prototype = {
this._cellSizeAndPositionData[i] = {
offset: offset,
size: size
size: size,
};
offset += size;
@ -51,28 +51,28 @@ BI.CellSizeAndPositionManager.prototype = {
this._lastMeasuredIndex = index;
}
return this._cellSizeAndPositionData[index];
},
}
getSizeAndPositionOfLastMeasuredCell: function () {
getSizeAndPositionOfLastMeasuredCell() {
return this._lastMeasuredIndex >= 0
? this._cellSizeAndPositionData[this._lastMeasuredIndex]
: {
offset: 0,
size: 0
size: 0,
};
},
}
getTotalSize: function () {
var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell();
getTotalSize() {
const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell();
return lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size + (this._cellCount - this._lastMeasuredIndex - 1) * this._estimatedCellSize;
},
}
getUpdatedOffsetForIndex: function (align, containerSize, currentOffset, targetIndex) {
var datum = this.getSizeAndPositionOfCell(targetIndex);
var maxOffset = datum.offset;
var minOffset = maxOffset - containerSize + datum.size;
getUpdatedOffsetForIndex(align, containerSize, currentOffset, targetIndex) {
const datum = this.getSizeAndPositionOfCell(targetIndex);
const maxOffset = datum.offset;
const minOffset = maxOffset - containerSize + datum.size;
var idealOffset;
let idealOffset;
switch (align) {
case "start":
@ -89,25 +89,25 @@ BI.CellSizeAndPositionManager.prototype = {
break;
}
var totalSize = this.getTotalSize();
const totalSize = this.getTotalSize();
return Math.max(0, Math.min(totalSize - containerSize, idealOffset));
},
}
getVisibleCellRange: function (containerSize, offset) {
var totalSize = this.getTotalSize();
getVisibleCellRange(containerSize, offset) {
const totalSize = this.getTotalSize();
if (totalSize === 0) {
return {};
}
var maxOffset = offset + containerSize;
var start = this._findNearestCell(offset);
const maxOffset = offset + containerSize;
const start = this._findNearestCell(offset);
var datum = this.getSizeAndPositionOfCell(start);
const datum = this.getSizeAndPositionOfCell(start);
offset = datum.offset + datum.size;
var stop = start;
let stop = start;
while (offset < maxOffset && stop < this._cellCount - 1) {
stop++;
@ -116,17 +116,17 @@ BI.CellSizeAndPositionManager.prototype = {
return {
start: start,
stop: stop
stop: stop,
};
},
}
resetCell: function (index) {
resetCell(index) {
this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, index - 1);
},
}
_binarySearch: function (high, low, offset) {
var middle;
var currentOffset;
_binarySearch(high, low, offset) {
let middle;
let currentOffset;
while (low <= high) {
middle = low + Math.floor((high - low) / 2);
@ -144,10 +144,10 @@ BI.CellSizeAndPositionManager.prototype = {
if (low > 0) {
return low - 1;
}
},
}
_exponentialSearch: function (index, offset) {
var interval = 1;
_exponentialSearch(index, offset) {
let interval = 1;
while (index < this._cellCount && this.getSizeAndPositionOfCell(index).offset < offset) {
index += interval;
@ -155,17 +155,17 @@ BI.CellSizeAndPositionManager.prototype = {
}
return this._binarySearch(Math.min(index, this._cellCount - 1), Math.floor(index / 2), offset);
},
}
_findNearestCell: function (offset) {
_findNearestCell(offset) {
if (isNaN(offset)) {
return;
}
offset = Math.max(0, offset);
var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell();
var lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex);
const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell();
const lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex);
if (lastMeasuredCellSizeAndPosition.offset >= offset) {
return this._binarySearch(lastMeasuredIndex, 0, offset);
@ -173,99 +173,97 @@ BI.CellSizeAndPositionManager.prototype = {
return this._exponentialSearch(lastMeasuredIndex, offset);
}
};
}
BI.ScalingCellSizeAndPositionManager = function (cellCount, cellSizeGetter, estimatedCellSize, maxScrollSize) {
this._cellSizeAndPositionManager = new BI.CellSizeAndPositionManager(cellCount, cellSizeGetter, estimatedCellSize);
export class ScalingCellSizeAndPositionManager {
constructor(cellCount, cellSizeGetter, estimatedCellSize, maxScrollSize) {
this._cellSizeAndPositionManager = new CellSizeAndPositionManager(cellCount, cellSizeGetter, estimatedCellSize);
this._maxScrollSize = maxScrollSize || 10000000;
};
BI.ScalingCellSizeAndPositionManager.prototype = {
constructor: BI.ScalingCellSizeAndPositionManager,
}
configure: function () {
configure() {
this._cellSizeAndPositionManager.configure.apply(this._cellSizeAndPositionManager, arguments);
},
}
getCellCount: function () {
getCellCount() {
return this._cellSizeAndPositionManager.getCellCount();
},
}
getEstimatedCellSize: function () {
getEstimatedCellSize() {
return this._cellSizeAndPositionManager.getEstimatedCellSize();
},
}
getLastMeasuredIndex: function () {
getLastMeasuredIndex() {
return this._cellSizeAndPositionManager.getLastMeasuredIndex();
},
}
getOffsetAdjustment: function (containerSize, offset) {
var totalSize = this._cellSizeAndPositionManager.getTotalSize();
var safeTotalSize = this.getTotalSize();
var offsetPercentage = this._getOffsetPercentage(containerSize, offset, safeTotalSize);
getOffsetAdjustment(containerSize, offset) {
const totalSize = this._cellSizeAndPositionManager.getTotalSize();
const safeTotalSize = this.getTotalSize();
const offsetPercentage = this._getOffsetPercentage(containerSize, offset, safeTotalSize);
return Math.round(offsetPercentage * (safeTotalSize - totalSize));
},
}
getSizeAndPositionOfCell: function (index) {
getSizeAndPositionOfCell(index) {
return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(index);
},
}
getSizeAndPositionOfLastMeasuredCell: function () {
getSizeAndPositionOfLastMeasuredCell() {
return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell();
},
}
getTotalSize: function () {
getTotalSize() {
return Math.min(this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize());
},
}
getUpdatedOffsetForIndex: function (align, containerSize, currentOffset, targetIndex) {
getUpdatedOffsetForIndex(align, containerSize, currentOffset, targetIndex) {
currentOffset = this._safeOffsetToOffset(containerSize, currentOffset);
var offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex(align, containerSize, currentOffset, targetIndex);
const offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex(align, containerSize, currentOffset, targetIndex);
return this._offsetToSafeOffset(containerSize, offset);
},
}
getVisibleCellRange: function (containerSize, offset) {
getVisibleCellRange(containerSize, offset) {
offset = this._safeOffsetToOffset(containerSize, offset);
return this._cellSizeAndPositionManager.getVisibleCellRange(containerSize, offset);
},
}
resetCell: function (index) {
resetCell(index) {
this._cellSizeAndPositionManager.resetCell(index);
},
}
_getOffsetPercentage: function (containerSize, offset, totalSize) {
_getOffsetPercentage(containerSize, offset, totalSize) {
return totalSize <= containerSize
? 0
: offset / (totalSize - containerSize);
},
}
_offsetToSafeOffset: function (containerSize, offset) {
var totalSize = this._cellSizeAndPositionManager.getTotalSize();
var safeTotalSize = this.getTotalSize();
_offsetToSafeOffset(containerSize, offset) {
const totalSize = this._cellSizeAndPositionManager.getTotalSize();
const safeTotalSize = this.getTotalSize();
if (totalSize === safeTotalSize) {
return offset;
}
var offsetPercentage = this._getOffsetPercentage(containerSize, offset, totalSize);
const offsetPercentage = this._getOffsetPercentage(containerSize, offset, totalSize);
return Math.round(offsetPercentage * (safeTotalSize - containerSize));
},
}
_safeOffsetToOffset: function (containerSize, offset) {
var totalSize = this._cellSizeAndPositionManager.getTotalSize();
var safeTotalSize = this.getTotalSize();
_safeOffsetToOffset(containerSize, offset) {
const totalSize = this._cellSizeAndPositionManager.getTotalSize();
const safeTotalSize = this.getTotalSize();
if (totalSize === safeTotalSize) {
return offset;
}
var offsetPercentage = this._getOffsetPercentage(containerSize, offset, safeTotalSize);
const offsetPercentage = this._getOffsetPercentage(containerSize, offset, safeTotalSize);
return Math.round(offsetPercentage * (totalSize - containerSize));
}
};
}

66
src/core/structure/heap.js

@ -1,30 +1,27 @@
(function () {
function defaultComparator(a, b) {
return a < b;
}
BI.Heap = function (items, comparator) {
export class Heap {
constructor(items, comparator) {
this._items = items || [];
this._size = this._items.length;
this._comparator = comparator || defaultComparator;
this._heapify();
};
}
BI.Heap.prototype = {
constructor: BI.Heap,
empty: function () {
empty() {
return this._size === 0;
},
}
pop: function () {
pop() {
if (this._size === 0) {
return;
}
var elt = this._items[0];
const elt = this._items[0];
var lastElt = this._items.pop();
const lastElt = this._items.pop();
this._size--;
if (this._size > 0) {
@ -33,36 +30,36 @@
}
return elt;
},
}
push: function (item) {
push(item) {
this._items[this._size++] = item;
this._bubbleUp(this._size - 1);
},
}
size: function () {
size() {
return this._size;
},
}
peek: function () {
peek() {
if (this._size === 0) {
return;
}
return this._items[0];
},
}
_heapify: function () {
for (var index = Math.floor((this._size + 1) / 2); index >= 0; index--) {
_heapify() {
for (let index = Math.floor((this._size + 1) / 2); index >= 0; index--) {
this._sinkDown(index);
}
},
}
_bubbleUp: function (index) {
var elt = this._items[index];
_bubbleUp(index) {
const elt = this._items[index];
while (index > 0) {
var parentIndex = Math.floor((index + 1) / 2) - 1;
var parentElt = this._items[parentIndex];
const parentIndex = Math.floor((index + 1) / 2) - 1;
const parentElt = this._items[parentIndex];
// if parentElt < elt, stop
if (this._comparator(parentElt, elt)) {
@ -74,25 +71,25 @@
this._items[index] = parentElt;
index = parentIndex;
}
},
}
_sinkDown: function (index) {
var elt = this._items[index];
_sinkDown(index) {
const elt = this._items[index];
while (true) {
var leftChildIndex = 2 * (index + 1) - 1;
var rightChildIndex = 2 * (index + 1);
var swapIndex = -1;
const leftChildIndex = 2 * (index + 1) - 1;
const rightChildIndex = 2 * (index + 1);
let swapIndex = -1;
if (leftChildIndex < this._size) {
var leftChild = this._items[leftChildIndex];
const leftChild = this._items[leftChildIndex];
if (this._comparator(leftChild, elt)) {
swapIndex = leftChildIndex;
}
}
if (rightChildIndex < this._size) {
var rightChild = this._items[rightChildIndex];
const rightChild = this._items[rightChildIndex];
if (this._comparator(rightChild, elt)) {
if (swapIndex === -1 ||
this._comparator(rightChild, this._items[swapIndex])) {
@ -111,5 +108,4 @@
index = swapIndex;
}
}
};
})();
}

44
src/core/structure/index.js

@ -0,0 +1,44 @@
import * as a1 from "./aes";
import * as a2 from "./aspect";
import * as a3 from "./base64";
import * as a4 from "./cache";
import * as a5 from "./cellSizeAndPositionManager";
import * as a6 from "./heap";
import * as a7 from "./linkedHashMap";
import * as a8 from "./lru";
import * as a9 from "./prefixIntervalTree";
import * as a10 from "./queue";
import * as a11 from "./sectionManager";
import * as a12 from "./tree";
import * as a13 from "./vector";
Object.assign(BI, {
...a1,
...a2,
...a3,
...a4,
...a5,
...a6,
...a7,
...a8,
...a9,
...a10,
...a11,
...a12,
...a13,
});
export * from "./aes";
export * from "./aspect";
export * from "./base64";
export * from "./cache";
export * from "./cellSizeAndPositionManager";
export * from "./heap";
export * from "./linkedHashMap";
export * from "./lru";
export * from "./prefixIntervalTree";
export * from "./queue";
export * from "./sectionManager";
export * from "./tree";
export * from "./vector";

58
src/core/structure/linkedHashMap.js

@ -1,19 +1,14 @@
!(function () {
BI.LinkHashMap = function () {
export class LinkHashMap {
constructor() {
this.array = [];
this.map = {};
};
BI.LinkHashMap.prototype = {
constructor: BI.LinkHashMap,
has: function (key) {
if (key in this.map) {
return true;
}
return false;
},
add: function (key, value) {
has(key) {
return key in this.map;
}
add(key, value) {
if (typeof key === "undefined") {
return;
}
@ -23,50 +18,49 @@
this.array.push(key);
this.map[key] = value;
}
},
}
remove: function (key) {
remove(key) {
if (key in this.map) {
delete this.map[key];
for (var i = 0; i < this.array.length; i++) {
for (let i = 0; i < this.array.length; i++) {
if (this.array[i] == key) {
this.array.splice(i, 1);
break;
}
}
}
},
}
size: function () {
size() {
return this.array.length;
},
}
each: function (fn, scope) {
var scope = scope || window;
var fn = fn || null;
each(fn, scope) {
scope = scope || window;
fn = fn || null;
if (fn == null || typeof (fn) !== "function") {
return;
}
for (var i = 0; i < this.array.length; i++) {
var key = this.array[i];
var value = this.map[key];
var re = fn.call(scope, key, value, i, this.array, this.map);
for (let i = 0; i < this.array.length; i++) {
const key = this.array[i];
const value = this.map[key];
const re = fn.call(scope, key, value, i, this.array, this.map);
if (re == false) {
break;
}
}
},
}
get: function (key) {
get(key) {
return this.map[key];
},
}
toArray: function () {
var array = [];
toArray() {
const array = [];
this.each(function (key, value) {
array.push(value);
});
return array;
}
};
})();
}

38
src/core/structure/lru.js

@ -1,24 +1,21 @@
!(function () {
BI.LRU = function (limit) {
export class LRU {
constructor(limit) {
this.size = 0;
this.limit = limit;
this.head = this.tail = undefined;
this._keymap = {};
};
var p = BI.LRU.prototype;
}
p.put = function (key, value) {
var removed;
put(key, value) {
let removed;
if (this.size === this.limit) {
removed = this.shift();
}
var entry = this.get(key, true);
let entry = this.get(key, true);
if (!entry) {
entry = {
key: key
key: key,
};
this._keymap[key] = entry;
if (this.tail) {
@ -33,10 +30,10 @@
entry.value = value;
return removed;
};
}
p.shift = function () {
var entry = this.head;
shift() {
const entry = this.head;
if (entry) {
this.head = this.head.newer;
this.head.older = undefined;
@ -45,11 +42,10 @@
this.size--;
}
return entry;
};
}
p.get = function (key, returnEntry) {
var entry = this._keymap[key];
get(key, returnEntry) {
const entry = this._keymap[key];
if (entry === undefined) return;
if (entry === this.tail) {
return returnEntry
@ -78,9 +74,9 @@
return returnEntry
? entry
: entry.value;
};
}
p.has = function (key) {
has(key) {
return this._keymap[key] != null;
};
})();
}
}

105
src/core/structure/prefixIntervalTree.js

@ -1,32 +1,32 @@
// 线段树
(function () {
var parent = function (node) {
const parent = function (node) {
return Math.floor(node / 2);
};
var Int32Array = _global.Int32Array || function (size) {
var xs = [];
for (var i = size - 1; i >= 0; --i) {
const Int32Array = _global.Int32Array || function (size) {
const xs = [];
for (let i = size - 1; i >= 0; --i) {
xs[i] = 0;
}
return xs;
};
var ceilLog2 = function (x) {
var y = 1;
const ceilLog2 = function (x) {
let y = 1;
while (y < x) {
y *= 2;
}
return y;
};
BI.PrefixIntervalTree = function (xs) {
export class PrefixIntervalTree {
constructor(xs) {
this._size = xs.length;
this._half = ceilLog2(this._size);
// _heap是一个_size两倍以上的堆
this._heap = new Int32Array(2 * this._half);
var i;
let i;
// 初始化 >= _size 的堆空间, 即叶子节点
for (i = 0; i < this._size; ++i) {
this._heap[this._half + i] = xs[i];
@ -35,13 +35,23 @@
for (i = this._half - 1; i > 0; --i) {
this._heap[i] = this._heap[2 * i] + this._heap[2 * i + 1];
}
};
}
static uniform(size, initialValue) {
const xs = [];
for (let i = size - 1; i >= 0; --i) {
xs[i] = initialValue;
}
return new PrefixIntervalTree(xs);
}
BI.PrefixIntervalTree.prototype = {
constructor: BI.PrefixIntervalTree,
// 往_half之后的空间set值,需要更新其所有祖先节点的值
set: function (index, value) {
var node = this._half + index;
static empty(size) {
return PrefixIntervalTree.uniform(size, 0);
}
set(index, value) {
let node = this._half + index;
this._heap[node] = value;
node = parent(node);
@ -49,27 +59,27 @@
this._heap[node] =
this._heap[2 * node] + this._heap[2 * node + 1];
}
},
}
get: function (index) {
var node = this._half + index;
get(index) {
const node = this._half + index;
return this._heap[node];
},
}
getSize: function () {
getSize() {
return this._size;
},
}
/**
* get(0) + get(1) + ... + get(end - 1).
*/
sumUntil: function (end) {
sumUntil(end) {
if (end === 0) {
return 0;
}
var node = this._half + end - 1;
var sum = this._heap[node];
let node = this._half + end - 1;
let sum = this._heap[node];
for (; node !== 1; node = parent(node)) {
if (node % 2 === 1) {
sum += this._heap[node - 1];
@ -77,38 +87,38 @@
}
return sum;
},
}
/**
* get(0) + get(1) + ... + get(inclusiveEnd).
*/
sumTo: function (inclusiveEnd) {
sumTo(inclusiveEnd) {
return this.sumUntil(inclusiveEnd + 1);
},
}
/**
* sum get(begin) + get(begin + 1) + ... + get(end - 1).
*/
sum: function (begin, end) {
sum(begin, end) {
return this.sumUntil(end) - this.sumUntil(begin);
},
}
/**
* Returns the smallest i such that 0 <= i <= size and sumUntil(i) <= t, or
* -1 if no such i exists.
*/
greatestLowerBound: function (t) {
greatestLowerBound(t) {
if (t < 0) {
return -1;
}
var node = 1;
let node = 1;
if (this._heap[node] <= t) {
return this._size;
}
while (node < this._half) {
var leftSum = this._heap[2 * node];
const leftSum = this._heap[2 * node];
if (t < leftSum) {
node = 2 * node;
} else {
@ -118,24 +128,24 @@
}
return node - this._half;
},
}
/**
* Returns the smallest i such that 0 <= i <= size and sumUntil(i) < t, or
* -1 if no such i exists.
*/
greatestStrictLowerBound: function (t) {
greatestStrictLowerBound(t) {
if (t <= 0) {
return -1;
}
var node = 1;
let node = 1;
if (this._heap[node] < t) {
return this._size;
}
while (node < this._half) {
var leftSum = this._heap[2 * node];
const leftSum = this._heap[2 * node];
if (t <= leftSum) {
node = 2 * node;
} else {
@ -145,36 +155,23 @@
}
return node - this._half;
},
}
/**
* Returns the smallest i such that 0 <= i <= size and t <= sumUntil(i), or
* size + 1 if no such i exists.
*/
leastUpperBound: function (t) {
leastUpperBound(t) {
return this.greatestStrictLowerBound(t) + 1;
},
}
/**
* Returns the smallest i such that 0 <= i <= size and t < sumUntil(i), or
* size + 1 if no such i exists.
*/
leastStrictUpperBound: function (t) {
leastStrictUpperBound(t) {
return this.greatestLowerBound(t) + 1;
}
};
BI.PrefixIntervalTree.uniform = function (size, initialValue) {
var xs = [];
for (var i = size - 1; i >= 0; --i) {
xs[i] = initialValue;
}
return new BI.PrefixIntervalTree(xs);
};
BI.PrefixIntervalTree.empty = function (size) {
return BI.PrefixIntervalTree.uniform(size, 0);
};
})();
}

93
src/core/structure/queue.js

@ -1,89 +1,86 @@
import {contains, remove} from "../2.base";
!(function () {
BI.Queue = function (capacity) {
export class Queue {
constructor(capacity) {
this.capacity = capacity;
this.array = [];
};
BI.Queue.prototype = {
constructor: BI.Queue,
}
contains: function (v) {
return BI.contains(this.array, v);
},
contains(v) {
return contains(this.array, v);
}
indexOf: function (v) {
return BI.contains(this.array, v);
},
indexOf(v) {
return contains(this.array, v);
}
getElementByIndex: function (index) {
getElementByIndex(index) {
return this.array[index];
},
}
push: function (v) {
push(v) {
this.array.push(v);
if (this.capacity && this.array.length > this.capacity) {
this.array.shift();
}
},
}
pop: function () {
pop() {
this.array.pop();
},
}
shift: function () {
shift() {
this.array.shift();
},
}
unshift: function (v) {
unshift(v) {
this.array.unshift(v);
if (this.capacity && this.array.length > this.capacity) {
this.array.pop();
}
},
}
remove: function (v) {
BI.remove(this.array, v);
},
remove(v) {
remove(this.array, v);
}
splice: function () {
splice() {
this.array.splice.apply(this.array, arguments);
},
}
slice: function () {
slice() {
this.array.slice.apply(this.array, arguments);
},
}
size: function () {
size() {
return this.array.length;
},
}
each: function (fn, scope) {
var scope = scope || window;
var fn = fn || null;
each(fn, scope) {
scope = scope || window;
fn = fn || null;
if (fn == null || typeof (fn) !== "function") {
return;
}
for (var i = 0; i < this.array.length; i++) {
var re = fn.call(scope, i, this.array[i], this.array);
if (re == false) {
for (let i = 0; i < this.array.length; i++) {
const re = fn.call(scope, i, this.array[i], this.array);
if (re === false) {
break;
}
}
},
}
toArray: function () {
toArray() {
return this.array;
},
}
fromArray: function (array) {
var self = this;
BI.each(array, function (i, v) {
self.push(v);
});
},
fromArray(array) {
array.each(v => this.push(v));
}
clear: function () {
clear() {
this.array.length = 0;
}
};
})();
}

79
src/core/structure/sectionManager.js

@ -1,5 +1,7 @@
!(function () {
var Section = function (height, width, x, y) {
import {each, keys, map, size} from "../2.base";
class Section {
constructor(height, width, x, y) {
this.height = height;
this.width = width;
this.x = x;
@ -7,60 +9,58 @@
this._indexMap = {};
this._indices = [];
};
}
Section.prototype = {
constructor: Section,
addCellIndex: function (index) {
addCellIndex(index) {
if (!this._indexMap[index]) {
this._indexMap[index] = true;
this._indices.push(index);
}
},
}
getCellIndices: function () {
getCellIndices() {
return this._indices;
}
};
}
const SECTION_SIZE = 100;
var SECTION_SIZE = 100;
BI.SectionManager = function (sectionSize) {
this._sectionSize = sectionSize || SECTION_SIZE;
export class SectionManager {
constructor(sectionSize = SECTION_SIZE) {
this._sectionSize = sectionSize;
this._cellMetadata = [];
this._sections = {};
};
}
BI.SectionManager.prototype = {
constructor: BI.SectionManager,
getCellIndices: function (height, width, x, y) {
var indices = {};
getCellIndices(height, width, x, y) {
const indices = {};
BI.each(this.getSections(height, width, x, y), function (i, section) {
BI.each(section.getCellIndices(), function (j, index) {
each(this.getSections(height, width, x, y), function (i, section) {
each(section.getCellIndices(), function (j, index) {
indices[index] = index;
});
});
return BI.map(BI.keys(indices), function (i, index) {
return map(keys(indices), function (i, index) {
return indices[index];
});
},
}
getCellMetadata: function (index) {
getCellMetadata(index) {
return this._cellMetadata[index];
},
}
getSections: function (height, width, x, y) {
var sectionXStart = Math.floor(x / this._sectionSize);
var sectionXStop = Math.floor((x + width - 1) / this._sectionSize);
var sectionYStart = Math.floor(y / this._sectionSize);
var sectionYStop = Math.floor((y + height - 1) / this._sectionSize);
getSections(height, width, x, y) {
const sectionXStart = Math.floor(x / this._sectionSize);
const sectionXStop = Math.floor((x + width - 1) / this._sectionSize);
const sectionYStart = Math.floor(y / this._sectionSize);
const sectionYStop = Math.floor((y + height - 1) / this._sectionSize);
var sections = [];
const sections = [];
for (var sectionX = sectionXStart; sectionX <= sectionXStop; sectionX++) {
for (var sectionY = sectionYStart; sectionY <= sectionYStop; sectionY++) {
var key = sectionX + "." + sectionY;
for (let sectionX = sectionXStart; sectionX <= sectionXStop; sectionX++) {
for (let sectionY = sectionYStart; sectionY <= sectionYStop; sectionY++) {
const key = sectionX + "." + sectionY;
if (!this._sections[key]) {
this._sections[key] = new Section(this._sectionSize, this._sectionSize, sectionX * this._sectionSize, sectionY * this._sectionSize);
@ -71,18 +71,17 @@
}
return sections;
},
}
getTotalSectionCount: function () {
return BI.size(this._sections);
},
getTotalSectionCount() {
return size(this._sections);
}
registerCell: function (cellMetadatum, index) {
registerCell(cellMetadatum, index) {
this._cellMetadata[index] = cellMetadatum;
BI.each(this.getSections(cellMetadatum.height, cellMetadatum.width, cellMetadatum.x, cellMetadatum.y), function (i, section) {
each(this.getSections(cellMetadatum.height, cellMetadatum.width, cellMetadatum.x, cellMetadatum.y), function (i, section) {
section.addCellIndex(index);
});
}
};
})();
}

578
src/core/structure/tree.js

@ -1,125 +1,263 @@
(function () {
BI.Tree = function () {
this.root = new BI.Node(BI.UUID());
};
BI.Tree.prototype = {
constructor: BI.Tree,
addNode: function (node, newNode, index) {
if (BI.isNull(newNode)) {
import {
isObject,
UUID,
extend,
isEmpty,
isArray,
first,
last,
findIndex,
isUndefined,
isNull,
each,
deepClone,
isEqual, some, every, clone
} from "../2.base";
export class Node {
constructor(id) {
if (isObject(id)) {
extend(this, id);
} else {
this.id = id;
}
this.clear();
}
set(key, value) {
if (isObject(key)) {
extend(this, key);
return;
}
this[key] = value;
}
get(key) {
return this[key];
}
isLeaf() {
return isEmpty(this.children);
}
getChildren() {
return this.children;
}
getChildrenLength() {
return this.children.length;
}
getFirstChild() {
return first(this.children);
}
getLastChild() {
return last(this.children);
}
setLeft(left) {
this.left = left;
}
getLeft() {
return this.left;
}
setRight(right) {
this.right = right;
}
getRight() {
return this.right;
}
setParent(parent) {
this.parent = parent;
}
getParent() {
return this.parent;
}
getChild(index) {
return this.children[index];
}
getChildIndex(id) {
return findIndex(this.children, function (i, ch) {
return ch.get("id") === id;
});
}
removeChild(id) {
this.removeChildByIndex(this.getChildIndex(id));
}
removeChildByIndex(index) {
const before = this.getChild(index - 1);
const behind = this.getChild(index + 1);
if (before != null) {
before.setRight(behind || null);
}
if (behind != null) {
behind.setLeft(before || null);
}
this.children.splice(index, 1);
}
removeAllChilds() {
this.children = [];
}
addChild(child, index) {
let cur = null;
if (isUndefined(index)) {
cur = this.children.length - 1;
} else {
cur = index - 1;
}
child.setParent(this);
if (cur >= 0) {
this.getChild(cur) && this.getChild(cur).setRight(child);
child.setLeft(this.getChild(cur));
}
if (isUndefined(index)) {
this.children.push(child);
} else {
this.children.splice(index, 0, child);
}
}
equals(obj) {
return this === obj || this.id === obj.id;
}
clear() {
this.parent = null;
this.left = null;
this.right = null;
this.children = [];
}
}
export class Tree {
constructor() {
this.root = new Node(UUID());
}
addNode(node, newNode, index) {
if (isNull(newNode)) {
this.root.addChild(node, index);
} else if (BI.isNull(node)) {
} else if (isNull(node)) {
this.root.addChild(newNode, index);
} else {
node.addChild(newNode, index);
}
},
}
isRoot: function (node) {
isRoot(node) {
return node === this.root;
},
}
getRoot: function () {
getRoot() {
return this.root;
},
}
clear: function () {
clear() {
this.root.clear();
},
}
initTree: function (nodes) {
var self = this;
initTree(nodes) {
this.clear();
var queue = [];
BI.each(nodes, function (i, node) {
var n = new BI.Node(node);
const queue = [];
each(nodes, (i, node) => {
const n = new Node(node);
n.set("data", node);
self.addNode(n);
this.addNode(n);
queue.push(n);
});
while (!BI.isEmpty(queue)) {
var parent = queue.shift();
var node = parent.get("data");
BI.each(node.children, function (i, child) {
var n = new BI.Node(child);
while (!isEmpty(queue)) {
const parent = queue.shift();
const node = parent.get("data");
each(node.children, (i, child) => {
const n = new Node(child);
n.set("data", child);
queue.push(n);
self.addNode(parent, n);
this.addNode(parent, n);
});
}
},
}
_toJSON: function (node) {
var self = this;
var children = [];
BI.each(node.getChildren(), function (i, child) {
children.push(self._toJSON(child));
_toJSON(node) {
const children = [];
each(node.getChildren(), (i, child) => {
children.push(this._toJSON(child));
});
return BI.extend({
id: node.id
}, BI.deepClone(node.get("data")), (children.length > 0 ? {
children: children
return extend({
id: node.id,
}, deepClone(node.get("data")), (children.length > 0 ? {
children: children,
} : {}));
},
}
toJSON: function (node) {
var self = this, result = [];
BI.each((node || this.root).getChildren(), function (i, child) {
result.push(self._toJSON(child));
toJSON(node) {
const result = [];
each((node || this.root).getChildren(), (i, child) => {
result.push(this._toJSON(child));
});
return result;
},
}
_toJSONWithNode: function (node) {
var self = this;
var children = [];
BI.each(node.getChildren(), function (i, child) {
children.push(self._toJSONWithNode(child));
_toJSONWithNode(node) {
const children = [];
each(node.getChildren(), (i, child) => {
children.push(this._toJSONWithNode(child));
});
return BI.extend({
id: node.id
}, BI.deepClone(node.get("data")), {
node: node
return extend({
id: node.id,
}, deepClone(node.get("data")), {
node: node,
}, (children.length > 0 ? {
children: children
children: children,
} : {}));
},
}
toJSONWithNode: function (node) {
var self = this, result = [];
BI.each((node || this.root).getChildren(), function (i, child) {
result.push(self._toJSONWithNode(child));
toJSONWithNode(node) {
const result = [];
each((node || this.root).getChildren(), (i, child) => {
result.push(this._toJSONWithNode(child));
});
return result;
},
}
search: function (root, target, param) {
if (!(root instanceof BI.Node)) {
return arguments.callee.apply(this, [this.root, root, target]);
search(root, target, param) {
if (!(root instanceof Node)) {
return this.search(this.root, root, target);
}
var self = this, next = null;
let next = null;
if (BI.isNull(target)) {
if (isNull(target)) {
return null;
}
if (BI.isEqual(root[param || "id"], target)) {
if (isEqual(root[param || "id"], target)) {
return root;
}
BI.any(root.getChildren(), function (i, child) {
next = self.search(child, target, param);
some(root.getChildren(), (i, child) => {
next = this.search(child, target, param);
if (null !== next) {
return true;
}
});
return next;
},
}
_traverse: function (node, callback) {
var queue = [];
_traverse(node, callback) {
let queue = [];
queue.push(node);
while (!BI.isEmpty(queue)) {
var temp = queue.shift();
var b = callback && callback(temp);
while (!isEmpty(queue)) {
const temp = queue.shift();
const b = callback && callback(temp);
if (b === false) {
break;
}
@ -130,51 +268,50 @@
queue = queue.concat(temp.getChildren());
}
}
},
}
traverse: function (callback) {
traverse(callback) {
this._traverse(this.root, callback);
},
}
_recursion: function (node, route, callback) {
var self = this;
return BI.every(node.getChildren(), function (i, child) {
var next = BI.clone(route);
_recursion(node, route, callback) {
return every(node.getChildren(), (i, child) => {
const next = clone(route);
next.push(child.id);
var b = callback && callback(child, next);
const b = callback && callback(child, next);
if (b === false) {
return false;
}
if (b === true) {
return true;
}
return self._recursion(child, next, callback);
return this._recursion(child, next, callback);
});
},
}
recursion: function (callback) {
recursion(callback) {
this._recursion(this.root, [], callback);
},
}
inOrderTraverse: function (callback) {
inOrderTraverse(callback) {
this._inOrderTraverse(this.root, callback);
},
}
// 中序遍历(递归)
_inOrderTraverse: function (node, callback) {
_inOrderTraverse(node, callback) {
if (node != null) {
this._inOrderTraverse(node.getLeft());
callback && callback(node);
this._inOrderTraverse(node.getRight());
}
},
}
// 中序遍历(非递归)
nrInOrderTraverse: function (callback) {
nrInOrderTraverse(callback) {
var stack = [];
var node = this.root;
while (node != null || !BI.isEmpty(stack)) {
const stack = [];
let node = this.root;
while (node != null || !isEmpty(stack)) {
while (node != null) {
stack.push(node);
node = node.getLeft();
@ -183,28 +320,28 @@
callback && callback(node);
node = node.getRight();
}
},
}
preOrderTraverse: function (callback) {
preOrderTraverse(callback) {
this._preOrderTraverse(this.root, callback);
},
}
// 先序遍历(递归)
_preOrderTraverse: function (node, callback) {
_preOrderTraverse(node, callback) {
if (node != null) {
callback && callback(node);
this._preOrderTraverse(node.getLeft());
this._preOrderTraverse(node.getRight());
}
},
}
// 先序遍历(非递归)
nrPreOrderTraverse: function (callback) {
nrPreOrderTraverse(callback) {
var stack = [];
var node = this.root;
const stack = [];
let node = this.root;
while (node != null || !BI.isEmpty(stack)) {
while (node != null || !isEmpty(stack)) {
while (node != null) {
callback && callback(node);
@ -214,38 +351,38 @@
node = stack.pop();
node = node.getRight();
}
},
}
postOrderTraverse: function (callback) {
postOrderTraverse(callback) {
this._postOrderTraverse(this.root, callback);
},
}
// 后序遍历(递归)
_postOrderTraverse: function (node, callback) {
_postOrderTraverse(node, callback) {
if (node != null) {
this._postOrderTraverse(node.getLeft());
this._postOrderTraverse(node.getRight());
callback && callback(node);
}
},
}
// 后续遍历(非递归)
nrPostOrderTraverse: function (callback) {
nrPostOrderTraverse(callback) {
var stack = [];
var node = this.root;
var preNode = null;// 表示最近一次访问的节点
const stack = [];
let node = this.root;
let preNode = null;// 表示最近一次访问的节点
while (node != null || !BI.isEmpty(stack)) {
while (node != null || !isEmpty(stack)) {
while (node != null) {
stack.push(node);
node = node.getLeft();
}
node = BI.last(stack);
node = last(stack);
if (node.getRight() == null || node.getRight() == preNode) {
if (node.getRight() == null || node.getRight() === preNode) {
callback && callback(node);
node = stack.pop();
preNode = node;
@ -255,203 +392,72 @@
}
}
}
};
BI.Node = function (id) {
if (BI.isObject(id)) {
BI.extend(this, id);
} else {
this.id = id;
}
this.clear.apply(this, arguments);
};
BI.Node.prototype = {
constructor: BI.Node,
set: function (key, value) {
if (BI.isObject(key)) {
BI.extend(this, key);
return;
}
this[key] = value;
},
get: function (key) {
return this[key];
},
isLeaf: function () {
return BI.isEmpty(this.children);
},
getChildren: function () {
return this.children;
},
getChildrenLength: function () {
return this.children.length;
},
getFirstChild: function () {
return BI.first(this.children);
},
getLastChild: function () {
return BI.last(this.children);
},
setLeft: function (left) {
this.left = left;
},
getLeft: function () {
return this.left;
},
setRight: function (right) {
this.right = right;
},
getRight: function () {
return this.right;
},
setParent: function (parent) {
this.parent = parent;
},
getParent: function () {
return this.parent;
},
getChild: function (index) {
return this.children[index];
},
getChildIndex: function (id) {
return BI.findIndex(this.children, function (i, ch) {
return ch.get("id") === id;
});
},
removeChild: function (id) {
this.removeChildByIndex(this.getChildIndex(id));
},
removeChildByIndex: function (index) {
var before = this.getChild(index - 1);
var behind = this.getChild(index + 1);
if (before != null) {
before.setRight(behind || null);
}
if (behind != null) {
behind.setLeft(before || null);
}
this.children.splice(index, 1);
},
removeAllChilds: function () {
this.children = [];
},
addChild: function (child, index) {
var cur = null;
if (BI.isUndefined(index)) {
cur = this.children.length - 1;
} else {
cur = index - 1;
}
child.setParent(this);
if (cur >= 0) {
this.getChild(cur) && this.getChild(cur).setRight(child);
child.setLeft(this.getChild(cur));
}
if (BI.isUndefined(index)) {
this.children.push(child);
} else {
this.children.splice(index, 0, child);
}
},
equals: function (obj) {
return this === obj || this.id === obj.id;
},
clear: function () {
this.parent = null;
this.left = null;
this.right = null;
this.children = [];
}
};
BI.extend(BI.Tree, {
transformToArrayFormat: function (nodes, pId, childKey) {
static transformToArrayFormat(nodes, pId, childKey) {
if (!nodes) return [];
var r = [];
let r = [];
childKey = childKey || "children";
if (BI.isArray(nodes)) {
for (var i = 0, l = nodes.length; i < l; i++) {
var node = BI.clone(nodes[i]);
if (isArray(nodes)) {
for (let i = 0, l = nodes.length; i < l; i++) {
const node = clone(nodes[i]);
node.pId = node.pId == null ? pId : node.pId;
delete node.children;
r.push(node);
if (nodes[i][childKey]) {
r = r.concat(BI.Tree.transformToArrayFormat(nodes[i][childKey], node.id));
r = r.concat(Tree.transformToArrayFormat(nodes[i][childKey], node.id));
}
}
} else {
var newNodes = BI.clone(nodes);
const newNodes = clone(nodes);
newNodes.pId = newNodes.pId == null ? pId : newNodes.pId;
delete newNodes.children;
r.push(newNodes);
if (nodes[childKey]) {
r = r.concat(BI.Tree.transformToArrayFormat(nodes[childKey], newNodes.id));
r = r.concat(Tree.transformToArrayFormat(nodes[childKey], newNodes.id));
}
}
return r;
},
}
arrayFormat: function (nodes, pId) {
static arrayFormat(nodes, pId) {
if (!nodes) {
return [];
}
var r = [];
if (BI.isArray(nodes)) {
for (var i = 0, l = nodes.length; i < l; i++) {
var node = nodes[i];
let r = [];
if (isArray(nodes)) {
for (let i = 0, l = nodes.length; i < l; i++) {
const node = nodes[i];
node.pId = node.pId == null ? pId : node.pId;
r.push(node);
if (nodes[i]["children"]) {
r = r.concat(BI.Tree.arrayFormat(nodes[i]["children"], node.id));
r = r.concat(Tree.arrayFormat(nodes[i]["children"], node.id));
}
}
} else {
var newNodes = nodes;
const newNodes = nodes;
newNodes.pId = newNodes.pId == null ? pId : newNodes.pId;
r.push(newNodes);
if (nodes["children"]) {
r = r.concat(BI.Tree.arrayFormat(nodes["children"], newNodes.id));
r = r.concat(Tree.arrayFormat(nodes["children"], newNodes.id));
}
}
return r;
},
}
transformToTreeFormat: function (sNodes) {
var i, l;
static transformToTreeFormat(sNodes) {
let i, l;
if (!sNodes) {
return [];
}
if (BI.isArray(sNodes)) {
var r = [];
var tmpMap = {};
if (isArray(sNodes)) {
const r = [];
const tmpMap = {};
for (i = 0, l = sNodes.length; i < l; i++) {
if (BI.isNull(sNodes[i].id)) {
if (isNull(sNodes[i].id)) {
return sNodes;
}
tmpMap[sNodes[i].id] = BI.clone(sNodes[i]);
tmpMap[sNodes[i].id] = clone(sNodes[i]);
}
for (i = 0, l = sNodes.length; i < l; i++) {
if (tmpMap[sNodes[i].pId] && sNodes[i].id !== sNodes[i].pId) {
@ -468,19 +474,19 @@
}
return [sNodes];
},
}
treeFormat: function (sNodes) {
var i, l;
static treeFormat(sNodes) {
let i, l;
if (!sNodes) {
return [];
}
if (BI.isArray(sNodes)) {
var r = [];
var tmpMap = {};
if (isArray(sNodes)) {
const r = [];
const tmpMap = {};
for (i = 0, l = sNodes.length; i < l; i++) {
if (BI.isNull(sNodes[i].id)) {
if (isNull(sNodes[i].id)) {
return sNodes;
}
tmpMap[sNodes[i].id] = sNodes[i];
@ -499,19 +505,17 @@
}
return [sNodes];
},
}
traversal: function (array, callback, pNode) {
if (BI.isNull(array)) {
static traversal(array, callback, pNode) {
if (isNull(array)) {
return;
}
var self = this;
BI.some(array, function (i, item) {
some(array, (i, item) => {
if (callback(i, item, pNode) === false) {
return true;
}
self.traversal(item.children, callback, item);
this.traversal(item.children, callback, item);
});
}
});
})();
}

49
src/core/structure/vector.js

@ -1,27 +1,29 @@
// 向量操作
BI.Vector = function (x, y) {
export class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
};
BI.Vector.prototype = {
constructor: BI.Vector,
cross: function (v) {
}
cross(v) {
return (this.x * v.y - this.y * v.x);
},
length: function (v) {
}
length(v) {
return (Math.sqrt(this.x * v.x + this.y * v.y));
}
};
BI.Region = function (x, y, w, h) {
}
export class Region {
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
};
BI.Region.prototype = {
constructor: BI.Region,
}
// 判断两个区域是否相交,若相交,则要么顶点互相包含,要么矩形边界(或对角线)相交
isIntersects: function (obj) {
isIntersects(obj) {
if (this.isPointInside(obj.x, obj.y) ||
this.isPointInside(obj.x + obj.w, obj.y) ||
this.isPointInside(obj.x, obj.y + obj.h) ||
@ -34,17 +36,18 @@ BI.Region.prototype = {
return true;
} else if (obj.x != null && obj.y != null)// 判断矩形对角线相交 |v1 X v2||v1 X v3| < 0
{
var vector1 = new BI.Vector(this.w, this.h);// 矩形对角线向量
var vector2 = new BI.Vector(obj.x - this.x, obj.y - this.y);
var vector3 = new BI.Vector(vector2.x + obj.w, vector2.y + obj.h);
const vector1 = new Vector(this.w, this.h);// 矩形对角线向量
const vector2 = new Vector(obj.x - this.x, obj.y - this.y);
const vector3 = new Vector(vector2.x + obj.w, vector2.y + obj.h);
if ((vector1.cross(vector2) * vector1.cross(vector3)) < 0) {
return true;
}
}
return false;
},
}
// 判断一个点是否在这个区域内部
isPointInside: function (x, y) {
isPointInside(x, y) {
if (this.x == null || this.y == null) {
return false;
}
@ -52,12 +55,14 @@ BI.Region.prototype = {
return true;
}
return false;
},
}
// 返回区域的重心,因为是矩形所以返回中点
getPosition: function () {
var pos = [];
getPosition() {
const pos = [];
pos.push(this.x + this.w / 2);
pos.push(this.y + this.h / 2);
return pos;
}
};
}

Loading…
Cancel
Save