can anyone figure out the bug in my code? - javascript

The function is supposed to solve the following problem, but there is something wrong in it.
The problem:
Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number.
function repeatStringNumTimes(str, num) {
var result = '';
for(let i = 0; i < num; i++){
result += 'str';
}
return result;
}
repeatStringNumTimes("abc", 3);

two problems. first 'str' will give you a literal. you want the variable str. second, once you have the result you need to display it.
function repeatStringNumTimes(str, num) {
var result = '';
for(let i = 0; i < num; i++){
result += str;
}
return result;
}
var result = repeatStringNumTimes("abc", 3);
console.log(result);

you will have to add the old string to the new one and don't forget the space between them
function repeatStringNumTimes(str, num) {
var result = '';
for(let i = 0; i < num; i++){
result = result + str + ' ';
}
return result;
}
repeatStringNumTimes("abc", 3);

First you're not returning if the num is not positive. Second, it should be str and not 'str' if you want to repeat the variable.
function repeatStringNumTimes(str, num) {
var result = '';
if (num < 1) return; //return if num is not postive
for(let i = 0; i < num; i++){
result += str;
}
return result;
}
var res = repeatStringNumTimes("abc", 3);
console.log(res)

Related

How do I print the return value of a function?

I'm trying to print the return value of a function but I just can't seem to do it. I keep getting undefined for the last line.
let count = 0;
function product(num){
let result = 1;
strNum = num.toString()
strNumArr = strNum.split("")
if(strNum.length === 1){
return count;
}
for(let i = 0; i< strNum.length; i++){
result *= parseInt(strNumArr[i])
}
count++;
//console.log(count)
product(result)
}
let bool = product(39);
console.log(product(39));
I know I'm missing something basic, but I don't know what it is.
If I understand what you are trying to achieve correctly, here is a working version of your code.
function product(num){
let result = 1;
strNum = num.toString()
strNumArr = strNum.split("")
if(strNum.length === 1){
return num;
}
for(let i = 0; i< strNum.length; i++){
result *= parseInt(strNumArr[i])
}
return result;
}
console.log(product(39)); // should return 27
console.log(product(5)); // should return 5
console.log(product(234)); // should return 24
You should return the result after you are done with the loop.
By the way the same can be achieved with a one liner. For example
function product(num) {
return Array.from(String(num).split('')).reduce((c,p) => p * c, 1)
}
Replace product(result) to return product(result). This way if the function calls itself it returns the value generated in the nested function call.
let count = 0;
function product(num){
let result = 1;
strNum = num.toString()
strNumArr = strNum.split("")
if(strNum.length === 1){
return count;
}
for(let i = 0; i< strNum.length; i++){
result *= parseInt(strNumArr[i])
}
count++;
//console.log(count)
return product(result)
}
let bool = product(39);
console.log(product(39));

Why Javascript console.log result is NaN when I tried Repeat a string a specified times

function repeatS(srr, num) {
if (num <= 0) {
return "";
}
var result = "";
for (var i = 0; i < num; i++) {
result = +srr;
}
return result;
}
console.log(repeatS("ahfidhfd", 3));
strong text
Here is my question, the result is Nan, anyone knows what might be the problem here...
result = +srr;
should be
result += srr;
You use an unary plus + for converting a string to a number, but you need to assign the value to the left hand variable.
function repeatS(srr, num) {
if (num <= 0) {
return "";
}
var result = "";
for (var i = 0; i < num; i++) {
result += srr;
}
return result;
}
console.log(repeatS("ahfidhfd", 3));

Sum of Digits using tostring and number methods javascript

Can someone explain what I am doing wrong in this problem? I want to add the sum of the num variable using toString and Number methods. I first turn num into the string num = '12345'. Then I loop through string, turn it into a number and add it to the sum.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = 0;
num.toString();
for(var i = 0; i < num.length; i++){
sumOfDigits += Number(num[i]);
}
return sumOfDigits;
}
You're not assigning the result of num.toString() to anything.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = 0;
num = num.toString();
for (var i = 0; i < num.length; i++) {
sumOfDigits += Number(num[i]);
}
return sumOfDigits;
}
console.log(sumDigits(num));
I believe you can use this one :
var num = 12345;
function sumDigits(num) {
//empty variable
var str;
//check type of the incoming value
(typeof num == "string") ? str = num : str = num.toString();
//this is the same with above if you don't know how to use short handed if else
/*
if(typeof num == "string"){
str = num;
} else {
str = num.toString();
}
*/
//Array's split Method and a variable which u have create already
var arr = str.split(''), sumOfDigits = 0;
for(var i in arr){
//You should use parseInt() method.
sumOfDigits += parseInt(arr[i]);
}
//return the sum of the digits
return sumOfDigits;
};
console.log(sumDigits(num));
If you have future problems please first search a bit then write here :)
Updated:
You can use split, map and reduce to split the array, map it to integers, then use a reduce function to sum the integers.
You could eliminate the map if you want to move parse into the reduce, but I like to keep the steps separate.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = num
.toString()
.split('')
.map(function(n) { return parseInt(n);})
.reduce(function(acc, val) {
return acc + val;
},
0
);
return sumOfDigits;
}
var sum = sumDigits(num);
console.log(sum)

How to make characters in a string repeat using Javascript?

How can I make individual characters within a string repeat a given amount of times?
That is, how do I turn "XyZ" into "XXXyyyZZZ"?
Try this:
var foo = 'bar';
function makeString(str, repeat) {
var str = Array.prototype.map.call(str, function(character) {
var nascentStr = '';
while (nascentStr.length < repeat) {
nascentStr += character;
}
return nascentStr;
}).join('');
return str;
}
alert(makeString(foo, 3));
You'll need to use a combination of a few functions. First you'll need to split the string into individual characters:
var charArray = "XyZ".split('');
Once you have it split up, you can use a combination of the .map function and a nifty little trick of javascript Array.
var someMultiplier = 5;
var duplicatedArray = charArray.map(function(char) {
return Array(someMultiplier).join(char);
});
At that point, you have an array of strings that have the duplicate letters, and you can combine them back with .join
var dupString = duplicatedArray.join('');
dupString === "XXXXXyyyyyZZZZZ
Sounds straight forward. You can run this in your browser's console:
var my = 'XyZ';
function repeat(str, times) {
var res = '';
for (var i in str) {
var char = str[i];
for (var j=0; j < times; j++) {
res += char;
}
}
return res;
}
var his = repeat(my, 3);
console.log(his);
you have not mentioned what will happen if input will be like xyxzy. Assuming it will be xxxyyxxxzzzyyy
// function takes input string & num of repitation
function buildString(input, num) {
var _currentChar = ""; // Final output string
for (var m = 0; m < input.length; m++) {
//call another function which will return XXX or yyy or zzz & then finally concat it
_currentChar += _repeatString((input.charAt(m)), num);
}
}
// It will return XXX or yyy or ZZZ
// takes individual char as input and num of times to repeat
function _repeatString(char, num) {
var _r = "";
for (var o = 0; o < num; o++) {
_r += char;
}
return _r
}
buildString('XyZ', 3)
jsfiddle for Example
function repeatStringNumTimes(str, num) {
let valueCopy = str
if (num > 0) {
for (var i = 0; i < num - 1; i++) {
valueCopy = valueCopy.concat(str)
}
} else {
valueCopy = ""
}
return valueCopy;
}
repeatStringNumTimes("abc", 3);
These days can be done a lot easier:
const repeater = (str, n) => [...str].map(c => c.repeat(n)).join('');
alert(repeater('XyZ', 3));

Getting a nth element from a string

How can I get a certain nth element from a string. Like if I want to get every 3rd element from the word GOOGLE how can i do that. SO far i've done this but i dont know what to type after the If
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=0; i<string_length; i++) {
if(string[i]%3==0) {
}
new_string.push(string[i]);
}
return new_string;
}
Use the charAt() function of String which returns the char at a specific index passed to the function. Using charAt, I have created a script that will return every third character.
var result = "";
for(var i = 2; i < test.length; i+=3){
result += test.charAt(i);
}
If you would like to turn this script into a more reusable function:
var test = "GOOGLE";
function getEveryNthChar(n, str){
var result = "";
for(var i = (n-1); i < test.length; i+=n){
result += str.charAt(i);
}
return result;
}
alert(getEveryNthChar(1,test));
alert(getEveryNthChar(2,test));
alert(getEveryNthChar(3,test));
alert(getEveryNthChar(4,test));
Working Demo: http://jsfiddle.net/Q7Lx2/
Documentation
How about this?
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=2; i<string_length; i+=3) { // instead of an if, use +=3
new_string.push(string.charAt(i));
}
return new_string.join(""); // turn your array back into a string
}
Note that if you start making this compact, you'll end up with the same answer as Kevin's ;-)
function create_string( s ) {
var new_string = '';
for( var i=2; i<s.length; i+=3) { // instead of an if, use +=3
new_string += s.charAt(i);
}
return new_string;
}
Here's a function that will work for any number, not just 3:
function stringHop(s, n) {
var result = "";
for (var i = 0; i < s.length; i+= n) {
result += s.charAt(i);
}
return result;
}
var foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var bar = stringHop(foo, 2); // returns "ACEGIKMOQSUWY"
var baz = stringHop(foo, 3); // returns "ADGJMPSVY"
String.charAt(index) will return the character at the specified index, from 0 to String.length - 1. So:
String.prototype.every = function(n) {
var out = '';
for (var i = 0; i < this.length; i += n) {
out += this.charAt(i);
}
return out;
}
var str = "GOOGLE";
console.log(str.every(3)) // Outputs: GG
If you don't want to include the first character, then change the for loop to:
for (var i = n - 1; i < this.length; i += n) {

Categories