I am a total newbie and currently learning Javacript.
I encountered this problem on JSChallenger and have been struggling with it.
Here's my code:
// Write a function that takes a string (a) and a number (n) as argument
// Return the nth character of 'a'
function myFunction(a, n)
{let string = a;
let index = n;
return string.charAt(index);
}
Can anyone point out my errors?
Thanks so much!
Here's a very short solution
function find( a, b){
return a[b]
}
console.log(find('how',1));
although you need to do some tests in the function to check if the input for b is greater than the length of a else it would fail.
You can do that like this
function find( a, b){
if(a.length<b-1){
return 'error';
}
return a[b]
}
console.log(find('how',5));
that way your code would be free from error
Try this one
function myFunction(a, n){
return a[n - 1];}
// there is a shorter way to do this since you want to find what's missing here is what's missing.
function myFunction(a, n){
let string = a;
let index = n-1;
return string.charAt(index);
}
JS string's index starts enumerating from 0 so the n should be decremented by 1
// Write a function that takes a string (a) and a number (n) as argument
// Return the nth character of 'a'
function myFunction(a, n)
{
let string = a;
let index = n;
return string.charAt(index-1);
}
the easiest way to write it would be:
// Write a function that takes a string (a) and a number (n) as argument
// Return the nth character of 'a'
function myFunction(a,n) {
return a[n - 1];
}
Meaning return from string "a" of myFunction the index "[n-1]" , "n-1" it's a needed operation to get the right index because string index start enumerating from 0.
It is very easy you can just return the a[n]
but it is not the right answer because as you know the strings in JavaScript are zero-indexed so the right answer is
function myFunction(a, n) {
return a[n - 1]
}
Happy Coding & keep Learning
also this solution works too, with empty space at first of string we can remove that counting from zero :
function myFunction(a, n) {
return ` ${a}}`[n]
}
but this is just another solution. not tested. and you can check this repo for other JSchallenger solutinos: JSchallenger solutions
in javascript, you can write this simple code to solve your problem
ex:
let string = "Hello";
let n = 2;
return string[n];
function myFunction(a, n) {
return a.charAt(n - 1);
}
console.log(myFunction("hello", 2));
I think so this is best way
that is a tricky question if you look to the test cases you will notice that it ignore counting from zero
function myFunction(a, n) {
return a.charAt(n-1);
}
Related
I am trying to make the code below repeat string s n number of times, however, it will always repeat n - 1 times, because I need to pass a decrement to exit the recursion or I will exceed the max call stack.
function repeatStr (n, s) {
while(n > 1) {
result = repeatStr(-n, s)
return s = s.concat(s)
}
}
repeatStr(3, "Hi")
What can I change to make it recurse correctly?
Recursion involves making a function call itself and AVOIDS using a loop. You have a loop in the recursive function which is a big red flag.
Do something like this:
If n is 1 return s else return s concatenated to the result of the function with n - 1.
function repeatStr (n, s) {
if (n == 1)
return s;
else
return s.concat(repeatStr(n - 1, s))
}
repeatStr(3, "Hi")
Because you're new to programming and JavaScript, let's work up to the solution. Start with a simple case, e.g. repeatStr(3, "Hi"). One simple answer may be:
function repeatStr(n, s) {
return "HiHiHi";
}
Here, we assume what the inputs are always 3 and "Hi". We don't have a while loop, and we don't have recursion. We have the correct answer for those specific inputs but no other inputs are supported.
Let's make the answer a little bit harder:
function repeatStr(n, s) {
return "Hi" + "Hi" + "Hi";
}
Here, again, we are assuming the inputs are 3 and "Hi". We still don't have a while loop nor do we have recursion.
Okay, let's start using one of your inputs:
function repeatStr(n, s) {
return s + s + s;
}
Here, we are finally using the string that's passed in as s. We can handle inputs other than "Hi" to generate a correct answer. But, we're still assuming the number input is 3.
Finally, let's have a look at n:
function repeatStr(n, s) {
let result = "";
while (n > 0) {
n = n - 1;
result = result + s;
}
return result;
}
Okay, here we take both inputs n and s into consideration and we solve the problem by appending s exactly the number n times needed. This is a while loop solution, not a recursion solution. Our while loop has the action result = result + s; repeated exactly n times where we use n as a countdown and stop when we reach 0.
Now, we have all that background, let's look at one version of the recursion solution.
function repeatStr(n, s) {
if (n <= 0) {
return "";
}
return s + repeat(n - 1, s);
}
Even in recursion form we retain the countdown feature. This time the countdown is used to drive the recursion instead of a while loop. We still counting down to 0 where we have an if-return guard condition that's needed to terminate the recursion. i.e. when n <= 0, we exit with the simple empty string "". Then for the more complex case, it is solving any nth version by expressing in terms of the (n-1) th version. Another way of looking at it is this:
repeatStr(3, "Hi") === "Hi" + repeatStr(2, "Hi")
=== "Hi" + "Hi" + repeatStr(1, "Hi")
=== "Hi" + "Hi" + "Hi" + repeatStr(0, "Hi")
=== "Hi" + "Hi" + "Hi" + ""
If you want to get a little clever, JavaScript has a conditional which can be used in place of your if statement:
function repeatStr(n, s) {
return (n <= 0) ? "" : s + repeat(n - 1, s);
}
Hope that makes sense.
Adding a decomposed approach to the other nice answers in this thread -
const concat = a => b =>
a.concat(b)
const repeat = n => f =>
x => n && repeat(n - 1)(f)(f(x)) || x
const hello =
repeat(3)(concat("Hi"))
console.log(hello("Alice"))
console.log(hello(""))
HiHiHiAlice
HiHiHi
This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 3 years ago.
I have a function that takes an input (n) and puts it in the parameters of another function. (n) represents in the second equation the number to what (m) is being compared to (in this case 10). I understand how this function is structured, just don't understand what this means:
return m => m > n;
function greaterThan(n) {
return m => m > n;
}
let greaterThan10 = greaterThan(10);
console.log(greaterThan10(9)); //should output false
m => m > n is an arrow function in javascript. almost same as,
function(m){
return m>n
}
Read more here http://2ality.com/2012/04/arrow-functions.html
This is an example of currying. The function greaterThan is returning a new anonymous function. It's probably easier to understand written like this:
function greaterThan(n) {
return function (m) {
return m > n
}
}
Calling greaterThan(10) returns a new function that will compare its argument to 10. In your example you give it the name greaterThan10 so now you can call greaterThan10(9). This is all because the other function returns another function to use.
You can rewrite your example:
function greaterThan(n) {
return function(m) { return m > n }
}
which uses the same function syntax for both of them.
Otherwise I found your explanation to be let much what anyone would write to explain it. m is simply the parameter to the function returned.
I was in codewars this morning and there is this Kata asking for a function to reverse a string passed as parameter through recursion method.
The best solution listed for this problem was this.
function reverse(str) {
return str.length > 1 ? reverse(str.slice(1)) + str[0] : str;
}
I researched for this all this morning and I still don't know what is happening here:
+ str[0]
Can somebody please clarify this for me?
The essence of the function is the following:
Take the substring from the second character to the last
Apply the reverse function recursively
Take the first character and append it to the end of the result of the recursive call
Return the result
This results in the following logic, the (recursive) function calls indicated by brackets:
(A B C D E)
((B C D E) A)
(((C D E) B) A)
((((D E) C) B) A)
(((((E) D) C) B) A)
str.slice(1) "chops off" the first letter of the string and returns the rest of it. So 'abcd'.slice(1) gives you 'bcd'.
str[0] is the first letter of the string. 'abcd'[0] is 'a'.
So, str.slice(1) + str[0] is taking the first letter of the string and "moving" it to the end: 'abcd' becomes 'bcda'.
This does not address the recursive nature of the solution, but it answers your question about + str[0].
I'll try to rewrite the function in a more "human-readable" way
reverse = str => {
// If there is still string to reverse
if (str.length > 1) {
let firstChar = str[0]
let strWithoutFirstChar = str.slice(1)
// Notice only a part of the string 'comes back' here
// console.log(strWithoutFirstChar) // Might help
return reverse(strWithoutFirstChar) + firstChar
}
// Else return result as is
else {
return str
}
}
This is the same function, but without ternaries and declaring well named variables.
If you uncomment the console.log() line and call:
reverse('help');
The output should be:
elp
lp
p
'pleh'
Hope it helps!
The + operator is a concatenator for string.
You can instead use concat this :
var reverse = str => str.length > 1 ? reverse(str.slice(1)).concat(str[0]) : str;
console.log(reverse("123456789")); // 987654321
I've completely drawn a blank on how to get a string to return properly inside of an if statement.
function truncateString(str, num) {
var s = str;
var n = num;
if(s > n.length) {
return s.slice(0, n - 3).concat("...");
} else return s;
}
truncateString("This string is too long", 11);
I know I've got it all wrong but can't figure out how to make it work.
Please do not post the solution, just remind me how to return the string correctly within an if statement.
It's fine, you just swapped the arguments by mistake.
if(s > n.length)
should be
if(s.length > n)
Basically a number do not have a property called length with it,
if(s.length > n)
Full code would be,
function truncateString(str, num){
var s = str;
var n = num;
if(s.length > n) {
return s.slice(0, n - 3).concat("...");
}
else {
return s;
}
}
truncateString("This string is too long", 11);
//"This str..."
You're accessing the .length property on the wrong object. (You're asking for the number length instead of the string length). This means your if statement's primary condition never executes, and the function returns the whole string every time.
I believe you have at least one error on the logic. Instead of comparing s with n.length, you need to compare str/s length with num/n.
And I think what you were trying to use is the conditional ternary operator ?:
The next is a modified version of yours.
function truncateString(str, num)
{
var s = str;
var n = num;
return (s.length > n) ? s.slice(0, n - 3).concat("...") : s;
}
alert(truncateString("This string is too long", 11));
Variable 'n' holds a primitive value but not an object.That's why there is no 'length' property of variable 'n'. So n.length statement returns 'undefined' value. Finally s > n.length statement returns false and if block never executes. You could use s.length instead.Here 's' holds string value and string is also primitive value in JavaScript but at run time string value converts into its wrapper String Object whenever you try to access any property of it including length property.
If I got a Letter in JavaScript, I'd like to find out the previous letter in alphabetic order, so if input is "C", output must be "B". Are there any standard solutions or do i have to create some special functions?
var ch = 'b';
String.fromCharCode(ch.charCodeAt(0) - 1); // 'a'
And if you wanted to loop around the alphabet just do a check specifically for 'a' -- loop to 'z' if it is, otherwise use the method above.
This should work in some cases, you might need to tweak it a bit:
function prevLetter(letter) {
return String.fromCharCode(letter.charCodeAt(0) - 1);
}
If letter is A, the result is #, so you need to add some sanity checking if you want it to be foolproof. Otherwise should do the job just fine.
The full function from Tatu's comment would be
function prevLetter(letter) {
if (letter === 'a'){ return 'z'; }
if (letter === 'A'){ return 'Z'; }
return String.fromCharCode(letter.charCodeAt(0) - 1);
}
Something like this should work.
function prevLetter(letter) {
var code = letter.charCodeAt(0);
var baseLetter = "A".charCodeAt(0);
if (code>"Z".charCodeAt(0)) {
var baseLetter = "a".charCodeAt(0);
}
return String.fromCharCode((code-baseLetter+25)%26+baseLetter);
}