How to passing data from Javascript to lua - javascript

How to passing data from javascript to lua ?
for(var i = 1; i<= totalsd; i++){
if( eval('q' + i) == null || eval('q' + i) == ''){
var number = i
alert(number)
$.post('http://ns_45/unfinishtk',JSON.stringify({number}));
return false;
}
}
Lua
RegisterNUICallback('unfinishtk', function(number)
print(number)
end)
When i try to do alert , it's shown the correct value , but when i try to pass it to lua , it's wont detect the value

SOLVED
for(var i = 1; i<= totalsd; i++){
if( eval('q' + i) == null || eval('q' + i) == ''){
var number = i
$.post('http://ns_45/unfinishtk',JSON.stringify({number:number}));
return false;
}
}
Lua
RegisterNUICallback('unfinishtk', function(data,cb)
print(data.number)
end)

Related

Bubble Sort in never ending loop

I have the following data:
I basically want the 5,6,7 records to be at the very top of the list ordered by eta. The rest I am OK with as they stand. since they do not realy have an eta.
My JS function :
bubbleSortETA : function(array) {
var swapped;
do {
swapped = false;
for(var i = 0; i < array.length; i++) {
console.log('array[i]');
console.log(array[i]);
console.log('array[i+1]');
console.log(array[i+1]);
var thisRowEta;
var nextRowEta;
if (array[i] && typeof(array[i].eta) != "undefined"){
thisRowEta = array[i].eta;
}else{
thisRowEta = 1000; //so it appears at the bottom???
}
if (array[i+1] && typeof(array[i+1].eta) != "undefined"){
nextRowEta = array[i+1].eta;
}else{
nextRowEta = 1000;
}
if(array[i] && array[i + 1] && typeof(array[i].walkInDetails) != "undefined" && typeof(array[i+1].walkInDetails) != "undefined" && (thisRowEta != nextRowEta)){
this.swap(array, i, i + 1);
console.log('we swapped...');
swapped = true;
}
}
} while(swapped);
console.log(array);
return array;
}
It goes into this never ending loop. I have tried looking at output statements but am unable to understand why it is going into infinite loop.
Any tips?

How do i return the result of all loops in javascript?

I am trying to insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers, but I am only getting the last result.
I want to print out all the elements in the array.
For example: if num is 4546793 the output should be 454*67-9-3. I Did not count zero as an odd or even number.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i] === 0) {
continue;
}
if (num[i - 1] % 2 == 0 && num[i] % 2 == 0) {
result = num[i - 1] + "*" + num[i];
continue;
}
if (num[i - 1] % 2 == !0 && num[i] % 2 == !0) {
result = num[i - 1] + "-" + num[i];
continue;
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
You do not need to check as if&continue. Inserting given numbers to the result string and only adding "-" when index and previous are odd, and "*" when index and previous are even.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i]%2 ===0) {// even
if(i !== 0 && num[i-1]%2===0){// previous is even either
result+="*"+num[i];
}else{
result+=num[i];
}
}else{// odd
if(i !== 0 && num[i-1]%2===1){// previous is odd either
result+="-"+num[i];
}else{
result+=num[i];
}
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Try this :)
function test(a){
let result=""
for(let i=0; i < a.length; i++){
if(a[i] != 0 && a[i-1] % 2 == 0 && a[i] % 2 == 0){
result = result + '*' + a[i]
}
else if (a[i] != 0 && a[i-1] % 2 != 0 && a[i] % 2 != 0){
result = result + '-' + a[i]
}
else{
result = result + a[i]
}
}
return result
}
console.log(test([4,5,4,6,7,9,3]));
As everyone has identified, the problem is you are not adding to result.
But here is a suggestion to make your code easier to read
// These one line functions make your code easier to read
function IsEven(num){
return num % 2 === 0;
}
function IsOdd(num){
return num % 2 !== 0;
}
function StringChallenge(numArray) {
// return empty string if not an array or empty array
if(!Array.isArray(numArray) || numArray.length === 0) return "";
let result = "" + numArray[0]; // use "" to coerce first element of numArray from number to string
for (let i = 1; i < numArray.length; i++) {
// focus on the conditions to determine the separator you want between each element
separator = "";
if (numArray[i] !== 0) {
if (IsEven(numArray[i]) && IsEven(numArray[i - 1])) {
separator = "*";
} else if (IsOdd(numArray[i]) && IsOdd(numArray[i - 1])){
separator = "-";
}
}
// build the result
result += separator + numArray[i];
}
return result;
}
I will do that this way :
== some advices for 2 cents ==
1 - try to make your code as readable as possible.
2 - use boolean tests rather than calculations to simply do a parity test
3 - ES7 has greatly improved the writing of JS code, so take advantage of it
console.log(StringChallenge([4,5,4,6,7,9,3])); // 454*67-9-3
function StringChallenge( Nums = [] )
{
const
isOdd = x => !!(x & 1) // Boolean test on binary value
, isEven = x => !(x & 1) && x!==0 // zero is not accepted as Even value
;
let result = `${Nums[0]??''}`; // get first number as
// result if Nums.length > 0
for (let i=1; i<Nums.length; i++)
{
if ( isOdd(Nums[i-1]) && isOdd(Nums[i]) ) result += '-';
if ( isEven(Nums[i-1]) && isEven(Nums[i]) ) result += '*';
result += `${Nums[i]}`; // same as Nums[i].toString(10);
}
return result
}
I hope this helps. I tried to keep it as simple as possible.
function StringChallenge(num) {
//start with a string to concatenate, or else interpreter tries to do math
operations
let result = num[0].toString();
function checkOdd(num){ //helper function to check if odd
return num % 2
}
for (let i = 0; i < num.length - 1; i++) {
if (checkOdd(num[i]) && checkOdd(num[i+1])) { //checks if both odd
result += `-${num[i+1]}`; //adds - and next number
} else if (!checkOdd(num[i]) && !checkOdd(num[i+1])) { //checks if both even
result += `*${num[i+1]}`; //adds * and next number
} else { //otherwise
result += num[i+1]; //just add next number
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Use +=. And, change your logic, your code prints out "4*67-99-3".
The zero check was pretty hard for me I hope the variables in my code explain itself. If not, let me know.
function even(num) {
return num % 2 === 0;
}
function odd(num) {
return num % 2 !== 0;
}
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
var currentZero = num[i] === 0
var previousZero = num[i-1] === 0
var bothEven = even(num[i]) && even(num[i-1])
var bothOdd = odd(num[i]) && odd(num[i-1])
var firstNumber = (i === 0)
if (!currentZero) {
if (firstNumber) {
result += num[i]
} else {
if (bothEven && !previousZero) {
result += "*" + num[i]
} else if (bothOdd && !currentZero) {
result += "-" + num[i]
} else {
result += num[i]
}
}
}
}
return result;
}
console.log(StringChallenge([0,4,5,0,4,6,7,9,3]));

Cannot read property length null error when used with regular expressions

I'm a javascript beginner doing some CodeWars.com questions. I came across this question and I'm stuck due to a "cannot read property length null" error. I've tried to look up that error and can't find what the problem is in my program.
The assignment is:
"Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contains any char."
And this is what I've written so far:
function XO(str) {
var x = "x";
var o = "o";
var numX = str.match(/x/gi).length;
var numO = str.match(/o/gi).length;
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
}
}
if (numX === -1 && numO === -1){
return true;
}
}
XO("xoxo");
The assignment also says that if there is neither an X or an O then the program should return true.
This will not give you that error. When there are no matches, the match function returns null and you cannot get the length of null. A few extra lines solves this issue.
function XO(str) {
var x = "x";
var o = "o";
var numX = 0;
var numO = 0;
var xMatch = str.match(/x/gi);
var oMatch = str.match(/o/gi);
if (xMatch) {
numX = xMatch.length;
}
if (oMatch) {
numO = oMatch.length;
}
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
} else {
return false;
}
}
if (numX === -1 && numO === -1){
return true;
} else {
return false;
}
}
console.log(XO("ddd"));
I think you are making this problem more complex than it has to be.
All you need to do is make the string lowercase(to account for case insensitive), traverse the string, and when it finds an x, add 1 to a counter, and when you find and o, decrease 1 from the counter.
If it ends at 0, you return true, else you return false. There's no need for regexes
function XO(str){
var count = 0;
str = str.toLowerCase();
for(var i = 0; i < str.length; i++){
if(str[i] === 'x') count++;
if(str[i] === 'o') count--;
}
return count === 0 ? true : false;
}
Yes you have to check the return value of match is not null before checking the length property. However
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
}
}
looks like an infinite loop if either string contains lower case 'x' or 'o' and there are a different number of each.
More simply:
function XO(str)
{ var matchX = str.match(/x/gi);
var matchY = str.match(/o/gi);
return (matchX && matchY) ? matchX.length == matchY.length : !matchX && !matchY;
}

all valid combinations of n-pair of parenthesis

I am learning js now..
I am trying to write a simple js programme..
what I am trying to do is to print all valid combinations of n-pair
of parenthesis(properly opened and closed)
eg (), (()()),(())
i have written the logic can you tell me whether its correct or not
https://jsfiddle.net/e7mcp6xb/
module.exports = Parentheses = (function() {
var _isParenthesesMatch = function(str) {
var parentheses = str.length;
var rightParentheses = '(';
var leftParentheses = ')';
var rightCount = 0;
var leftCount = 0;
for(i=0;i<=str.length;i++){
if(rightParentheses == str.charAt(i))
{
rightCount++;
}
else if(leftParentheses == str.charAt(i))
{
leftCount++;
}
}
if(rightCount == leftCount){
return true;
}
else(rightCount != leftCount){
return false;
}
}
}());
The check is wrong, but You can fix it easily: In each step of the for loop the number of opening parenthesis cannot be smaller than the number of closing ones:
if (rightCount < leftCount)
return false;
The whole function should look like this:
function(str) {
var rightParentheses = '(';
var leftParentheses = ')';
var rightCount = 0;
var leftCount = 0;
for (var i = 0; i <= str.length; i++) {
if (rightParentheses == str.charAt(i))
rightCount++;
else if (leftParentheses == str.charAt(i))
leftCount++;
if (rightCount < leftCount)
return false;
}
return rightCount == leftCount;
}
If You'd like to generate all valid strings, you can use this function:
function nPair(n) {
if (n == 0)
return [""];
var result = [];
for (var i = 0; i < n; ++i) {
var lefts = nPair(i);
var rights = nPair(n - i - 1);
for (var l = 0; l < lefts.length; ++l)
for (var r = 0; r < rights.length; ++r)
result.push("(" + lefts[l] + ")" + rights[r]);
}
return result;
}
// result of nPair(3):
// ["()()()", "()(())", "(())()", "(()())", "((()))"]
Try this, i have modified your code a little bit. Modification and its explanation is marked in comments.
module.exports = Parentheses = (function() {
var _isParenthesesMatch = function(str) {
var parentheses = str.length;
var rightParentheses = '(';
var leftParentheses = ')';
var count=0;
for(i=0;i<str.length;i++){
//this is to check valid combination start always from ( and end with )
if(str.charAt(0)==rightParentheses && str.length-1==leftParentheses)
{
if(rightParentheses == str.charAt(i))
{
count++; //this will calculate how many times rightParentheses is present & increment count by 1
}
else if(leftParentheses == str.charAt(i))
{
count--; //this will simply decrement count to match valid sequence
}
}
if(count==0){
return true;
}
}
}());
Your function is wrong, try checking if left and right parenthesis and balanced:
function isValid(str){
var stripedStr = str.replace(/[^\(\)]+/g, '');
return stripedStr.split('').reduce(function(a, b){
return a > -1 ? b === '(' ? a + 1 : a - 1 : -1;
}, 0) === 0;
}
stripedStr - use replace() to remove any characters that are not ( or ).
split('') - returns an array so we can use reduce.
reduce() - applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.
The reduce starts with 0 as initial value and in the reduce function we count parenthesis
(+1 for (, -1 for ) )
Our string is valid if our counter never goes below 0 and we end up with 0.
You can write the reduce function like this too:
function(previousValue, currentValue){
if (previousValue > -1){
if (currentValue === '('){
return previousValue + 1;
} else {
return previousValue - 1;
}
}
return -1;
}
This is equivalent to:
function(a, b){
return a > -1 ? b === '(' ? a + 1 : a - 1 : -1;
}
It is wrong, because your function will return true for this example ))(( or this ())(()

Removing unwanted characters from textbox with JQuery

What I would like to get some input on is how to remove certain characters from a textbox (or textarea) with JQuery. I have the code in C# but I can´t seem to translate that to JQuery javascript. My problem is that I don´t know how to get the value from a textbox as a character array which I then can loop through and compare against a given set of unwanted characters.
This is how "far" I have come in JQuery:
$("input[type=text], textarea").change(function() {
// code here
});
This is my code in C#:
for (int i = 0; i < charArray.Length; i++)
{
current = charArray[i];
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)))
_validXML.Append(current);
}
return _validXML.ToString().TrimEnd((char)32, (char)160) ;
UPDATE:
I went with a combination of some answers below (I will upvote them) and my final JQuery looks like this and works:
$(document).ready(function() {
$(":text, textarea").change(function() {
var text = "";
var arr = $(this).val()
$.each(arr, function(i) {
var c = arr.charCodeAt(i);
if ((c == 0x9) ||
(c == 0xA) ||
(c == 0xD) ||
(c >= 0x20 && c <= 0xD7FF) ||
(c >= 0xE000 && c <= 0xFFFD))
{
text += arr.charAt(i);
}
});
$(this).val(text);
});
});
Thanks all!
Would't this be the case for regular expressions, like:
$("input[#type='text'], textarea").change(function() {
this.value = this.value.replace(/[^\w\d]+/gim,"");
});
Textarea:
<textarea id="item" name="item" rows="5" cols="80">Some text in here</textarea>
jQuery code:
var text = $('#item').val();
var newtext = "";
for (var i = 0; i < text.length; i++) {
var c = text.charCodeAt(i);
if ((c == 0x9) || (c == 0xA) || (c == 0xD) ||
(c >= 0x20 && c <= 0xD7FF) ||
(c >= 0xE000 && c <= 0xFFFD)) {
newtext += text[i];
}
}
$('#item').val(newtext);
This has actually very little to do with jQuery, methinks, except to access the text data and set it again.
You can use the charCodeAt() method combined with the length property of strings to loop through the characters in the string.
Something like:
$("input[type=text], textarea").change(function() {
var text = $(this).val()
for(var i = 0; i < text.length; ++i) {
var currentChar = text.charCodeAt(i);
// Do something with it...
});
My initial version used charAt(), but since it looks like you're dealing with Unicode code points, charCodeAt() is more appropriate.
Use an event observer (onkeydown / onkeypress / onkeyup) on the input/textarea, get the key pressed, if the key is an unwanted character, stop the event from happening.
$("input[type=text], textarea").observe('keypress', function(e) {
var keynum;
if(window.event)
{
keynum = e.keyCode
}
else if(e.which)
{
keynum = e.which
}
if(keynum == '13' || keynum == 'something else' || [...])
{
Event.stop(e);
}
});
to get the value of textarea try:
$('input[type=textarea]').change(function(){
var value = $(this).val();
...........
});
to remove unwanted character try this example .. i copy from the jquery documentation (jQuery.grep())
var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
$("div").text(arr.join(", "));
arr = jQuery.grep(arr, function(n, i){
return (n != 5 && i > 4);
});
$("p").text(arr.join(", "));
arr = jQuery.grep(arr, function (a) { return a != 9; });
$("span").text(arr.join(", "));
I prefer to stop the character from getting entered in the first place, using this type of javascript function (from my shady past):
each input control has something like this on it:
onkeypress='checkKey(this,"a-zA-Z0-9","N","10");'
the function looks like:
//****************************************************************************
// Function: checkKey()
// Author: Ron Savage
// Date: 10-11-2004
//
// Description: This function tests reg exp syntax.
//****************************************************************************
function checkKey(textControl, reExpr, allCaps, maxlen)
{
popupMessage.hide();
keyStr = String.fromCharCode(event.keyCode);
textLength = textControl.value.length;
if (allCaps == 'Y')
{
keyStr = keyStr.toUpperCase();
event.keyCode = keyStr.charCodeAt(0);
}
if ( reExpr != '' )
{
reString = '[^' + reExpr + ']';
re = new RegExp(reString, 'g');
//alert('RE: ' + reString);
result = keyStr.match(re);
if (result)
{
beep();
event.returnValue = false;
showPopupMessage(textControl, result.toString() + ' not allowed!');
}
}
if ( textLength > maxlen )
{
beep();
event.returnValue = false;
showPopupMessage(textControl, 'Max length [' + maxlen + '] exceeded!');
}
//alert('Key: ' + keyStr + ' code: ' + event.keyCode);
}

Categories

Resources