How to count backwards [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Hey guys im developing something and I need to fix this please give me some feedback on how to improve this. (how to make it cleaner, easier to read , etc). Here's the code!
function wordFliper(word) {
let wordOutput = "";
let reverseIndex = word.length - 1;
for (let index = reverseIndex; index >= 0; index--) {
let storage = word[index];
wordOutput = wordOutput + storage;
}
return wordOutput;
}

I would remove some variables (variables that are used once in loop and then assigned to a function variable) to reduce code and rename one like this:
/// <summary>Function to flip words backwards</summary>
/// <param name="word" type="string">Word to be flipped</param>
/// <returns type="string">Word flipped</returns>
function wordFlipper(word) {
let flippedWord = "";
for (let i = word.length - 1; i >= 0; i--) {
flippedWord += word[i];
}
return flippedWord;
}
Also IMHO use i variable instead of index (for loop incrementer)
And Also get used to commenting your code, to know what is for the functions you're writing
I hope you helped to keep your code clean for further programming and happy coding!

You can use JS array functions like reduce(),split(),reverse(), etc. You can write the code in following ways:
function wordFlipper(word) {
return(word.split('').reverse().join(''));
}
function wordFlipper(word) {
return(word.split('').reduce((a,c)=>c+a));
}
Please go through the links for clarity on the functions used above:
split() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
join() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
reverse() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
reduce() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Related

Javascript - Sum solution [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am getting below line in my source file and I would like to sum those values separated by pipe ("|")
There is no limit for the values coming in the line (might be 100 values)
10|20|30|40|[no limit for values] - Separator is pipe "|"
The ouptput would be 100
Please help to write a javascript function for the above query.
Regards
Jay
You should take a look at JavaScript's built-in functions: With split you can split your string into an array, with reduce you can 'reduce' your array to a single value, in that case via summation. These two links should provide you enough information for building your code.
You could try something like below:
function sum(value){
var total = 0;
var array = value.split(",").map(Number);
for( var i = 0; i < array.length; i++) {
total += array[i];
}
alert(total);
}
var value = "10|20|30|40".replace(/\|/g, ',');
console.log(sum(value));
https://jsfiddle.net/f7uqw7cL/

For loop and hoisting [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a question.
For example I use for loop like this:
for ( var i = 0; i < some_length; i++ ) {
/* some code */
}
After that variable i is hoisted.
Does it mean that I always should declare i variable at the beginning of the scope?
var i;
for ( i = 0; i < some_length; i++ ) {
/* some code */
}
UPD:
I know that both loops work the same way.
I mean which one is more correct?
Modern JavaScript supports block scoping via let.
for ( let i = 0; i < some_length; i++ ) {
/* i is defined here */
}
/* i is not defined here * /
Back to the original quetion: which example is more correct?
I would argue that the second one is less error prone.
In your example - first one is classic type declaration of your iterator variable. In other cases like when you operate on many functions/objects/variables i recommend you to declare all variables on the beginning of your scope/object/function.
When you see code wrote in that way in future it will be much easier to see what is going on in here. You just look on first 10-15 lines of code and you would not search for every variable inside - everything will be explained in the beggining of your code.

Why does Douglas Crockford write `if` conditionals that are executed everytime except the first? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've been reading his book and he does stuff like this is a lot. For example, on p. 48 of JavaScript: The Good Parts, he has the function
Cat.prototype.purr = function ( n )
var i, s = '';
for ( i = 0; i < n; i += 1 )
{
if (s) {
s += '-';
}
s += 'r';
}
return s;
}
where the if conditional if essentially useless since it returns true every time but the first. The function could be written equivalently
Cat.prototype.purr = function ( n )
var i, s = 'r';
for ( i = 2; i < n; i += 1 )
{
s += '-r';
}
return s;
}
for better performance. Also, why does he define i outside the for loop?
The two functions are not the same. The original function returns an empty string of n is 0. Your function returns "r" if n is 0;
I am guessing that this is just an example to illustrate a common need where you want to separate a list of items with a character like '-' or ','.
You might write a loop like this and instead of 'r' you would have the names of items. E.g. "Bob-Mike-Jill-Jack"
To simplify the example for the book then he has just used 'r' which means the code could be written a different way like you say. But for a generic list you do want to add the separator every time except the first.
In regards to the var placement if you are declaring s then it is less chars to declare i there as well rather than write out var again in the loop. But I suspect it is probably just his idea of good practice to declare all variables that you use at the start of the function.

How do I rearrange an array with similar items so that similar items will never neighbor each other? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So for example if I have this array:
var input = [1,1,2,4,6,7,7,1];
I want the output to be something like:
[1,2,1,4,6,7,1,7]
The order of the new array does not matter, as long as similar items will never (or at least as seldom as possible) neighbor each other.
I can use plain JavaScript as well as underscore.js.
Try the following:
var input = [1,1,2,4,6,7,7,1];
input.sort()
var output = [];
var len = input.length;
for (var i = 0; i < Math.floor((len / 2)); i++) {
output.push(input[i]);
output.push(input[len - i - 1]);
}
if (len % 2) {
var left_over = input[Math.floor(len / 2)];
if (left_over == output[0]) {
output.push(left_over);
} else {
output.unshift(left_over);
}
}
Or see http://jsfiddle.net/d0j3Lfa3/1.
The solution sorts the numbers then alternates high and low. It deals with an odd number of elements, including corner cases such as [1,1,2] and [1,2,2] where it needs to push the middle element differently to pass. Since the input is sorted, input order doesn't affect the output.
This answer may help simplify things a bit.

My first permutation lesson - what is this code missing? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Translated (apparently wrongly) from a C++ book.
If I can get it to work, then I can start trying to understand it.
function recPermute(soFar, rest)
{
if (rest==="")
{
console.log(soFar);
}
else
{
for(i=0; i<rest.length; i++) // <<< error was in not declaring the "i"
{
var next = soFar + rest[i];
var remaining = rest.substr(0,i) + rest.substr(i+1);
recPermute(next, remaining);
}
}
}
function listPerm(s)
{
recPermute("",s);
}
listPerm("kitcap")
You need to declare i so it's scoped to recPermute:
for(var i=0; i<rest.length; i++)
Without the var, it'll be created as a global so each call to recPermute will alter it for any other calls.
for JavaScript, use charAt(), instead of using array like acessing.
var next = soFar + rest.charAt(i);
One thing that could be an issue is you are using effectively the same i for each call to the function. You need to declare a local i or it will be declared in the global scope.
for(var i = 0; ....

Categories

Resources