I was trying to write a quick example of a an object, and some prototypes for that object, and I was getting some unexpected results out of the code. I'm working with two files, index.js and cards.js The basic idea is to instantiate a new object called "deck" and then call some methods on that object. Here's my code
cards.js
//constructor
function cardsClass() {
this.cards = [
{ suit: 'heart', number: 1, name: 'ace' },
{ suit: 'heart', number: 10, name: 10 },
{ suit: 'heart', number: 11, name: 'jack' },
{ suit: 'heart', number: 12, name: 'queen' },
{ suit: 'heart', number: 13, name: 'king' }
];
}
//class method
cardsClass.prototype.getCards = function() {
return this.cards;
}
cardsClass.shuffle_helper = function (input_cards, return_deck, callback) {
if (input_cards.length !=0) {
index = Math.floor(Math.random() * input_cards.length);
if (input_cards[index]) {
return_deck.push(input_cards[index]);
input_cards.splice(index, 1);
}
cardsClass.shuffle_helper(input_cards, return_deck, callback);
}
else {
callback(null, 'success');
}
}
//class method
cardsClass.prototype.shuffle = function (callback) {
//set up a temp deck...
var return_deck = [];
cardsClass.shuffle_helper(this.cards, return_deck, function (err, results) {
this.cards = return_deck;
callback(null, this.cards);
});
}
module.exports = cardsClass;
index.js
var cards = require('./cards.js');
deck = new cards();
console.log( deck.getCards() );
deck.shuffle(function (err, results){
console.log ('our results of a deck.shuffle');
console.log (results);
});
console.log ('and this is what our getCards function returns');
console.log( deck.getCards() );
console.log ('looking at deck.cards');
console.log (deck.cards);
The results I get from running this code is below
$ node index.js
[ { suit: 'heart', number: 1, name: 'ace' },
{ suit: 'heart', number: 10, name: 10 },
{ suit: 'heart', number: 11, name: 'jack' },
{ suit: 'heart', number: 12, name: 'queen' },
{ suit: 'heart', number: 13, name: 'king' } ]
our results of a deck.shuffle
[ { suit: 'heart', number: 1, name: 'ace' },
{ suit: 'heart', number: 11, name: 'jack' },
{ suit: 'heart', number: 13, name: 'king' },
{ suit: 'heart', number: 10, name: 10 },
{ suit: 'heart', number: 12, name: 'queen' } ]
and this is what our getCards function returns
[]
looking at deck.cards
[]
It looks like I'm getting proper results from my card shuffle, but when I look back at what "cards" contains, I get unexpected results, even though I'm setting the value. I'm having some trouble understanding why this is. Also, is it poor form to return results in this way, or should I be using a traditional "return" statement like I have in the getCards method?
Thanks in advance.
varin front of local variable declarations so you're not creating accidental, implicit global variables. It's also unclear why you're using recursion when a simplefororwhileloop would work just fine.