generated from comp426-2022-spring/a03
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coin.mjs
105 lines (94 loc) · 2.39 KB
/
coin.mjs
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/** Coin flip functions
* This module will emulate a coin flip given various conditions as parameters as defined below
*/
/** Simple coin flip
*
* Write a function that accepts no parameters but returns either heads or tails at random.
*
* @param {*}
* @returns {string}
*
* example: coinFlip()
* returns: heads
*
*/
export function coinFlip() {
var random = Math.floor(Math.random() * 2);
if (random < 1) {
return 'heads';
}
return 'tails';
}
/** Multiple coin flips
*
* Write a function that accepts one parameter (number of flips) and returns an array of
* resulting "heads" or "tails".
*
* @param {number} flips
* @returns {string[]} results
*
* example: coinFlips(10)
* returns:
* [
'heads', 'heads',
'heads', 'tails',
'heads', 'tails',
'tails', 'heads',
'tails', 'heads'
]
*/
export function coinFlips(flips) {
var results = [];
for (var i = 0; i < flips; i++) {
results[i] = coinFlip();
}
return results;
}
/** Count multiple flips
*
* Write a function that accepts an array consisting of "heads" or "tails"
* (e.g. the results of your `coinFlips()` function) and counts each, returning
* an object containing the number of each.
*
* example: conutFlips(['heads', 'heads','heads', 'tails','heads', 'tails','tails', 'heads','tails', 'heads'])
* { tails: 5, heads: 5 }
*
* @param {string[]} array
* @returns {{ heads: number, tails: number }}
*/
export function countFlips(array) {
var results = {heads: 0, tails: 0};
for (var i = 0; i < array.length; i++) {
var coin = array[i];
if (coin == "heads") {
results.heads += 1;
}else{
results.tails += 1;
}
}
return results;
}
/** Flip a coin!
*
* Write a function that accepts one input parameter: a string either "heads" or "tails", flips a coin, and then records "win" or "lose".
*
* @param {string} call
* @returns {object} with keys that are the input param (heads or tails), a flip (heads or tails), and the result (win or lose). See below example.
*
* example: flipACoin('tails')
* returns: { call: 'tails', flip: 'heads', result: 'lose' }
*/
export function flipACoin(call) {
var flip = coinFlip();
var win_or_lose;
if (flip == call) {
win_or_lose = 'win';
}else{
win_or_lose = 'lose';
}
return {call: call, flip: flip, result: win_or_lose};
}
/** Export
*
* Export all of your named functions
*/