How can I make this to remember the last modification statement - javascript

How can I make this to remember the last modification statement.
Bacause this code is Always reinitialize the str variable.
But I have to make a loop what is add plus one "*" to my str. This is the reason why I want to "save" the previous statement.
Above I posted the test results.
function padIt(str, n) {
do {
if (n % 2 === 0) {
str + "*";
}
else {
str = "*" + str;
}
} while (n > 5)
return str;
}
I get this:
Test Passed: Value == '\'*a\''
Expected: '\'*a*\'', instead got: '\'a\''
Expected: '\'**a*\'', instead got: '\'*a\''
Expected: '\'**a**\'', instead got: '\'a\''

You are missing += in your if block. It should be str += "*";
function padIt(str, n) {
do {
if (n % 2 === 0) {
str += "*";
} else {
str = "*" + str;
}
} while (n > 5)
return str;
}

I think you really intended the padIt function to be recursive. If so, we can attempt such a solution by adding some padding on each side, in each recursive call. The base case occurs when the n counter reaches one, in which case we just return the cumulatively built padded string.
padIt = function(str, n) {
if (n === 1) return str;
if (n%2 === 0) {
return padIt(str + "*", n-1);
}
else {
return padIt("*" + str, n-1);
}
}
console.log(padIt("a", 5));

Related

How to print a value of parameter inside of function in javascript?

I am trying to create a function pluralizeParam(n, word, pluralWord) with these requirements:
If n is 1, return the non-plural word (parameter word);otherwise, add an “s” to the plural word;
If the pluralWord parameter is provided, instead of adding an “s,” return the pluralWord.
What I have done so far is following:
function returnPluralWord(n, word, pluralWord) {
if (n === 1) {
return word;
} else if (n === 1 && (word.lastIndexOf("s")) || (word.lastIndexOf("ess"))) {
return word + "s";
} else if (n !== 1 && word.length - 2 === "es") {
return word + "s";
} else if (pluralWord !== 'undefined') {
return pluralWord;
}
}
var result = returnPluralWord(2, "lioness", "lionesses");
console.log(result);
My problem is: it is not printing pluralWord. How do I do that?
Thanks
word.length - 2 can't never be equal to "es". You need also to rearrange your statements, the 2nd is already catched by 1.
When you use the word.lastIndexOf('s') ( which is wrong logic I think ), it returns the last index of the s character, not if it ends on s.
You can check String#endsWith and String#startsWith methods, these ones check if the string starts or ends with the given part
const str = 'less';
console.log(str.endsWith('s'))

Javascript palindrome check word to see if it's a palindrome

I'm trying to determine if a word is a palindrome. A palindrome is a word that is spelled the same way forwards and backwards. I want my code to console.log what I've written but I'm getting an error: unreachable code after return statement.
The line where error starts is: isWordAPalindrome('word');?
isWordAPalindrome('word');
function isWordAPalindrome(word) {
var word = "sherpa,stewie,anna,lil squiggle, racecar, tacocat"
str[0];
str.length
console.log(); {
if (str.length = 0) {
return true;
}
if (str[0] != str[str.length - 1]) {
return false;
}
return isWordAPalindrome(str.slice(1, str.length - 1));
isWordAPalindrome('word');
console.log('sherpa');
console.log('stewie');
console.log('anna');
console.log('lil squiggle');
console.log('racecar');
console.log('tacocat');
}
console.log(''); //simply making a newline for easier console reading
console.log('The word provided is: ', word);
isWordAPalindrome('sherpa');
console.log('sherpa is not a palindrome');
isWordAPalindrome('stewie');
console.log('stewie is not a palindrome');
isWordAPalindrome('anna');
console.log('anna is a palindrome');
isWordAPalindrome('lil squiggle');
console.log('lil squiggle is not a palindrome');
isWordAPalindrome('racecar');
console.log('racecar is a palindrome');
isWordAPalindrome('tacocat');
console.log('tacocat is a palindrome');
}
Different approach:
const word = "sherpa,stewie,anna,lil squiggle, A butt tuba, racecar, tacocat";
const a = word.split(',').map(s => s.toLowerCase().replace(/\s+/g, ""));
const isP = s => s === s.split('').reverse().join('');
for (let w of a) {
console.log(`${w}: ${isP(w)}`)
}
You have a return statement which stops the code execution and returns from the function.
Here what you want to achieve
function checkPalindrome(word) {
for (var i = 0, j = word.length -1; i++, j--; i < word.length, j >= 0, i < j) {
if (word.charAt(i) !== word.charAt(j)) {
return false;
}
}
return true;
}
console.log(checkPalindrome('sherpa'));
console.log(checkPalindrome('anna'));
You have code inside the isWordAPalindrom method that is after the return:
return isWordAPalindrome(str.slice(1,str.length-1));
//unreachable
isWordAPalindrome('word');
console.log('sherpa');
console.log('stewie');
...
that code is unreachable
Your recursive routine is fine. You just need to know where to start and end your tabs and braces.
Also, you were assigning the value 0 to your str.length instead of evaluating if it was equal (=== or at the very least ==).
Also, you can evaluate if the word is a palindrome before your print out the log message.
var words = "sherpa, stewie, anna, lil squiggle, racecar, tacocat".split(/,\s*/);
words.forEach(word => {
var isPalindrome = isWordAPalindrome(word);
console.log(`${word} is ${!isPalindrome ? 'not ' : ''}a palindrome`);
});
function isWordAPalindrome(str) {
if (str.length === 0) {
return true;
}
if (str[0] != str[str.length - 1]) {
return false;
}
return isWordAPalindrome(str.slice(1, str.length - 1));
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Output
sherpa is not a palindrome
stewie is not a palindrome
anna is a palindrome
lil squiggle is not a palindrome
racecar is a palindrome
tacocat is a palindrome
When you do return you are doing your thread "go out" of the function.
Code after return can't be ever executed, it is what the error is saying to you.
If you are trying to do something before the return statement, just put it before.
isWordAPalindrome('word');
console.log('sherpa');
console.log('stewie');
console.log('anna');
console.log('lil squiggle');
console.log('racecar');
console.log('tacocat');
return isWordAPalindrome(str.slice(1, str.length - 1));

Truncate a String in Javascript

I'm trying to accomplish the following :
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.
Note that inserting the three dots to the end will add to the string length.
However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.
The code I have will only pass test if my num >2, otherwise it fails.
function truncateString(str, num) {
// Clear out that junk in your trunk
var trunString = "";
if (str.length > num) {
trunString = str.slice(0, (num -3)) + "...";
return trunString;
}
return str;
}
truncateString("A-", 1);
Found a solution for this:
var trunString = "";
if (str.length > num && num >= 4 ) {
trunString = str.slice(0, (num - 3)) + "...";
return trunString;
}
else if (str.length > num && num <= 3) {
trunString = str.slice(0, (num)) + "...";
return trunString;
}
You could use a conditional (ternary) operator ?:
function truncateString(str, num) {
return str.length > num ?
str.slice(0, num > 3 ? num - 3 : num) + "..." :
str;
}
console.log(truncateString("Abcdefghijk", 5));
console.log(truncateString("A-", 1));
console.log(truncateString("Alpha", 5));
console.log(truncateString("Beta", 5));
console.log(truncateString("Epsilon", 3));
function truncateString(str, num) {
// clear out that junk in your trunk
var trunString = '';
if (str.length && str.length > num) {
trunString = str.slice(0, num - 1) + '…';
return trunString;
}
return str;
}
truncateString("A-", 1);
P.S.: read also #techfoobar comment, using &hellip HTML entity will help...
This is my solution, hoping to help you
function truncate(str, num) {
// Clear out that junk in your trunk
var newStr;
if(num>3&&num<str.length){
newStr=str.slice(0,num-3)+"...";
}else if(num>=str.length){
newStr=str;
}else{
newStr=str.slice(0,num)+"...";
}
return newStr;
}
truncate("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length);

Convert from Dec to Binary in JS

i am trying to convert a decimal number into a binary number and i wrote a function in c++ that do this work and it worked fine , but when i wrote the same function in Javascript it didn't work out and printed a false value like "11101111111111" something like that.
can anyone tell me what's wrong with this function ?
var decToBinary=function() {
var n=16,s="";
while(n) {
if(n % 2 == 0)
s += "0";
else
s += "1";
n /= 2;
}
s.reverse();
return s;
}
The problem stems from the fact that you only terminate when n === 0 but in many cases you'll get n === 1 which will cause it to incrementally divide n by 2 until the limits of floating point math cause it to be zero. Instead, terminate if n is not greater than or equal to 1.
function log(msg) {
document.querySelector('pre').innerHTML += msg + '\n';
}
function decToBinary(n) {
var str = '';
while(n >= 1) {
if (n % 2 === 0) {
str += '0';
} else {
str += '1';
}
n /= 2;
}
str = str.split('').reverse().join('');
return str;
}
log('1: ' + decToBinary(1));
log('2: ' + decToBinary(2));
log('15: ' + decToBinary(15));
log('16: ' + decToBinary(16));
<pre></pre>
how do I convert an integer to binary in javascript?
I think this would be the link you'd want to check out.
function dec2bin(dec){
return (dec >>> 0).toString(2);
}

Failed test for JavaScript palindrome

I noticed when I literally type the word test or dabd, it fails by saying "test is a palindrome"; obviously these should fail. I test other words like racecar, madam, cat, they all pass. I check from the left most character and right most character and go down until we reach the middle. What could be the issue?
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome(str);
}
function palindrome(str) {
var j = str.length;
if (/\s/.test(str)) {
alert("No spaces allowed.")
return false;
}
for (i = 0; i < j / 2; i++) {
if (str[i] == str[j - 1 - i]) {
isPalindrome('', str);
return true;
} else {
notPalindrome(str);
return false;
}
}
}
function isPalindrome(e, str) {
alert(str + " is a Palindrome.");
}
function notPalindrome(str) {
alert(str + " isn't a Palindrome");
}
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", lengthChecker);
});
In palindrome() you always only check the first character and immediately return. Fix the loop like this:
for (var i = 0; i < j / 2; i++) {
if (str[i] != str[j - 1 - i]) {
notPalindrome(str);
return false;
}
}
isPalindrome('', str);
return true;
For reference, you don't need to loop. You can simplify the palindrome test to just this:
str === str.split('').reverse().join('')
This splits the string into an array, which can then be reversed. It then joins it back into a string so you can compare it.
I'd then put this in a ternary statement for modifying the message:
var notp = (str === '' || str !== str.split('').reverse().join('').replace(" ", "")) ? 'is NOT':'IS';
I added "str === ''" to test for non-entries, and I added a remove spaces test as well. Now you've got a variable that you can push into a generic alert or whatever. You can change that to read "true:false;" instead is you want to control more than just the text of the message.
The following gets rid of the leading and trailing spaces:
str = str.trim();
There are more edits you can make, but this should help you along. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/fudLdx0r/

Categories