I am trying to figure out the solution but I can't find it. I need a function that throws an error when maximum call stack is reached and throws an error when minimum call stack is reached.
class Stack {
constructor() {
this.items = [];`Please Help me with this...`
}
push(item) {
this.items.push(item)
}
pop() {
const popped = this.items.pop();
if (this.items == null) {
throw new Error("Underflow");
}
return popped;
}
isEmpty() {
}
peek() {
}
}
How about modifying your functions?
push and pop should throw an error if Number.MAX_SAFE_INTEGER or <= 0 is reached.
class Stack {
constructor() {
this.items = [];
}
push(item) {
if (this.items.length >= Number.MAX_SAFE_INTEGER) {
throw new Error("Maximum call stack reached");
}
this.items.push(item)
}
pop() {
if (this.items.length <= 0) {
throw new Error("Minimum call stack reached");
}
return this.items.pop();
}
isEmpty() {
return this.items.length === 0;
}
peek() {
return this.items[this.items.length - 1];
}
}
Related
In this example I would like to call the defineX function before calling the add and value methods
class cl {
#x;
defineX(n) {
this.#x = n;
return this;
}
add(n) {
this.#x += n;
return this;
}
value() {
return this.#x;
}
}
const cObj = new cl();
console.log(cObj.defineX(3).add(5).value()); // output 8
console.log(cObj.add(3)) // should not happen
what is the best solution so I can prevent calling add before defineX method ??
also how to prevent calling the add method after it has been called for the first time ??
Don't use a single class, use multiple ones with different methods, each holding a different immutable state. It's simpler without class syntax at all though:
const cObj = {
defineX(n) {
const x = n;
return {
add(n) {
const v = x + n;
return {
value() {
return v;
}
};
}
};
}
};
console.log(cObj.defineX(3).add(5).value()); // output 8
console.log(cObj.add(3)) // error
With classes:
const cObj = {
defineX(n) {
return new Cl(n);
}
};
class Cl {
#x;
constructor(x) {
this.#x = x;
}
add(n) {
return new Result(this.#x + n);
}
}
class Result {
#v;
constructor(v) {
this.#v = v;
}
value() {
return this.#v;
}
}
Since 1) operations not allowed and 2) breaking from a chain of calls are involved, it seems to me correct way is to throw an exception whenever something wrong happens. You can always try/catch it if you know exception is a possibility.
class cl {
#x;
#defined;
#added;
defineX(n) {
this.#x = n;
this.#defined = true;
return this;
}
add(n) {
if (!this.#defined) {
throw new Error("`add` before define")
}
if (this.#added) {
throw new Error("already did `add`")
}
this.#x += n;
this.#added = true;
return this;
}
value() {
return this.#x;
}
}
const cObj = new cl();
// tests:
// console.log(cObj.defineX(3).add(5).value()); // output 8
// console.log(cObj.add(3)) // should not happen - output error
console.log(cObj.defineX(3).add(5).add(6).value()); // output error
I was having trouble tracking down a memory leak in Node.js and wrote a func to monitor object and array size increases over time but my func infinitely loops. I wrote a provision into it to detect and not iterate circular structures, but I've made some silly mistake and can't figure out what.
//monitor.js
const isCircular = require("../funcs/is-circular.js");
module.exports = class {
constructor() {
}
countObjContents(obj, count = 0) {
if (Array.isArray(obj)) count += this.countObjContents(obj)
else if (typeof obj == "object") {
if (isCircular(obj)) {
console.log("!!! is circular")
count++;
} else {
console.log("not circular")
Object.values(obj).forEach(prop => {
if (isCircular(prop)) {
console.log("!!! is circular")
count++;
} else {
console.log("not circular")
count += this.countObjContents(obj);
}
});
}
} else count++;
return count;
}
watch(obj, name) {
let count = false;
setInterval(() => {
console.log("monitoring", name)
let newCount = this.countObjContents(obj)
if (!count) count = newCount;
else {
console.log("object", name, "increased from", count, "properties to", newCount);
count = newCount;
}
}, 5000);
}
}
//is-circular.js
module.exports = (obj) => {
try {
JSON.stringify(obj);
} catch (e) {
return true;
}
return false;
}
What stupid mistake did I make this time? It seems like simple code and the fact that I don't understand why it's infinite looping is embarrasing lol.
error:
countObjContents(obj, count = 0) {
^
RangeError: Maximum call stack size exceeded
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:6:19)
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:7:43)
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:7:43)
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:7:43)
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:7:43)
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:7:43)
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:7:43)
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:7:43)
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:7:43)
at module.exports.countObjContents (C:\Users\jonat\Documents\GitHub\emporos\js\classes\monitor.js:7:43)
Your foreach loop is calling countObjContents with the original obj
rather than the prop.
You are also re-invoking countObjContents in the first condition check.
countObjContents(obj, count = 0) {
if (Array.isArray(obj)) count += this.countObjContents(obj)
This part alone is an infinite loop
I am making a function that returns true if number in outerfucntion is within innerfunction list
<script>
function hasMatch(item) {
hasMatch(2)
function inList() {
var List = [1,2,3,4];
for (i = 0; i<List.length; i++){
if (list[i] == item) {
return true;
} else {
return false;
}
}
}
inList();
}
hasMatch();
</script>
I get a "Max Stack exceeded error", how would I fix this?
hasMatch(2) is recursive call without any terminating condition.
hasMatch() is getting called infinitely and that's why you see stack exceeded error.
function hasMatch(item) {
function inList() {
var List = [1,2,3,4];
for (i = 0; i<List.length; i++){
if (List[i] == item) {
return true;
} else {
return false;
}
}
}
return inList();
}
hasMatch(2);
I have been trying to figure this out for days now, The app.js returns a "Maximum call stack size exceeded" after I logged "Debug: 3". I am new to Javascript, so I'm not sure if I'm creating functions that call themselves in a loop or something. Here is the function that is run and causes an error.
function sendNewUserPackage(node) {
console.log("Debug: 00");///////////////////////////////
for (var i in SOCKET_LIST) {
console.log("Debug: 01");///////////////////////////////
var s = SOCKET_LIST[i];
if (node === 1) {
for (var n in Node1.NODE_PLAYERS) {
console.log("Debug: 02");///////////////////////////////
var pl = Node1.NODE_PLAYERS[n];
if (s.id === pl.id) {
console.log("Debug: 03");///////////////////////////////Code never reaches Debug: 5 at the end of the function
s.emit('newUserPackage', Node1.NODE_PLAYERS);
}
}
}
else if (node === 2) {
console.log("Debug: 04");///////////////////////////////
for (var n in Node2.NODE_PLAYERS) {
var pl = Node2.NODE_PLAYERS[n];
if (s.id === pl.id) {
s.emit('newUserPackage', Node2.NODE_PLAYERS);
}
}
}
else if (node === 3) {
for (var n in Node3.NODE_PLAYERS) {
var pl = Node3.NODE_PLAYERS[n];
if (s.id === pl.id) {
s.emit('newUserPackage', Node3.NODE_PLAYERS);
}
}
}
}
console.log("Debug: 05");///////////////////////////////
}
function sendClientMessage(socket, message) {
socket.emit('message', message);
}
Here is how sendNewUserPackage() is called:
socket.on('loginAttempt', function(data) {
//Check credentials with database...
try {
console.log("Debug: 1");///////////////////////////////
Database.checkAccount(data.username, data.password, function(error, result) {
console.log("Debug: 2");///////////////////////////////
if (result === undefined) {
socket.emit('loginMessage', {status:false});
return;
}
if (result.length > 0) {
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
var player = new Player(socket.id, result[0].Username, result[0].Rank, result[0].Points);
player.socket = socket;
PLAYER_LIST[socket.id] = player;
console.log("Debug: 3");///////////////////////////////
var nodeNumber = selectGameNode();
console.log("Debug: 4");///////////////////////////////
if (nodeNumber === 1) {
Node1.addPlayer(player);
console.log("Debug: 98");///////////////////////////////
} else if (nodeNumber === 2) {
Node2.addPlayer(player);
console.log("Debug: 99");///////////////////////////////
} else if (nodeNumber === 3) {
Node3.addPlayer(player);
console.log("Debug: 100");///////////////////////////////
} else {
console.log("Debug: 5");///////////////////////////////
player.node = 0;
socket.emit('loginMessage', {status:true});
sendClientMessage(player.socket, 'Whoops! Looks like all games are full! Try again later!')
return;
}
console.log("Debug: 6");///////////////////////////////
socket.emit('loginMessage', {status:true});
sendNewUserPackage(player.node);
return;
}
console.log("Debug: 7");///////////////////////////////
socket.emit('loginMessage', {status:false});
});
} catch(err) {
console.log(err.message);
}
});
What confuses me about it is that each "Debug: num" that is called only shows up once in the console. So I think that means neither function is called more than once. Could something else be causing it?
Help is greatly appreciated!
Can anyone tell me. how to implement queue using 2 stacks.
Specifically, implement the enqueue and dequeuer methods.
it will helpful if you guys tell me in php or JavaScript programming
Here is a personal example, I'm sure it could be more optimized, but it allows for queue dequeue and peek functionality in JS.
function processData(input) {
let stackOne = [];
let stackTwo = [];
let parsableInput = input.split('\n');
for(let i = 1; i < parsableInput.length; i++) {
// handle 1 push
if (parsableInput[i][0] === '1') {
enqueue(stackOne, stackTwo, parsableInput[i].slice(2));
}
// handle 2
if (parsableInput[i] === '2') {
dequeue(stackTwo);
}
// handle 3
if (parsableInput[i] === '3') {
console.log(peek(stackTwo));
}
}
}
function enqueue(stackOne, stackTwo, queuedValue) {
while(stackTwo.length !== 0) {
stackOne.push(stackTwo.pop());
}
stackOne.push(queuedValue);
while(stackOne.length !== 0) {
stackTwo.push(stackOne.pop());
}
}
function dequeue(stackTwo) {
return stackTwo.pop();
}
function peek(stackTwo) {
let stringToBeParsed = stackTwo[stackTwo.length - 1];
let parsedString = stringToBeParsed.slice(0, stringToBeParsed.length);
if (parsedString) {
return parsedString;
} else {
console.log('Error: there is nothing to peek at!');
}
}
Here is my solution, but it's in C lang.
#include<stdio.h>
#include<stdlib.h>
struct Stack{
int size;
int top;
int *S;
}S1,S2;
void create(struct Stack *st){
st->size=10;
st->top=-1;
st->S=(int *)malloc(st->size*sizeof(int));
}
void push(struct Stack *st, int x){
if(st->top==st->size-1)
printf("\nStack overflow\n");
else
{
st->top++;
st->S[st->top]=x;
}
}
int pop(struct Stack *st){
int x=-1;
if(st->top==-1)
printf("\nStack Underflow\n");
else
{
x=st->S[st->top--]; // post decrement of top
}
return x;
}
int isEmpty(struct Stack *st){
if(st->top==-1)
return 1;
return 0;
}
void enqueue(int x){
push(&S1,x);
}
int dequeue(){
int x=-1;
if(isEmpty(&S2)){
if(isEmpty(&S1)){
printf("Empty Queue!");
return x;
}
else
{
while(!isEmpty(&S1))
push(&S2,pop(&S1));
}
}
return pop(&S2);
}
void display(struct Stack *st){
for(int i=st->top;i>=0;i--)
printf("%d ",st->S[i]);
printf("\n");
}
int main(){
create(&S1);
create(&S2);
enqueue(10);
enqueue(20);
enqueue(30);
enqueue(40);
int deleted_element=dequeue();
printf("Dequeued Element is = %d\n",deleted_element);
display(&S2);
return 0;
}