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

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; ....

Related

How to count backwards [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 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

How to use `this` like an object and get its variables/functions by a string? [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 6 years ago.
Improve this question
I've got an object.
function Obj()
{
}
Obj.prototype.doSomething = function(thing)
{
this["do" + thing]();
}
Obj.prototype.doAlert = function()
{
alert("Alert!");
}
var obj = new Obj();
obj.doSomething("Alert");
This is just a shortened down version of my object, and is a lot bigger.
What I would like to do is that if you pass in 'Alert' it will run this.doAlert(); and if I pass in 'Homework' it will run this.doHomework();
Obviously, in this case, it is stupid to do it like this, but my final project is going to be completely different.
It works fine with window like this:
window["do" + thing]();
but I don't want it to be a global function, but to be part of obj.
Does anyone have an idea how I'd go about doing this?
Thanks in advance!
It turns out that when you get the function through this['functionName'], this is not bound to it.
This means you cannot use this.foo inside any function called like above.
To fix this, I used the following code:
this["do" + thing].bind(this)();
instead of this["do" + thing]();
JSFiddle: https://jsfiddle.net/auk1f8ua/

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 can I call an unnamed instance in javascript? [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 8 years ago.
Improve this question
So if I make a class, and then create new instances of that class without naming them -maybe with a loop that creates a bunch of instances- how can I call a specific (or unspecific) instance? For example, if I'm generating a bunch a squares, but I want to move a specific one somewhere, how would I do that?
Sorry if this is a total noob question, or if I miss-used some terminology, but I'm pretty new to programming.
Example code:
function example(x){
this.x = x;
}
for(var i=0; i<10; i++){
new example(1);
}
//now how would I get a specific instance of examples to have x = say, 10.
You could put each square in an array and access them that way:
function Square(i){
this.index = i;
}
Square.prototype = {
constructor: Square,
intro: function(){
console.log("I'm square number "+this.index);
}
}
var squares = [];
for(var i = 0;i < 10;i++){
squares.push(new Square(i));
}
squares.forEach(function(square){
// do something with each square
square.intro();
});
Demo: http://jsfiddle.net/louisbros/MpcrT/1/

Categories

Resources