Javascript functions not working in console - javascript

So I have this code:
<script>
function add7(n) {
let x = n + 7;
console.log(x);
}
function lastLetter(theString) {
let x = lastIndexOf(theString);
console.log(x);
})
</script>
<script>
function multiply(a, b) {
let ans = a * b;
console.log(ans);
}
</script>
<script>
function capitalize(word) {
if (word = String) {
toLowerCase(word);
charAt(0).toUpperCase(word);
console.log(word);
} else {
console.log("not a string");
}
}
</script>
I write functionName(chosenVariable) in the console and expected to see a clear answer but add7 and lastLetter just returns ReferenceError (function) not defined. and the other 2 get undefined as an answer. I know that I am blind but am I also a bit stupid? I've looked at the code and tried different changes but cant get it to work.

There were a few errors with your code
Extra ) at the end of the first script block
lastIndexOf is not defined anywhere on your script
word = String will just assign the value of the String class to the word variable (and always return true)
Strings are immutable, so you can't edit an existing string you can however create a new string based on another, so using word.toLowerCase() on it's own won't do anything, you need to reassign the value
add7(2);
lastLetter("123123");
multiply(2, 3);
capitalize("asd");
function add7(n) {
let x = n + 7;
console.log(x);
}
function lastLetter(theString) {
let x = theString[theString.length - 1];
console.log(x);
}
function multiply(a, b) {
let ans = a * b;
console.log(ans);
}
function capitalize(word) {
if (typeof word === "string") {
word = word.toLowerCase();
word = word[0].toUpperCase() + word.substring(1);
console.log(word);
} else {
console.log("not a string");
}
}

Related

Javascript function that checks whether number is palindrome

I read through a few of palindrome questions posted here, but unfortunately couldn't find a way to fix mine. An example of what I'm trying to achieve:
Input: 989
Output: "It's a palindrome"
Input: 23
Output: "Not a palindrome"
Input: 9
Output: "It's a palindome" (any single digit)
My try
function Palindrome(num) {
let numToStringArray = num.toString().split('');
let reversedArray = numToStringArray.reverse();
if (num.toString().length<2) {
return "It's a palindrome"
}
else {
for (let i = 0; i<numToStringArray; i++;) {
if (numToStringArray[i] !== reversedArray[i]) {
return "It's not a palindrome"
}
else {
return "It's a palindrome"
}
}
}
}
When invoked, the function only works for single-digit strings. I tried to fix my for-loop, as I feel that the problem lies in the following line:
if (numToStringArray[i] !== reversedArray[i])
but could not come up with a working solution. Thanks for reading or even helping me out!
I'm spotting several problems...
First, you don't want a ; after your i++ in the loop definition. In jsFiddle at least, that's resulting in a syntax error. Other environments may be more forgiving, but it's worth fixing.
Second, the loop condition is wrong:
i < numToStringArray
should be:
i < numToStringArray.length
Third, the logic of the loop is a bit broken. You're returning "It's a palindrome" immediately if the very first pair match. So by that logic "1231" is a palindrome. Instead, only return within the loop if you find that it's not a palindrome. If the loop completes without returning, then return that it's a palindrome:
for (let i = 0; i < numToStringArray.length; i++) {
if (numToStringArray[i] !== reversedArray[i]) {
return "It's not a palindrome";
}
}
return "It's a palindrome";
Made this quick & working solution:
function checkPalindrome(num) {
var numString = num.toString();
return numString.split("").reverse().join("") == numString;
}
Provide an integer parameter inside the checkPalindrome() function, and it will return either true or false.
For example:
if (checkPalindrome(123321)) {
console.log("Is a palindrome");
} else {
console.log("Not a palindrome");
}
How about this
str === str.split('').reverse().join("")
like so
const palindrome = num => {
const str = num.toString();
return `It's ${str.length<2 || str === str.split('').reverse().join("") ? "" : "not "}a palindrome`
};
console.log(
[989, 23, 9].map(num => `${num}: ${palindrome(num)}`)
)
actually your numToStringArray is not reversing. Try this:
function Palindrome(num) {
let numToStringArray = num.toString().split('');
let reversedArray = num.toString().split('').reverse();
console.log("here", numToStringArray, reversedArray)
if (num.toString().length<2) {
return "It's a palindrome"
}
else {
for (let i = 0; i<numToStringArray.length; i++) {
if (numToStringArray[i] !== reversedArray[i]) {
return "It's not a palindrome"
}
else {
return "It's a palindrome"
}
}
}
}
console.log(Palindrome(686))
The reason your logic doesn't is mainly due to the fact that you use i < numToStringArray instead of i < numToStringArray.length as mentioned in the comments.
The simplest way to achieve what you want though, would simply be-
function isPalindrome(num) {
return num === Number(num.toString().split('').reverse().join(''));
}
This should work.
const pal = num => {
let reversedNum = parseFloat(num.toString().split('').reverse().join(''));
if (reversedNum === num) {
console.log("palindrome")
} else {
console.log("no palindrome")
}
}
pal(12121);
Without using split, reverse and join, it can be checked through a single array.
function Palindrome(num) {
let numToStringArray = num.toString();
var len = numToStringArray.length;
if (len < 2) {
return "It's a palindrome"
}
else {
for (var i = 0; i < len / 2; i++) {
if (numToStringArray[i] !== numToStringArray[len - 1 - i]) {
return "It's not a palindrome";
}
return "It's a palindrome"
}
}
}
console.log(Palindrome(989));
console.log(Palindrome(23));
console.log(Palindrome(9));
A short function to test if the number is a Palindrome and returns a "true" or "false" is as follows:
You can then call it and output your text result "It's a palindrome" in case it returns true or "Not a palindrome" if returns false.
Test examples provided below.
const IsPalindrome = e => (e+="").split("").reverse().join("") == e;
// ======== test =============
console.log(IsPalindrome(23)); // false
console.log(IsPalindrome(121)); // true
console.log(IsPalindrome(9889)); // true
console.log(IsPalindrome(989)); // true
console.log(IsPalindrome(1)); // true
To meet your specific requirements for the output text. Here is a one-liner function based on the function below:
function IsPalindrome(n) {
return n + (((n+="").split("").reverse().join("") == n) ? " is a palindrome" : " is not a palindrome");
}
// ======== test =============
console.log(IsPalindrome(23)); // 23 is not a palindrome
console.log(IsPalindrome(121)); // 121 is a palindrome
console.log(IsPalindrome(9889)); // 9889 is a palindrome
console.log(IsPalindrome(989)); // 989 is a palindrome
console.log(IsPalindrome(1)); // 1 is a palindrome
Taking advantage of its function, something you could do after using the split method and the reverse method to read the number from right to left, is to use the join to transform it into a string again and then compare them, like this:
function Palindrome(num) {
let numToStringArray = num.toString().split('');
let reversedArray = numToStringArray.reverse().join('');
if (num.toString() == reversedArray)
console.log('It\'s a palindrome');
else
console.log('It\'s not a palindrome');
}
Palindrome(9);
Palindrome(232);
Palindrome(152);
let a, b = 121;
a = b;
console.log(String(b).split("").reverse().join() === String(a).split("").join());

Javascript ING BANK 3 questions test interview

I had a test interview and for 3 questions I didn't know the answer:
Write a function that will insert underscore between characters: this will become t_h_i_s.
Write a function that will output this:
l('t') === 'lt'
l()('t') === 'l3t'
l()()('t') === 'l33t'
l()()('g') === 'l33g'
l()()()()()()()()()()()('t') === 'l33333333333t'
Why the output is true?
var bar = true;
function foo() {
bar = false;
return 5;
function bar() {}
}
foo();
console.log(bar);
Can someone help please with the answers?
Write a function that will insert underscore between characters: this will become t_h_i_s.
You want to write a function that iterates over all characters in a string, and appends an underscore between all characters.
For example:
function underscoreString(str) {
var result = str.charAt(0);
for (var i=1; i<str.length; i++) {
result += '_' + str.charAt(i);
}
return result;
}
console.log( underscoreString('this') );
Write a function that will output this:
You will need to write a function that returns another function, so you can chain the functions. Since Javascript allows you to store functions as variables, you can make use of this by re-calling the same function continuously until a proper argument is returned.
The following function is an example. It works as intended but is not the most beautiful.
function l(ch) {
var str = 'l';
if (ch) return str + ch;
else str += '3';
var newFunc = function (ch) {
if (ch) return str + ch;
str += '3';
return newFunc;
}
return newFunc
}
console.log( l('t') === 'lt' );
console.log( l()('t') === 'l3t' );
console.log( l()()('t') === 'l33t' );
console.log( l()()('g') === 'l33g' );
console.log( l()()()()()()()()()()()('t') === 'l33333333333t' );
Why the output is true?
var bar = true;
function foo() {
bar = false;
return 5;
function bar() {}
}
foo();
console.log(bar);
The bar that is within the function foo() is not referencing the global variable bar. Instead, it is referencing the function function bar() {}. This is because of hoisting, as mentioned in the comments.
Thus, the global bar variable is not touched at all by the function, and stays true at all times.
It really depends on the expected level of code. If you need to demonstrate understanding of algorithms or knowledge of how to use javascript constructs.
For example, the first one could be as simple as:
function insertUnderscore(x){
return x.split('').join('_');
}
2nd question a recursive method:
function l( end ){
var acc = '';
function iter( eChar ){
if( typeof eChar === "undefined"){
acc=acc+'3';
return iter;
}
return 'l'+acc+eChar;
}
if(typeof end === "undefined"){
acc = acc + '3';
return iter;
}
return iter(end);
}
Third question:
function bar(){} actually declares 'bar' within the local scope, so your assignment bar = false acts on local 'bar'.
This one simply returns the iterator function if the letter is undefined, When the letter is defined it repeats the character '3' n times.
The other two should be pretty easy to figure out
function l(letter) {
let count = 0
function iter(letter) {
if (typeof letter === 'undefined') {
count++
return iter
} else {
return 'l' + ('3'.repeat(count)) + letter
}
}
return iter(letter)
}
console.log(l('t') === 'lt')
console.log(l()('t') === 'l3t')
console.log(l()()('t') === 'l33t')
console.log(l()()('g') === 'l33g')
console.log(l()()()()()()()()()()()('t') === 'l33333333333t')
Question 1
Use a negative lookahead for the beginning of the string and a positive lookahead for a character. Replace the given empty string with an underscore.
function spacer(s) {
return s.replace(/(?!^.)(?=.)/g, '_');
}
console.log(spacer('this'));
Question 2
Use a closure and return for a non given paramter the function otherwise the extended value.
function l(v) {
var s = 'l';
fn = function (v) {
s += 3;
return v === undefined ? fn : s + v;
};
return v === undefined ? fn : s + v;
}
console.log(l('t') === 'lt');
console.log(l()('t') === 'l3t');
console.log(l()()('t') === 'l33t');
console.log(l()()('g') === 'l33g');
console.log(l()()()()()()()()()()()('t') === 'l33333333333t');
Question 3
Because function bar() {} is hoisted to the begin of the function and then overwritten with false. The outer bar variable has never changed it's content.
var bar = true;
function foo() {
bar = false;
console.log('foo\'s bar:', bar);
return 5;
function bar() {}
}
foo();
console.log(bar);

Javascript difference between two words

How do you detect the difference between two similar words?
For example:
word compared to word, gives , as a variable
this compared to .this gives . as a variable
info compared to :info, gives : and , as a variable
In this case we always know which word is the longer one. And the actual word is always the same for the comparison. It's just that the longer one maybe has some extra characters.
I need to do this using javascript only.
You could try checking for difference between the array of characters.
var shortStr = 'info';
var longStr = ':info,';
console.log(Array.from(longStr).filter(function(c) {
return Array.from(shortStr).indexOf(c) === -1;
}));
Also, there's a better way, check if the string is a sub-string, and then remove the sub-string from the main string:
function checkDiff(a, b) {
var big = '', small = '';
if (a.length > b.length) {
big = a;
small = b;
} else {
small = a;
big = b;
}
if (big.indexOf(small) != -1) {
return big.replace(small, "");
} else {
return false;
}
}
alert(checkDiff("word", "word,"));
alert(checkDiff("this", ".this"));
alert(checkDiff("info", ":info,"));
I have added demo for all your cases. It returns the values as a single string, based on the place it has occurred. You can send the output as an array as well, using the .split() method.
function checkDiff(a, b) {
var big = '', small = '';
if (a.length > b.length) {
big = a;
small = b;
} else {
small = a;
big = b;
}
if (big.indexOf(small) != -1) {
console.log(big.replace(small, "").split(""));
return big.replace(small, "").split("");
} else {
return false;
}
}
alert(checkDiff("word", "word,"));
alert(checkDiff("this", ".this"));
alert(checkDiff("info", ":info,"));

Replace string in JS array without using native replace() method

I am stuck a bit with replacing string in js array. I am trying to log the arguments to see what is going on but am missing a piece of the puzzle.
fiddle
// - trying to look for substring in array
// - if match is found
// - replace substring without using the native method replace();
var div = $('.insert');
data = ["erf,", "erfeer,rf", "erfer"];
data = data.map(function (x) {
return /""/g.test(x) ? x.replace(/""/g, "") : x
});
function fakeReplace(data, substr, newstr) {
//should show ["erf,", "erfeer,rf", "erfer"];
div.append("data before match replace = " + data);
div.append("\<br>");
div.append("substr = " + substr);
div.append("\<br>");
div.append("newstr = " + newstr);
div.append("\<br>");
return data.split(substr).join(newstr);
}
fakeReplace(data, "erf", "blue");
//should show ["blue,", "blueeer,rf", "blueer"];
div.append("data after fakeReplace is executed = " + data);
You are treating data like a string in your function. You can use map() to return a new array with each element replaced.
function fakeReplace(data, substr, newstr) {
return data.map(function(s) {
return s.split(substr).join(newstr);
})
}
let myString = "Victor";
let splitted = myString.split('');
function replaceManual(a,b){
for(let i = 0; i<= splitted.length-1; i++)
{
for(let j=i; j <=i;j++)
{
if(splitted[j]===a)
{
splitted[j]=b;
return splitted;
}
else
{
break;
}
}
}
}
replaceManual('V','T');
console.log(splitted.toString().replace(/[^\w\s]/gi, ''));

Adding a hundredths place to a number that can be either comma or period delimited

I am wondering if this code can be modified so that it will render "4,5" and "4.5" (or any number that only has a tenths place) as 4.50 (or 4,50) respectively...rather than as 45.
I think I need to test "source" first to see if it's got the format "x[.,]x" (digit, comma or period, digit) but haven't been able to do that successfully. I've tried using "toFixed" but that messes things up if it's 4.500 or something (which needs to render as 4500, not 4.50!)
Any help would be hugely appreciated. Thank you!
function parse(source) {
var sep = source.charAt(source.length - 3);
switch (sep) {
case '.':
case ',':
var parts = source.split(sep);
var norm = parts[0].replace(/(\.|,|\s)/g, '') + '.' + parts[1];
break;
default:
var norm = source.replace(/(\.|,|\s)/g, '');
}
return Math.round(Number(norm));
}
So I have figured out a regex that identifies the right pattern: /^\d{1}[.,]\d{1}$/ (note there's a slash not showing up right before the period inside the brackets!!)
I have added it into the following little function, which I want to just tack on a zero or leave the variable as is. But for some reason it's now crashing at the part where I'm adding the zero...
function addZeros(number) {
var s = number;
if (s.match(/^\d{1}[\.,]\d{1}$/)) { //should only get here on "X,X" or "X.X" cases
alert(s); //makes it to here, displays only this alert
s = s.toFixed(2); //wtf is wrong with this?!!
alert(s); //does NOT make it to here.
return s;
}
else {
alert('All good in the hood.');
return s;
}
}
If I understand you correctly this should do it
function parse(s) {
var found = false;
['.', ','].forEach(function (el) {
var i = s.indexOf(el);
if (s[i] === s[s.length - 2]) {
s = s + '0';
found = true;
return false;
}
});
if (!found) {
return s.replace(/(\.|,|\s)/g, '');
} else {
return s;
}
}
Run a forEach on each delimiter and figure out how you want it to be formatted.
http://jsfiddle.net/Ek6cJ/
Does this do what you want?
function parse(source) {
var dotIndex = source.lastIndexOf('.');
var commaIndex = source.lastIndexOf(',');
var numDots = source.match(/\./g).length;
if (dotIndex > commaIndex && numDots == 1) {
// Dot-delimited decimal
return Number(source.replace(/,/g, '')).toFixed(2);
} else {
return Number(source.replace(/\./g, '').replace(/,/g, '.')).toFixed(2);
}
}
> parse("1,200,300.20")
"1200300.20"
> parse("1.200.300,20")
"1200300.20"
> parse("1.200.300")
"1200300.00"

Categories

Resources