Parameter returns undefined - javascript

I am trying to write a function that identifies if a word is an isogram or not. This is what I have done so far:
function isIsogram(word) {
var result;
var counter = 0;
var dubs = 0;
if (word.length === 0) {
result = false;
} else {
var lower = word.toLowerCase();
var array = Array.from(lower);
for (i = 0; i < array.length; i++) {
counter++;
for (j = i + 1; j < array.length; j++) {
if (array[i] === array[j]) {
dubs++;
}
}
}
if ((counter > 0) && (dubs === 0)) {
result = true;
} else if ((counter > 0) && (dubs > 0)) {
result = false;
}
}
console.log(result);
return result;
}
isIsogram("word");
When I run the above code in my browser's javascript console, it works pretty well. But when I post it onto the environment where I am being tested, it gives an error that "word" (the parameter) is undefined.
I even tried hard coding a parameter by declaring a string value for word outside the function, it still said undefined. What am i not doing right?

Seems to work as far as I can see.
Can you provide information about how you call your function isIsogramm('teststring');?
https://jsfiddle.net/TobiObeck/z15eos81/

Related

Longest substring without repeating characters throwing a run time error?

My code works for many other test cases except for this
It runs a runtime error so I was wondering if someone could help me figure out why. Thanks, here's the code:
if(s.length <= 1){
return s.length
}
let lengths = []
s = s.split('')
function run(index){
if(index === s.length){
lengths.push(s.slice(0,index).length)
return
}
if(s.slice(0,index).indexOf(s[index]) >= 0){
lengths.push(s.slice(0,index).length)
s.splice(0, s.slice(0,index).indexOf(s[index]))
if( s.slice(0,index).indexOf(s[index]) === 0 ){
s.splice(0,1)
}
index = 0
}
run(index+1)
}
run(0)
return Math.max(...lengths)
};
var lengthOfLongestSubstring = function(str) {
if (str.length <=1){
return str.length;
}
var _max = 0;
do {
var obj_ = {};
var substrings = '';
var l = str.length;
//if (_max < l) - even i cannot add if condition here
// it cause time limit problem
for (var i = 0; i < l; i++) {
if (!obj_[str[i]]) {
obj_[str[i]] = 1;
} else {
obj_[str[i]] += 1;
}
if (obj_[str[i]] > 1) {
break;
} else {
substrings += str[i];
}
}
if (_max < substrings.length) {
_max = substrings.length;
}
var str = str.substring(1, str.length);
}
while (str.length > 0);
return _max;
};
This method only gives me output, others solutions gives me time limit exceeds.
LINK to input https://github.com/rinshankolayil/DUMMY_REPO/blob/main/leetcode/test_data.txt
OUTPUT

simple question about error cannot read property in javascript

From this codewars exercise, I've written the following code:
function encrypt(text, n) {
if(n <= 0) {
return text;
}
let en = text.split('');
for(let j = 0; j < n; j++) {
let odd = [];
let even = [];
en.forEach((el,i,arr) => {
if(i % 2 === 0) {
odd.push(el);
} else {
even.push(el);
}
})
en = even.concat(odd);
}
return en.join('');
}
function decrypt(encryptedText, n) {
if(n <= 0) {
return encryptedText;
}
let de = encryptedText.split('')
for(let j = 0; j < n; j++) {
let newArr = [];
de.forEach((el,i,arr) => {
i < Math.floor(arr.length/2) ?
newArr[2*i+1] = el
: newArr[2*(i-Math.floor(arr.length/2))] = el;
})
de = newArr;
}
return de.join('');
}
The challenge is to encrypt strings by taking every 2nd character and rearranging from the front and decrypting.
When I submitted the above code, I got 57 successes and only 1 failure saying >cannot read property split of null
(I do not know what the input was, and the test name is called null test).
What am I doing wrong?
From the instructions:
For both methods:
If the input-string is null or empty return exactly this value!
If n is <= 0 then return the input text.
"exactly this value" is a bit confusing, but what it means is that you need to change the initial test in both functions from
if(n <= 0) {
return text;
}
to
if(n <= 0 || text === null) {
return text;
}
Since you currently aren't checking if the input is null, the error cannot read property split of null will come up if it's null.

How to add a counter to this loop?

I'm a javascript newbie working on a hangman game, I had everything working properly until I realized that my method for comparing my guess to the answer was unable to handle words with multiple letters. I've written a new loop that takes care of this, but that's led to a new problem: I don't know how to work in a counter to keep track of wrong guesses.
This is the loop that I have:
function checkGuess(guess, array) {
for (let i = 0; i < array.length; i++) {
let found = false;
for (let j = 0; j < array.length; j++) {
if (array[i] === guess) {
found = true;
}
}
if (found) {
results += answer[i];
}
}
}
The game will end when the number of wrong guesses reaches a certain count or when results.length = answer.length but I can't figure out how to handle wrong guesses. Any tips would be appreciated.
try this, create a function that return the number of places that the guess exists
function checkGuess(guess, array) {
let found = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] === guess) {
found++;
}
}
return found;
}
then use 2 vars to hold the correct guess and the wrong guess
var correct = 0, wrong = 0
then every time the user is guessing, do the following:
var check = checkGuess(guess, question);
if (check > 0) {
correct += check;
} else {
wrong++;
}
to determine if win or lose
if (wrong >= 3) {
// set it to lose
}
if (correct == question.length) {
// set it to win
}
Is this maybe what you're looking for?
var wrongGuesses = 0;
function checkGuess(guess, array) {
for (let i = 0; i < array.length; i++) {
let found = false;
let go_time = false;
for (let j = 0; j < array.length; j++) {
if (array[i] === guess) {
found = true;
results += answer[i];
}
if(j===(array.length-1)){
go_time = true;
}
}
if (go_time===true&&found!==true) {
wrongGuesses++;
}
}
}

function that checks the number of times a character is used in a string

I'm writing a function that takes a string as an argument, checks it for a given character (say "B" in this case), and then returns an integer that reflects the number of times that character appeared. I'm aware that this can be done using regex and such, but the tutorial I'm using has so far made no mention of regex. Code time:
function countBs(string) {
var i = 0;
var n = 0;
var position = string.charAt(n);
while (i < string.length) {
if (string.charAt(n) == "B")
n += 1;
i++; //This line causes the following else statement to throw a syntax error. But it's the only way I can think of to have the loop continue iteration *while* checking for equivalence to "B"
else
i++;
return n;
}
}
And then check with console.log(countBs("ABBA"));
Your code is quite broken.
function countBs(string) {
var i = 0;
var n = 0;
// var position = string.charAt(n); // REMOVE--NOT NECESSARY
while (i < string.length) {
if (string.charAt(i) == "B") // i, NOT n
n++; // CONSISTENCY IN ADD-ONE SYNTAX
// i++; // INCREMENT ONCE BELOW
//else
i++;
}
return n; // MUST GO OUTSIDE THE LOOP
}
Correct code would therefore be:
function countBs(string) {
var i = 0;
var n = 0;
while (i < string.length) {
if (string.charAt(i) == "B") n++;
i++;
}
return n;
}
There's nothing particularly wrong with using a while loop, but a for would be more natural:
function countBs(str) {
var n = 0;
for (var i = 0; i < str.length; i++) if (str[i]== "B") n++;
return n;
}
Modern JS
For your reference, in modern JS, you could avoid the loops and variables. First, let's write a separate checking function:
function isB(c) { return c === 'B'; }
Then write
function countBs(str) {
return str . split('') . filter(isB) . length;
}
or, using reduce:
function countBs(str) {
return str.split('').reduce(function(cnt, c) {
return cnt + isB(c);
}, 0);
}
or, although you said you didn't want to use regexps:
function countBs(str) {
return (str.match(/B/g) || []) . length;
}
If you are writing in an ES6 environment, then using array comprehensions
function countBs(str) {
return [for (c of str) if (isB(c)) c] . length;
}
Try wrapping it in curly braces:
if (string.charAt(n) == "B")
{ n += 1;
i++;
}
An else requires a previous if, and no other statements in between. i++ was outside the if.
Here's my answer
function countBs(Str)
{
let char = "B" ;
return String(Str).split(char).length - 1;
}
function countChar(Str, char)
{
return String(Str).split(char).length - 1;
}

Test if object with attribute exists in an array using jQuery

Can someone please tell me the best way to check if an object within an array of objects has a type of 11?
Below is what I have but it will alert for every object in the array, can I check the whole array and get it to alert just the once at the end?
I've seen methods like grep but I've been trying and can't get it to work. I'm using jQuery.
var x;
for (x = 0; x < objects.length; x++) {
if (objects[x].type == 11) {
alert("exists");
} else {
alert("doesnt exist");
}
}
Best way is use Array.some:
var exists = objects.some(function(el) { return el.type === 11 });
In the link there is also a shim for the browser that doesn't support it.
Otherwise you can just iterate:
var exists = false;
for (var i = 0, el; !exists && (el = objects[i++]);)
exists = el.type === 11;
Once you have the exists variable set, you can just do:
if (exists) {
// do something
}
Outside the loop, in both cases.
Your code should actually do it. If you're bothered that the loop will continue uselessly, you can abort it by calling break;
if(objects[x].type == 11){
alert("exists");
break;
}
Make it a function:
function hasObjWithType11(arr) {
var x;
for (x = 0; x < arr.length; x++) {
if(arr[x].type == 11){
return true;
}
}
return false;
}
alert(hasObjWithType11([{type:1}, {type:11}]); // alerts true
This will do it
var exists = false;
for (var x = 0; x < objects.length; x++) {
if(objects[x].type == 11){
exists = true;
break;
}
}
if(exists){
alert("exists");
}
You could make the searching code more reusable by wrapping it into a separate function. That way you can externalize the condition for easier reading:
function array_contains(a, fn)
{
for (i = 0, len = a.length; i < len; ++i) {
if (fn(a[i])) {
return true;
}
}
return false;
}
if (array_contains(objects, function(item) { return item.type == 11; })) {
alert('found');
}
You could also use Array.some():
if (objects.some(function(item) {
return item.type == 11;
})) {
alert('exists');
}
For IE < 9, refer to the MDN documentation for a mock version.

Categories