I would like to define a shortcut method for checking the end of the stack.
The following works in Firefox:
const Stack = class extends Array {
last() {
return this[this.length - 1];
}
}
However, after compiling with Babel, this does not work:
var Stack = function (_Array) {
_inherits(Stack, _Array);
function Stack() {
_classCallCheck(this, Stack);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Stack).apply(this, arguments));
}
_createClass(Stack, [{
key: 'last',
value: function last() {
return this[this.length - 1];
}
}]);
return Stack;
}(Array);
console.log(Stack.prototype.last);
console.log((new Stack()).last);
Array.prototype.last = Stack.prototype.last;
console.log((new Stack()).last);
For some reason, I can add functions to the new prototype, but they will not be available to instances of this prototype unless they are inserted directly into the Array prototype (which is obviously bad practice due to potential side effects).
Update . There can be several ways around this (including proxy objects or extending the prototype manually instead of using it extends), but since mine Stackreally doesn't need most Array methods, now I just use the wrapper.
const Stack = class {
constructor(...x) {
this.arr = [...x];
}
pop() {
return this.arr.pop();
}
push(...x) {
return this.arr.push(...x);
}
top() {
return this.arr[this.arr.length - 1];
}
size() {
return this.arr.length;
}
}