|
1 | 1 | // Exercice : objet avec une méthode : l'objet magique `this` |
2 | 2 |
|
3 | 3 | o = { |
4 | | - x: "Romu", |
5 | | - y: 41, |
| 4 | + x: "Guillaume", |
| 5 | + y: 40, |
6 | 6 | do: function () { |
7 | 7 | console.log(this.x, this.y); |
8 | 8 | }, |
@@ -41,6 +41,24 @@ iterate_array_while([1, 1, 2, 3, 5, 8]); |
41 | 41 | console.log("Array.forEach"); |
42 | 42 | [1, 1, 2, 3, 5, 8].forEach(x => console.log(x)) |
43 | 43 |
|
| 44 | +// Exercice 1 : 99 Bottles of Beer |
| 45 | +// ---------------------------- |
| 46 | + |
| 47 | +function bottles(beers) { |
| 48 | + console.log("[js] bottles (" + beers + ")"); |
| 49 | + let res = ""; |
| 50 | + |
| 51 | + const bottle = n => `${n || "No more"} bottle${n === 1 ? "" : "s"} of beer`; |
| 52 | + |
| 53 | + for (let n = beers; n > 0; n--) { |
| 54 | + res += `${bottle(n)} on the wall, ${bottle(n).toLowerCase()}. |
| 55 | +Take one down and pass it around, ${bottle(n - 1).toLowerCase()} on the wall. |
| 56 | +
|
| 57 | +`; |
| 58 | + } |
| 59 | + |
| 60 | + return res.trim(); |
| 61 | +} |
44 | 62 |
|
45 | 63 | // Exercice 2 : fonction `range` |
46 | 64 | // ---------------------------- |
@@ -78,3 +96,30 @@ function fibonacci_fa(n) { |
78 | 96 |
|
79 | 97 | console.log(fibonacci_fa(8)); |
80 | 98 |
|
| 99 | +// Exercice 4 : calculatrice polonaise inverse |
| 100 | +// ---------------------------- |
| 101 | + |
| 102 | +let evaluate = function (expr) { |
| 103 | + console.log("[js] evaluate (" + expr + ")"); |
| 104 | + let results = []; |
| 105 | + |
| 106 | + const ops = { |
| 107 | + "+": (a, b) => a + b, |
| 108 | + "-": (a, b) => a - b, |
| 109 | + "*": (a, b) => a * b, |
| 110 | + "/": (a, b) => a / b, |
| 111 | + }; |
| 112 | + |
| 113 | + expr.split(" ").forEach(item => { |
| 114 | + let nb = parseFloat(item); |
| 115 | + |
| 116 | + if (!isNaN(nb)) results.push(nb); |
| 117 | + else { |
| 118 | + let b = results.pop(); |
| 119 | + let a = results.pop(); |
| 120 | + results.push(ops[item](a, b)); |
| 121 | + } |
| 122 | + }); |
| 123 | + |
| 124 | + return results.pop() || 0; |
| 125 | +}; |
0 commit comments