@monocircuit/utils
Version:
A repository that contains data structures, algorithms and more.
91 lines • 3.5 kB
JavaScript
"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A simple node that holds a piece of data and an array of connected children.
* It also possess a simple `toString` method.
*
* @generic `D` The type of data that will be stored in the `Node`
*/
var Node = /** @class */ (function () {
/**
* @param data A piece of data that will be held by the `Node`
* @param children A rest array that contains all connections to other `Nodes`
*/
function Node(data) {
var _this = this;
var children = [];
for (var _i = 1; _i < arguments.length; _i++) {
children[_i - 1] = arguments[_i];
}
/**
* Connections to children that are also instances of `Node`.
*/
this.children = [];
/**
* Holds the value for wether or not the children puffer should be enabled.
* Meaning if the array should expand when a child is added.
*
* The default value is false, since this is the way a `LinkedList` works.
*/
this.childrenPuffer = false;
/**
* Holds the size of the children puffer. Meaning the maximum size of the
* children array.
*
* This is only relevant if the `childrenPuffer` is enabled.
*/
this.childrenPufferSize = 1;
this.data = data;
children.filter(function (child) { return child; }).forEach(function (child) { return _this.children.push(child); });
}
Object.defineProperty(Node.prototype, "child", {
/**
* Returns the first child that was specified in the children array.
*
* Sets the first element of the children array equal to the passed child.
*/
get: function () {
var _a;
return (_a = this.children[0]) !== null && _a !== void 0 ? _a : null;
},
set: function (child) {
if (!this.childrenPuffer) {
this.children = [child];
}
else if (this.childrenPuffer && this.childrenPufferSize >= this.children.length + 1) {
this.children = __spreadArrays([child], this.children);
}
},
enumerable: false,
configurable: true
});
/**
* Converts the `Node` to a string. It simply takes the stored data to a
* string and returns it.
*
* @param callback A function that takes data and converts it to a string
* @returns The `Node` as a string
*/
Node.prototype.toString = function (callback) {
return callback ? callback(this.data) : "" + this.data;
};
/**
* Converts the children array of instances of `Node` into an array that
* only contains their data.
*
* @returns An array of the data the children contain
*/
Node.prototype.toChildrenArray = function () {
return this.children.map(function (child) { return (child ? child.data : null); });
};
return Node;
}());
exports.default = Node;
//# sourceMappingURL=Node.js.map