Getting empty data when I'm passing value to an array - javascript

I'm just wondering on how I got an empty object, and how to fix it.
tax1 has 16 objects
Payroll controller
if (vm.period === 'Semi-Monthly') {
for (var x = 0; x < vm.tax1.length; x++) {
if (vm.tax1[x].eventType === 'sm') {
vm.tax2[x] = vm.tax1[x];
}
}
} else if( vm.period === 'Monthly'){
for (var y = 0; y < vm.tax1.length; y++) {
if (vm.tax1[y].eventType === 'm') {
vm.tax2[y] = vm.tax1[y];
}
}
}
Output:

Indices are difficult to read and error-prone, you can consider using .push or .filter
Using .push
vm.tax2 = [];
var eventType;
if (vm.period == 'Semi-Monthly') {
eventType = 'sm';
}
else if( vm.period == 'Monthly') {
eventType = 'm';
}
vm.tax1.forEach(function(item) {
if (item.eventType == eventType) {
vm.tax2.push(item);
}
});
Using .filter
var eventType;
if (vm.period == 'Semi-Monthly') {
eventType = 'sm';
}
else if( vm.period == 'Monthly') {
eventType = 'm';
}
vm.tax2 = vm.tax1.filter(function(item) {
return (item.eventType == eventType);
});

Silly mistake from my side..
here's the fix
var x = 0;
var y = 0;
if (vm.period === 'Semi-Monthly') {
for ( x = 0; x < vm.tax1.length; x++) {
if (vm.tax1[x].eventType === 'sm') {
vm.tax2[y] = vm.tax1[x];
y++;
}
}
} else if( vm.period === 'Monthly'){
for ( x = 0; x < vm.tax1.length; x++) {
if (vm.tax1[x].eventType === 'm') {
vm.tax2[y] = vm.tax1[x];
y++;
}
}
}

Related

Uncaught Typeerror: Cannot read properties of undefined (reading 'split') error for Chrome extension code

Please I am working on an extension to discover where apples are on a game website but I keep seeing this error causing it to not work properly. I have tried a few things but they just make the script to not work at all. The error is one line 142 with the attr() function:
Uncaught Typeerror: Cannot read properties of undefined (reading
'split').
This is the full code:
var string_id = 1231414;
var page_title = document.title;
function sender_cheker(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.onload = function() {
document.onclick = ({target}) => {
page_title = document.title;
console.log(page_title);
if (page_title.indexOf('Apple Of Fortune') !== -1)
{
let parent = target;
clas_name_parent = parent.parentNode.parentNode.className;
if (clas_name_parent == "fortune-apple-bet__btn fortune-apple-btn fortune-apple-btn--bet")
{
arry_apple_start = creete_new_str();
$('.image_dop_for_provide').remove();
setInterval(print_result_apple,1000);
}
}
}
function creete_new_str()
{
var summ_true_apple = new Array();
var summ_false_apple = new Array();
var array_good_bed_apple = new Array();
summ_true_apple[0] = 4;
summ_true_apple[1] = 4;
summ_true_apple[2] = 4;
summ_true_apple[3] = 4;
summ_true_apple[4] = 3;
summ_true_apple[5] = 3;
summ_true_apple[6] = 3;
summ_true_apple[7] = 2;
summ_true_apple[8] = 2;
summ_true_apple[9] = 1;
summ_false_apple[0] = 1;
summ_false_apple[1] = 1;
summ_false_apple[2] = 1;
summ_false_apple[3] = 1;
summ_false_apple[4] = 2;
summ_false_apple[5] = 2;
summ_false_apple[6] = 2;
summ_false_apple[7] = 3;
summ_false_apple[8] = 3;
summ_false_apple[9] = 4;
var napravlen = 0;
for(i=0;i<10;i++)
{
array_good_bed_apple[i] = new Array();
if (napravlen == 0)
{
for(k=0;k<5;k++)
{
var rand_var_for_this = coinToss();
if (rand_var_for_this == true)
{
if (summ_true_apple[i] > 0)
{
array_good_bed_apple[i][k] = 1;
summ_true_apple[i] --;
}
else
{
array_good_bed_apple[i][k] = 0;
summ_false_apple[i] --;
}
}
else
{
if (summ_false_apple[i] > 0)
{
array_good_bed_apple[i][k] = 0;
summ_false_apple[i] --;
}
else
{
array_good_bed_apple[i][k] = 1;
summ_true_apple[i] --;
}
}
}
}
else
{
for(k=4;k>=0;k--)
{
var rand_var_for_this = coinToss();
if (rand_var_for_this == true)
{
if (summ_true_apple[i] > 0)
{
array_good_bed_apple[i][k] = 1;
summ_true_apple[i] --;
}
else
{
array_good_bed_apple[i][k] = 0;
summ_false_apple[i] --;
}
}
else
{
if (summ_false_apple[i] > 0)
{
array_good_bed_apple[i][k] = 0;
summ_false_apple[i] --;
}
else
{
array_good_bed_apple[i][k] = 1;
summ_true_apple[i] --;
}
}
}
}
if (napravlen == 0)
napravlen = 1;
else
napravlen = 0;
}
return array_good_bed_apple;
}
function print_result_apple()
{
var row_naw = $('div[class="fortune-apple-field__row fortune-apple-row fortune-apple-row--is-active"] button',0).attr('data-item').split('-');
var ind = -1;
for(i=0;i<10;i++)
{
if (i == 0)
ind = 9;
if (i == 1)
ind = 8;
if (i == 2)
ind = 7;
if (i == 3)
ind = 6;
if (i == 4)
ind = 5;
if (i == 5)
ind = 4;
if (i == 6)
ind = 3;
if (i == 7)
ind = 2;
if (i == 8)
ind = 1;
if (i == 9)
ind = 0;
if (row_naw[0] == ind)
{
$('.image_dop_for_provide').remove();
for(k=0;k<5;k++)
{
if (arry_apple_start[i][k] == 1)
$('button[data-item="'+ind+'-'+k+'"]').html('<img class="image_dop_for_provide" src="https://i.ibb.co/WtvVkbC/apple-t-f.png" style="opacity: 0.4; width:100%">');
else
$('button[data-item="'+ind+'-'+k+'"]').html('<img class="image_dop_for_provide" src="https://i.ibb.co/ZWfxcY9/apple-f-t.png" style="opacity: 0.4; width:100%">');
}
}
}
}
function coinToss()
{
return (Math.floor(Math.random() * 2) === 0);
}
};
This message:
Uncaught Typeerror: Cannot read properties of undefined (reading ’split’)
indicates that the string you are trying to call split(‘-') on is undefined. That means that the result of $('div[class="fortune-apple-field__row fortune-apple-row fortune-apple-row--is-active"] button',0).attr('data-item’) must be undefined.
There’s not enough detail to diagnose further.

No response from recursive function

I want to create a function that is able to determine if a number is same or palindrome. if a given number is palindrome or same then return 2 otherwise if it is not palindrome or same then i need check it twice by increment the given number by 1. after that if it palindrome or same then return 1. if no palindrome or same number found then return 0. i write the function which is giving me the exact result when i give the number as 11211 but the function don't show any response if i enter 1122 or other random value. please help me to find where the error of my function.
function sameOrPalindrome(num) {
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
here is my solution to this problem:
function reversedNum(num) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(num)
)
}
function sameOrPalindrome(num) {
if (num === reversedNum(num)) {
return 2;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
Perhaps not using recurse - I think your function loops
const allEqual = arr => arr.every( v => v === arr[0] )
const sameOrPalin = num => {
const str = String(num);
let arr = str.split("")
if (allEqual(arr)) return 2
arr.reverse();
if (arr.join("") === str) return 1;
return 0
};
console.log("1111",sameOrPalin(1111));
console.log("2111",sameOrPalin(2111));
console.log("2112",sameOrPalin(2112));
console.log("1234",sameOrPalin(1234));
for (let i = 2111; i<=2113; i++) console.log(i,sameOrPalin(i));
Question: I assumed if palindrome test is true at first time then return 2. if not try incrementing by one and test the palindrome again . if true return 1 else try incrementing for last time and check the palindrome if true return 1 else 0.
Store string into array first and do arr.reverse().join("") to compare
let arr=num.toString().split("");
if(num.toString() == arr.reverse().join(""))
function sameOrPalindrome(num, times) {
let arr = num.toString().split("");
if (num.toString() == arr.reverse().join("")) {
if (times == 3) return 2
else return 1;
} else if (times > 0) {
num++; times--;
return sameOrPalindrome(num, times);
} else return 0
}
console.log(sameOrPalindrome(123321, 3));
console.log(sameOrPalindrome(223321, 3));
console.log(sameOrPalindrome(323321, 3));
Your function needs to know if it should not call itself any more, e.g. when it's doing the second and third checks:
function sameOrPalindrome(num,stop) { // <-- added "stop"
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else if(!stop) { // <-- check of "stop"
num++;
al = sameOrPalindrome(num,true); // <-- passing true here
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num,true); // <-- and also here
if (al == 2) {
return 1;
}
}
}
return 0;
}
for(let i=8225;i<8230;i++)
console.log(i,sameOrPalindrome(i));
function check_palindrom(num){
var c1 = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] == revArray[i]) {
c1++;
}
}
if(c1==0){
return 2;
}else{
return 1;
}
}//check_palindrom
function my_fun_check_palindrome(mynum){
//console.log(mynum);
var num = mynum;
var c2 = 0;
var al = 0;
var normalArray = mynum.toString().split("");
var revArray = mynum.toString().split("").reverse();
for (var j = 0; j < normalArray.length; j++) {
if (normalArray[j] == revArray[j]) {
c2++;
}
}
if(c2==0){
console.log('Number is palindrome. Return Value :'+ 2);
}
if(1){
console.log('checking again with incremeting value my one');
num = parseInt(num)+1;
al = check_palindrom(num);
if(al==2){
console.log('Number is palindrome. Return Value :'+ 1);
}else{
console.log('Number is not palindrome. Return Value :'+ 0);
}
}
}//my_fun_check_palindrome
console.log(my_fun_check_palindrome(1122));
console.log(my_fun_check_palindrome(11221));
We should always strive to make function more effiecient... you dont need to run full loop. plus actual checking of palindrome can me modularized
function isSameOrPalindrome(num) {
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse(),
i;
for (i = 0; i < normalArray.length / 2; i++) {
if (normalArray[i] !== revArray[i]) {
break;
}
}
if (i >= normalArray.length/2) {
return "Palindrome";
} else {
return "Not Palindrome";
}
}
function doCheck(num) {
var isPalindrome = isSameOrPalindrome(num);
console.log(isPalindrome);
if(isPalindrome === "Palindrome") {
return 2;
} else {
num++;
isPalindrome = isSameOrPalindrome(num);
if(isPalindrome === "Palindrome") {
return 1;
} else {
return 0
}
}
}
console.log("100",doCheck(100));

Variable only works locally

I wrote some functions involving prime factorization and I noticed that when I identified my test paragraph (for testing the results of functions and such) as document.getElementById("text"), it worked fine. However, when I declared a global variable text as var text = document.getElementById("text"), and then substituted in text for the longer version, it no longer worked. I did, however, notice that it worked when I locally declared text. Why is this and how can I fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/3ehcz214/
And this is my code:
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
}
else if (num === 2) {
return true;
}
else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
}
else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
}
else if (dig === 2) {
return undefined;
}
else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
}
else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
}
else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
}
else if (isPrime(int) === true) {
return false;
}
else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
}
else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
//text.innerHTML = isPrime(6);
<div onclick="listPrimes()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
The text is global, you just need to make sure the whole script file is included in the html. Here's an example of what I mean
Here in code snippets stackoverflow does this for us already.
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
} else if (num === 2) {
return true;
} else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
} else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
} else if (dig === 2) {
return undefined;
} else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
} else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
} else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
} else if (isPrime(int) === true) {
return false;
} else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
} else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
function test() {
console.log("inside test1")
console.log(text);
text.innerHTML = "testtt"
}
function test2() {
console.log("inside test2")
console.log(text);
text.innerHTML = "testtt2"
}
text.innerHTML = isPrime(6);
<div onclick="test()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
<div onclick="test2()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
In the head the script runs/loads first and because you don't have the var's in a function they are never re-used they remain with the original value which is null since the document didn't exist at that time, then when the page loads all it has is access to the functions a call to the global var is null. This is why the code previously only worked when text = document.getElementById('text') was in a function.

Generating a random grid of connected paths

I am trying to generate a random grid of connected paths. The image below shows how far I've managed to get it:
The rules that the grid needs to adhere to are the following:
all the paths must connect to each other in some way but there can be dead ends
there can be no blocks that have no connections (i.e. can't be reached)
the blocks on the edge must have paths that point inward, not outward.
As you can see in my image, my code isn't quite right, but I can't find the error.
Here is a fiddle with the code: jsfiddle.net/thatOneGuy/jz5sfr00/1
But I think my mistake is in this function:
function linkAll() {
for (var x = 0; x < 9; x++) {
for (y = 0; y < 9; y++) {
//link up to each other
var count = 0;
if ((x > 0) && (y > 0)) {
if (hz[x - 1][y].right) {
hz[x][y].left = 1;
} else count++;
if (hz[x][y - 1].bottom) {
hz[x][y].top = 1;
} else count++;
}
if ((x < 9) && (y < 9)) {
if (hz[x + 1][y].left) {
hz[x][y].right = 1;
} else count++;
if (hz[x][y + 1].top) {
hz[x][y].bottom = 1;
} else count++;
}
if (count == 4) {
var newPath = getDirection(getRandomInt(0, 3));
if (newPath == 'top') {
hz[x][y - 1].bottom = 1
hz[x][y].top = 1;
} else if (newPath == 'left') {
hz[x - 1][y].right = 1;
hz[x][y].left = 1;
} else if (newPath == 'bottom') {
hz[x][y + 1].top = 1;
hz[x][y].bottom = 1;
} else if (newPath == 'right') {
hz[x + 1][y].left = 1;
hz[x][y].right = 1;
}
}
} //end for (y)
} //end for (x)
}
UPDATE:
I realised that I confused the x and y values of the array. They should have been swopped.
So I added a linkEdges() function so that the edge blocks all link together:
function linkEdges(){
for(var x = 0; x < 10; x++){
for(var y = 0; y < 10; y++){
if((x==0) && (y > 0) && (y < 9)){
if(hz[0][y-1].right){
//console.log(x + ' ' + y + ' y-1 = 1');
//console.log('Inside (y-1) ');
//console.log(hz[x][y]);
if (hz[0][y].left != null)
{
hz[0][y].left = 1;
}
}
}
if ((y==0) && (x > 0)){
if(hz[x-1][0].bottom){
if(hz[x][0].top != null)
hz[x][0].top = 1;
}
}
if ((y==9) && (x < 9) && (x > 0)){
if(hz[x+1][9].top){
if(hz[x][9].bottom != null)
hz[x][9].bottom = 1;
}
}
if ((x==9) && (y < 9)){
if(hz[9][y+1].left){
if(hz[9][y].right != null)
hz[9][y].right = 1;
}
}
} //end for(y)
}//end for(x)
}
I also updated the linkAll() function:
function linkAll(){
for(var x=0; x < 9; x++){
for(var y=0; y < 9; y++){
//link up to each other
var count = 0;
if((x > 0) && (y > 0)){
if(hz[x-1][y].bottom){
hz[x][y].top = 1;
}
else count++;
if(hz[x][y-1].right){
hz[x][y].left = 1;
}
else count++;
}
if((x < 9) && (y < 9)){
if(hz[x+1][y].top){
hz[x][y].bottom = 1;
}
else count++;
if(hz[x][y+1].left){
hz[x][y].right = 1;
}
else count++;
}
if(count == 4){
//console.log('x: ' + x + ' y: '+y);
var newPath = getDirection(getRandomInt(0, 3));
//console.log(newPath);
if(newPath == 'top'){
hz[x][y-1].right = 1
hz[x][y].left = 1;
}
else if(newPath == 'left'){
hz[x-1][y].bottom = 1;
hz[x][y].top = 1;
}
else if(newPath == 'bottom'){
hz[x][y+1].left = 1;
hz[x][y].right = 1;
}
else if(newPath == 'right'){
hz[x+1][y].top = 1;
hz[x][y].bottom = 1;
}
}
}//end for (y)
}//end for (x)
}
My grid now looks like this:
I just don't know how to connect those last few edges. I think it has something to do with my linkEdges() function.

Stacks with Javascript

I am working with stacks on the infamous 'Braces' problem and I got to a halt. This should be an easy fix but my eyes are not much of a help at the moment.
The first call to the function is working like a charm but the second one is running an extra time and I can't see why.
The first call returns 01110 which is correct but the second returns 011110 which is not...
If you can't read the code here, got to the fiddle
//constructor function for our Stack class
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
}
function push(element) {
this.dataStore[this.top++] = element;
}
function pop() {
return this.dataStore[--this.top];
}
function peek() {
return this.dataStore[this.top - 1];
}
function length() {
return this.top;
}
function clear() {
this.top = 0;
}
function braces(expression) {
for (var i = 0; i < expression.length; i++) {
//if the number of elements in the expression is odd, it is guaranteed not to have a matching expression
//therefore we print 0
if (expression[i].length%2 !== 0) {
console.log(0);
} else {
var s = new Stack();
var startPoint = expression[i].charAt(0);
//if the expression starts with an open brace it means we will not have a matching expression so we print 0
if (startPoint == '(' || startPoint == '{' || startPoint == '[') {
for (var j = 0; j < expression[i].length; j++) {
var char = expression[i].charAt(j);
var h = '';
if (char == '(' || char == '{' || char == '[') {
s.push(char);
} else {
h = s.peek();
if (h == "(" && char == ")") {
s.pop();
} else if (h == "{" && char == "}") {
s.pop();
} else if (h == "[" && char == "]") {
s.pop();
}
}
}
} else {
console.log(0);
}
if (s.length() == 0) {
console.log(1)
} else {
console.log(0);
}
}
}
}
var expr = [ "}()()", "[]({})", "([])", "{()[]}", "([)]" ]; //working
var expr2 = [ "}()(){", "[]({})", "([])", "{()[]}", "([)]" ]; //running an extra time
braces(expr);
Change this:
else {
console.log(0);
continue; //this is new
}
if (s.length() == 0) {
Your function would log both 0 and 1/0 if the startpoint is not { or ( or [ and the length of s was 0
Your stack functions are all outside of the scope of Stack() and therefore the data probably won't be what you expect. You can start fixing this by putting functions inside the Stack() function:
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
this.pop = function () {
// pop
}
this.push = function () {
// code
}
this.peek = function () {
// code
}
}
That way, the methods all have access to the same data.

Categories

Resources