-
Notifications
You must be signed in to change notification settings - Fork 21
/
cards.js
81 lines (61 loc) · 2.3 KB
/
cards.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
var makeCard = // receive factory with external name `makeCard`
(function () { //begin IIFE...
// The factory itself:
function makeCard(id) { //makeCard is also IIFE's internal name
if (!isValidID(id))
return null;
var card = {
id:id, //personal property
// links to shared methods, defined below:
rank : rank,
suit : suit,
color: color,
name : name
};
return card;
};
//------------------
// Private resources (internal use only)
//------------------
var isValidID = function(num) { // Returns--> true, false
return ((typeof num)==="number") //correct type
&& (num%1 === 0) //integer
&& num>=0 && num<=51; //in range
};
var rankNames = ['','Ace','Two','Three','Four','Five','Six','Seven',
'Eight','Nine','Ten','Jack','Queen','King'];
var suitNames = ['','Hearts','Diamonds','Spades','Clubs'];
//-----------------------
// Methods to be called through factory:
//-----------------------
makeCard.isCard = function(card) { // Returns --> true, falsish
return card && (typeof card === 'object') // check for null or primitive
&& (card.name === name) // check at least one method
&& ('id' in card) && isValidID(card.id); //check id
};
//-----------------------------
// Methods called though instances (where 'this' means the instance):
//-----------------------------
var rank = function() { // --> 1..13, NaN
return Math.floor(this.id/4)+1;
};
var suit = function() { // --> 1..4, NaN
return (this.id%4)+1;
};
var color = function() { // -->"red,"black", NaN
var suitVal=this.suit();
return suitVal && ((suitVal<3)? "red": "black");
};
var name = function() { //--> string, NaN
var rankVal = this.rank();
var suitVal = this.suit();
return rankVal && suitVal &&
(rankNames[rankVal]+' of '+suitNames[suitVal]);
};
// Use factory to create full set:
makeCard.fullSet = [];
for (var id=0; id<52; ++id) {
makeCard.fullSet.push(makeCard(id));
}
return makeCard; //return factory function, product of IIFE's work
})(); //end IIFE definition and do it now!