javascript scope, perm cant get correct variable - javascript

i cant get perm from function !!
there is scope problem here
var perm = "none";
var participantsPromise = getChannelParticipants(peerID * -1).then(
function (participants) {
angular.forEach(participants, function (participant){
if (participant.user_id == UserID) {
switch (participant._) {
case "channelParticipant":
perm = "normal";
console.log('->>>>>>> Perm = normal');
break;
case "channelParticipantEditor":
perm = "Admin";
console.log('->>>>>>> Perm = Admin');
break;
case "channelParticipantModerator":
perm = "Admin";
console.log('->>>>>>> Perm = Admin');
break;
case "channelParticipantCreator":
perm = "Creator";
console.log('->>>>>>> Perm = Creator');
break;
default:
console.log('#########> No handler for', participant._);
perm = "unknown";
}
}
})
});
return perm;
function return none , but perm already set on other values .
what can i do ?

Try this one
var perm = "none";
var participantsPromise = getChannelParticipants(peerID * -1).then(
function (participants) {
if (participants.user_id == UserID) {
switch (participants._) {
case "channelParticipant":
perm = "normal";
break;
case "channelParticipantEditor":
perm = "Admin";
break;
case "channelParticipantModerator":
perm = "Admin";
break;
case "channelParticipantCreator":
perm = "Creator";
break;
default:
console.log('No handler for', participants._);
perm = "unknown";
}
// perm variable is normal :)
} else {
console.log('userid does not match');
perm = "userId Error";
}
});

I believe the problem is that you're trying to read value of perm synchronously, while it's changed in the asynchronous callback.
var perm = "none"; // here value of `perm` is "none"
var participantsPromise = getChannelParticipants(peerID * -1).then(
function(participants) {
if (participants.user_id == UserID) {
switch (participants._) {
...
case "channelParticipantCreator":
perm = "Creator";
break;
}
// perm variable is normal :)
}
});
console.log(perm) // perm is back to none - yes,
// because the code `function(participants) ` hasn't yet
// been executed, since it's asynchronous
// let's add a delayed callback that will wait until async code finishes executing
var timeToFinishGetChannelParticipants = 10000; // 10 seconds
setTimeout(function() {
console.log(perm); // here it should have value set inside `function(participants)`
}, timeToFinishGetChannelParticipants);
UPDATE:
function getPerm() {
return getChannelParticipants(peerID * -1).then(
function (participants) {
if (participants.user_id == UserID) {
switch (participants._) {
case "channelParticipant":
return "normal";
break;
case "channelParticipantEditor":
return "Admin";
break;
case "channelParticipantModerator":
return "Admin";
break;
case "channelParticipantCreator":
return "Creator";
break;
default:
console.log('No handler for', participants._);
return "unknown";
}
// perm variable is normal :)
} else {
console.log('userid does not match');
return "userId Error";
}
});
}
// outer code
getPerm().then(function(perm) {
console.log(perm);
});

Related

NODE.JS how to loop stdin process

When i try loop my input stdin process in file parser.js it run only once, then it exit program.
How to loop my input infinitely?
input.js
function stdinLineByLine() {
return new Promise(resolve => {
console.log("Enter command: " + "\n")
let lines = '';
let buff = '';
process.stdin
.on('data', data => {
buff += data;
lines = buff.split(/\r\n|\n/).join(' ');
input += lines;
buff = "";
if(lines[lines.length - 2] === ';'){
process.stdin.emit('end');
}
})
.on('end', () => {
resolve(input);
process.stdin.destroy();
});
});
}
module.exports = stdinLineByLine;
parser.js
const input = require('./input');
const commands = require('./commands');
let createReg = /^CREATE+\s+\b[a-zA-Z0-9_]+\b$/i;
let insertReg = /^INSERT+\s+[a-zA-Z0-9_]+\s+\B"\b[a-zA-Z0-9_\w\s]+\b"+\B$/i;
let print_indexReg = /^PRINT_INDEX+\s+\b[a-zA-Z0-9_]+\b$/i;
let searchReg = /^SEARCH+\s+\b[a-zA-Z0-9_]+\b$/i;
let searchRegWhere = /^SEARCH+\s+[a-zA-Z0-9_]+\s+WHERE+\s+"\b[a-zA-Z0-9_]+\b"$/i;
let searchWhereDashReg = /^SEARCH+\s+[a-zA-Z0-9_]+\s+WHERE+\s+"\b[a-zA-Z0-9_]+\b"+\s+-+\s+"\b[a-zA-Z0-9_]+\b"$/i;
let searchWhereHooksReg = /^SEARCH+\s+[a-zA-Z0-9_]+\s+WHERE+\s+"\b[a-zA-Z0-9_]+\b"+\s+<+\d+>+\s+"\b[a-zA-Z0-9_]+\b"$/i;
function ifValid(str){
if(createReg.test(str))
return 0;
if(insertReg.test(str))
return 1;
if(print_indexReg.test(str))
return 2;
if(searchReg.test(str))
return 3;
if(searchRegWhere.test(str))
return 4;
if(searchWhereDashReg.test(str))
return 5;
if(searchWhereHooksReg.test(str))
return 6;
throw new Error("INVALID INPUT");
}
input().then(input => {
let tokens = [];
let token = ""
try {
for (let i = 0; i < input.length; i++) {
if (input[i] === " " || input[i] === ";") {
tokens.push(token);
token = "";
} else {
token += input[i];
}
}
tokens = tokens.filter(tokens => tokens !== "");
switch(ifValid(tokens.join(" "))){
case 0:
commands.create(tokens[1]);
break;
case 1:
commands.insert(tokens[1], tokens.slice(2,));
break;
case 2:
commands.print_index(tokens[1]);
break;
case 3:
commands.search(tokens[1]);
break;
case 4:
commands.searchWhere(tokens[1], tokens[3]);
break;
case 5:
commands.searchWhereDash(tokens[1], tokens[3], tokens[5]);
break;
case 6:
commands.searchWhereHooks(tokens[1], tokens[3], tokens[4][1], tokens[5]);
break;
}
console.log(tokens);
}catch(error){
console.log(error);
}
});
I tried loop it by wrapping input().then() in a function that return promise and when that function finished input it call itself recursively. it will loop my input function, but new user input includes previous user input

Imported module default.register is not a function

I'm trying to port a Node/React system over to ES6 although I'm encountering an error when compiling.
GameSettingsStore.js:91 Uncaught TypeError: _dispatcher_AppDispatcher__WEBPACK_IMPORTED_MODULE_1__.default.register is not a function at Module../src/client/stores/GameSettingsStore.js
This line that appears to be throwing an error comes from this specific line/function:
import AppDispatcher from '../dispatcher/AppDispatcher';
AppDispatcher.register((payload) => {
const { action } = payload;
switch (action.actionType) {
case Constants.ActionTypes.SET_CONTROLS_SIZE:
GameSettingsStore._setControlsSize(action.controlsSize);
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.SET_GRAPH_MODE:
GameSettingsStore._setGraphMode(action.graphMode);
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.TOGGLE_HOYTKEYS_STATE:
GameSettingsStore._toggleHotkeysState();
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.IGNORE_USER:
GameSettingsStore._ignoreUser(action.username);
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.APPROVE_USER:
GameSettingsStore._approveUser(action.username);
GameSettingsStore.emitChange();
break;
default:
GameSettingsStore.emitChange();
break;
}
return true;
});
And then the dispatcher system I'm using is the old Facebook one:
import invariant from 'invariant';
export default function () {
let _lastID = 1;
const _prefix = 'ID_';
function Dispatcher() {
this.$Dispatcher_callbacks = {};
this.$Dispatcher_isPending = {};
this.$Dispatcher_isHandled = {};
this.$Dispatcher_isDispatching = false;
this.$Dispatcher_pendingPayload = null;
}
Dispatcher.prototype.register = function (callback) {
const id = _prefix + _lastID++;
this.$Dispatcher_callbacks[id] = callback;
return id;
};
Dispatcher.prototype.unregister = function (id) {
invariant(
this.$Dispatcher_callbacks[id],
'Dispatcher.unregister(...): `%s` does not map to a registered callback.',
id
);
delete this.$Dispatcher_callbacks[id];
};
Dispatcher.prototype.waitFor = function (ids) {
invariant(
this.$Dispatcher_isDispatching,
'Dispatcher.waitFor(...): Must be invoked while dispatching.'
);
for (let ii = 0; ii < ids.length; ii++) {
const id = ids[ii];
if (this.$Dispatcher_isPending[id]) {
invariant(
this.$Dispatcher_isHandled[id],
'Dispatcher.waitFor(...): Circular dependency detected while '
+ 'waiting for `%s`.',
id
);
continue;
}
invariant(
this.$Dispatcher_callbacks[id],
'Dispatcher.waitFor(...): `%s` does not map to a registered callback.',
id
);
this.$Dispatcher_invokeCallback(id);
}
};
Dispatcher.prototype.dispatch = function (payload) {
invariant(
!this.$Dispatcher_isDispatching,
'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.'
);
this.$Dispatcher_startDispatching(payload);
try {
for (const id in this.$Dispatcher_callbacks) {
if (this.$Dispatcher_isPending[id]) {
continue;
}
this.$Dispatcher_invokeCallback(id);
}
} finally {
this.$Dispatcher_stopDispatching();
}
};
Dispatcher.prototype.isDispatching = function () {
return this.$Dispatcher_isDispatching;
};
Dispatcher.prototype.$Dispatcher_invokeCallback = function (id) {
this.$Dispatcher_isPending[id] = true;
this.$Dispatcher_callbacks[id](this.$Dispatcher_pendingPayload);
this.$Dispatcher_isHandled[id] = true;
};
Dispatcher.prototype.$Dispatcher_startDispatching = function (payload) {
for (const id in this.$Dispatcher_callbacks) {
this.$Dispatcher_isPending[id] = false;
this.$Dispatcher_isHandled[id] = false;
}
this.$Dispatcher_pendingPayload = payload;
this.$Dispatcher_isDispatching = true;
};
Dispatcher.prototype.$Dispatcher_stopDispatching = function () {
this.$Dispatcher_pendingPayload = null;
this.$Dispatcher_isDispatching = false;
};
return Dispatcher;
}
I'd much prefer to use a better alternative, or at least fix this issue if anyone could point me in the right direction?
The default export looks like an (obsolete) wrapper function. You might need to "unwrap" it first:
import AppDispatcherWrapper from '../dispatcher/AppDispatcher';
const AppDispatcher = AppDispatcherWrapper();
AppDispatcher.register((payload) => {
// ...
});

How do I run function inside a class. Javascript

I am having hard time calling a function inside a class. When I started working on this, I had it running, but after making revisions, I cant get it working :((
You can ignore my alerts because I just put them in there to check to see if the function gets called or not.
I have function "Unit" which is a class for me. then I call it by below.
From below code, that new Unit(args) does not get completed. It stops at this.direction=this.setDirection();
and this.setDirection() is not called for some reason. Can anyone take a look and tell me what went wrong?
Thanks!
var teamBlack = [];
var bking = new Unit("black", "king", new Coords(3,1, false));
teamBlack.push(bking);
function Unit(team, type, coords) {
alert("Unit started " + count);
this.team = team;
this.type = type;
this.position = coords;
this.highlight = false;
alert("before setdirection");
this.direction = this.setDirection();
alert("this " + this.type);
this.setDirection = function () {
alert("setDirection Started ");
alert(this.type);
var tempDir = [];
switch (this.type) {
case "king" :
alert("this is king");
tempDir = [this.N(), this.NW(), this.W(), this.SW(), this.S(), this.SE(), this.E(), this.NE()];
break;
case "bishop" :
tempDir = [this.NW(), this.SW(), this.SE(), this.NE()];
break;
case "rook" :
tempDir = [this.N(), this.S(), this.W(), this.E()];
break;
case "pawn" :
{
if (this.team == "white") {
tempDir = [this.S()];
} else {
tempDir = [this.N()];
}
break;
}
case "queen" :
{
if (this.team == "white") {
tempDir = [this.N(), this.W(), this.SW(), this.S(), this.SE(), this.E()];
} else {
tempDir = [this.N(), this.NW(), this.W(), this.S(), this.E(), this.NE()];
}
break;
}
}
tempDir = tempDir.filter(function (dir) {
return dir.x > -1 && dir.x < 3 && dir.y > -1 && dir.y < 4 && dir.c == false;
});
return tempDir;
}
}
This code is wrong because you try call function that is not exist yet in your class. I recommend you to move this function in prototype. For example:
function Unit() {
//this is your constructor
}
Unit.prototype.setDirection = function() {
//your code of setDirection function
}
Make sure variables are defined, then put this.setDirecton = function()... before calling this.setDirection().
See JSFiddle.
You need to use the setDirection function as a prototype of your Unit class.
Unit.prototype.setDirection = function() {
//setDirection functionality
}
Within the prototype you have access to your class properties via this.
Check this jsFiddle: https://jsfiddle.net/urtr3quc/
I would improve your code by separating the responsibilities:
//create the class Unit
function Unit(team, type, coords) {
alert("Unit started " + count);
this.team = team;
this.type = type;
this.position = coords;
this.highlight = false;
}
Then you specify new method for your class:
Unit.prototype.setDirection = function () {
alert("setDirection Started ");
alert(this.type);
var tempDir = [];
switch (this.type) {
case "king" :
alert("this is king");
tempDir = [this.N(), this.NW(), this.W(), this.SW(), this.S(), this.SE(), this.E(), this.NE()];
break;
case "bishop" :
tempDir = [this.NW(), this.SW(), this.SE(), this.NE()];
break;
case "rook" :
tempDir = [this.N(), this.S(), this.W(), this.E()];
break;
case "pawn" :
{
if (this.team == "white") {
tempDir = [this.S()];
} else {
tempDir = [this.N()];
}
break;
}
case "queen" :
{
if (this.team == "white") {
tempDir = [this.N(), this.W(), this.SW(), this.S(), this.SE(), this.E()];
} else {
tempDir = [this.N(), this.NW(), this.W(), this.S(), this.E(), this.NE()];
}
break;
}
}
tempDir = tempDir.filter(function (dir) {
return dir.x > -1 && dir.x < 3 && dir.y > -1 && dir.y < 4 && dir.c == false;
});
alert("before setdirection");
this.direction = tempDir;//setMethod doesn't return thing but set something somewhere
alert("this " + this.type);
};
and now you invoke your class instance:
var teamBlack = [];
var bking = new Unit("black", "king", new Coords(3,1, false));
bking.setDirection();
teamBlack.push(bking);
I suggest you to take a look on this link

Cannot read property length of undefined - Javascript

I'm new in javascript the main goal of this code is to type a question in the textbox the browser will check the question if it was in the switches statements and get the answer than write it on the paragraph's id="lable".
The function randomArray(z)-line[8]- return a random array value .
What's hapenning : Typed :"undefined" on the paragraph which has "lable" as an id .
.........................
The HTML code :
<body>
<img src="Alexs_face.png">
<p style="border:2px black solid; margin:100px 400px 50px 400px">Ask me !</p>
<p id="lable"></p>
<input id="input" type="text" autocomplete="off">
<input id="send" type="button" onclick="dosome()" value="Send">
<input id="delete" type="button" onclick="deleteVal()" value="Delete"></body>
The Javascript:
var greating , userName;
var firstHello = [[greating+userName+", How can I help you ?" ], ["Hi "+userName+" how can i help ?"] ,[ greating+", how can i help ?"]];
dosome () ;
function randomArray (z) {
var index = Math.floor(Math.random() * z.length);
return z[index];
};
function getVal() {
write(randomArray (firstHello)); /* <------ trying to write a radom value from the firstHello array
*/
var ask = document.getElementById("input").value;
return ask ;}
var ask = getVal();
function write (x){
var lable = document.getElementById("lable").innerHTML = x;
return lable ;
};
//Capitalize the first letters func :
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
//..............
//............................... you can ignore this function
function dosome () {
var ask = getVal();
var question = ask.split(" ");
var date = new Date().toTimeString().split(" ")[0]; ;
var userName ="Med" ;
//5// give you different "greatings" according to ur time
if (date >= "06:00:00" && date <="11:00:00"){
greating = "Good morning ";
var alertTime=""
}
else if (date >= "11:00:00" && date <= "15:00:00"){
greating = "Good afternoon ";
var alertTime=""
}
else if (date >= "15:00:00" && date <="22:00:00"){
greating = "Good evening ";
var alertTime=""
}
else {
greating = " You should have some sleep !";
var alertTime = greating ;
};
//5//end
//
if (question[0] === "what"){
switch ( question[1]){
case "time":
switch (question[2]){
case "is":
switch (question[3]){
case "it":
write("The time is :"+date+alertTime);
break;
default:
};
break;
default:
} ;
break;
case "is":
switch (question[2]){
case "your" :
switch (question[3]){
case "name":
write("Alex !");
break;
case "father":
write("Medardo Erabti , he made me !");
break;
default:
};
break;
case "my":
switch (question[3]){
case "name":
write("Alex !");
break;
default:
};
break;
default:
};
break;
default: write("unknown");
};}
else if (question[0] === "my"){
switch (question[1]){
case "name":
switch(question[2]){
case "is":
userName = capitalize(question[3]);;
alert("Your name is saved, "+userName);
break;
default:
};
break;
default:
};
}
else if (question[0] === "should" || "could" || "may" || "can" ) {
switch (question[1]) {
case "i" :
switch(question[2]){
case "sleep":
write("Sure ! you can sleep if you want to !!");
break;
default:
}
break;
default:
};
}
if (question[0] === "who"){
switch (question[1]){
case "are":
write ("I'm Alex !");
break;
case "am":
write ("My leader !");
default:
}
};
return userName,greating ;
};
function deleteVal () {
var x = document.getElementById("lable").innerHTML = "" ;
return x ;
};
What I have tried:
Tried to disable the 'z' parametr in the function 'randomArray(z)' and replace it with the name of the array "firstHello" , Its type "undefined in the paragraf that has "lable" as an id .
In the dosome function you create a local variable named userName, the same as the global variable. The local variable will shadow the global variable for the code inside the function, so the global variable will still be undefined after calling the function.
Notes about the code in the randomArray function:
You are using Math.floor instead of Math.random.
Don't use Math.round when creating an integer random number, that will make the first and last number occur half as often as the other numbers. Use Math.floor instead.
Your loop goes two items beyond the last item in the array.
You don't need to loop at all to get an item with a specific index.
Here is code that just shows the modified randomArray function and code to call it:
var greating = 'Hello', userName = 'sir';
var firstHello = [
[ greating + " " + userName + ", How can I help you ?" ],
[ "Hi " + userName + " how can i help ?" ],
[ greating + ", how can i help ?" ]
];
function randomArray(z) {
var index = Math.floor(Math.random() * z.length);
return z[index];
}
console.log(randomArray(firstHello));

if/else statement not registering if

My code seems to log the if statement as false, even though if I console.log the conditions it returns as true. Why is it doing that? (the code , that is not working is indicated by error not bypassing.)
function StaffMember(name,discountPercent){
this.name = name;
this.discountPercent = discountPercent;
}
function Stock(item){
this.item = item;
}
//Global Variables
var staffMembers = {};
var sally = new StaffMember("Sally",0.05);
staffMembers['sally'] = sally;
var bob = new StaffMember("Bob",0.10);
staffMembers['bob'] = bob;
var me = new StaffMember("Aaron",0.20);
staffMembers['me'] = me;
//item variables
var eggs = new Stock("Eggs");
var milk = new Stock("Milk");
var magazine = new Stock("Magazine");
var chocolate = new Stock("Chocolate");
//item Objects
var Stock = {};
Stock['eggs'] = eggs;
Stock['milk'] = milk;
Stock['magazine'] = magazine;
Stock ['chocolate'] = chocolate;**
var cashRegister = {
total:0,
lastTransactionAmount: 0,
add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item,quantity){
switch (item){
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
// Create a new method applyStaffDiscount here
applyStaffDiscount : function(employee){
this.total -= this.total*(employee.discountPercent);
}
};
$(document).ready(function(){
$('#target2').hide();
$('#check').on('click', function(e){
e.preventDefault();
var item = $('#item').val();
var quantity = $('#quantity').val();
var staff = $('#staff').val();
cashRegister.scan(item, quantity);
//ERROR IN CODE NOT BYPASSING
if(item === Stock['item'] && quantity > 0) {
cashRegister.scan(item, quantity);
}
///
else {
alert("This Item Does Not Exist!");
}
if(staff.length > 0 && typeof staffMembers[staff] !='undefined'){
cashRegister.applyStaffDiscount(staffMembers[staff]);
}
var output = document.getElementById("result");
result.innerHTML = 'Your bill is ' + cashRegister.total.toFixed(2);
$('#target2').fadeIn(5000)
// .animate({opacity: 0.5}, 3000)
.fadeOut(5000);
});
$('#target').submit(function(){
var info = $(this).serializeJSON();
console.log(info);
var data = JSON.parse('[info]');
console.log(data);
return false;
});
});
Stock['item'] is going to return undefined because Stock['item'] is not declared. You declare Stock['milk'], Stock['magazine'],Stock['eggs'], and Stock['chocolate'], but not Stock['item']. If you were trying to use it as a variable, you should remove the quotes.
You are also overwriting your "Stock" function with a "Stock" object, which is not causing trouble right now but it could cause issues later down the line. You should rename those to be different if possible.
Try using Stock[item] !== undefined && quantity > 0 in place of your current if expression
You did not post your HTML or a working fiddle, but my guess is your if statement should be:
if(item === Stock[item] && quantity > 0) {
cashRegister.scan(item, quantity);
}
Stock['item'] returns undefined as you're not calling it either with an object context like obj.Stock() or after using bind or call, so this is undefined. It's not returning anything either, so no assignment is made. I'm assuming $('#item').val() also. $('#item') is most likely null, triggering a runtime error and stopping your if sentence.

Categories

Resources