Files
cours-420-301-ah/Classes_exemples.ipynb
T
2023-12-22 20:40:56 -05:00

9.1 KiB

Ce que nous voulons, une classe qui définit un match de dodgeball!

In [33]:

// partie de dodgeball

class DodgeballGame{

    constructor(joueurs) {
        this.joueursEnVie = joueurs;
        this.joueursMorts = [];
        
    }

    kill(joueur){
        this.joueursMorts.push(joueur);
        const nouveauJoueursEnVie = []
        for(const joueurEnVie of this.joueursEnVie){
            if(this.joueursMorts.indexOf(joueurEnVie) === -1){
                nouveauJoueursEnVie.push(joueurEnVie);
            }
        }
        this.joueursEnVie = nouveauJoueursEnVie;
    }

    catchBall(){
        if(this.joueursMorts.length < 1){
            return;
        }
        const jesus = this.joueursMorts.shift();
        this.joueursEnVie.push(jesus);
    }
    
}

let players = ["a", "b", "c", "d", "e", "f"];

let game = new DodgeballGame(["a", "b", "c", "d", "e", "f"]);
game.kill("c");
game.kill("d")
game.catchBall();
console.log(game.joueursEnVie);
console.log(game.joueursMorts);
[ "a", "b", "e", "f", "c" ]
[ "d" ]

Définission premiere classe

In [2]:
class Politicien {

}

const politicien = new Politicien();

Classe avec méthode simple

In [12]:
class JackOfAllTrade{
   add(a, b){
       return a + b;
   }

   multiply(a, b){
       return a * b;
   }

   add1(x){
       return this.add(x, 1);
   }
}
In [13]:
let joat = new JackOfAllTrade()
joat.add(109, 90)
Out [13]:
199
In [14]:
joat.add1(100)
Out [14]:
101
In [19]:

class ChangeCase{
    
    toSnake(str){
        str = str.replace(" ", "_");
        return str;
    }

}
let case1 = new ChangeCase();
case1.toSnake("hello world foifoi");
Out [19]:
"hello_world foifoi"
In [1]:
let s = "bonjour monde"
In [2]:
let idx = s.indexOf(" ")
In [3]:
s = s.replace(" ", "")
Out [3]:
"bonjourmonde"
In [5]:
s.substring(idx, idx + 1).toUpperCase()
Out [5]:
"M"
In [8]:
import {Point} from "https://cdn.jsdelivr.net/gh/didiercrunch/cours-420-301-ah@tp1.1/modules-examples/mod.js"
In [10]:
let point  = new Point(34, 78)
In [11]:
point.getX()
Out [11]:
34
In [12]:
point.getY()
Out [12]:
78
In [13]:
class Point2D{
    constructor(x, y){
       this.x = x;
       this.y = y;
    }

    distanceFromOrigin(){
        return Math.sqrt(this.x * this.x + this.y * this.y);
    }
}
In [15]:
let point2D  = new Point2D(34, 78)
point2D.distanceFromOrigin()
Out [15]:
85.0881895447306
In [17]:
new URL("https://example.com/didier/rocks")
Out [17]:
URL {
  href: "https://example.com/didier/rocks",
  origin: "https://example.com",
  protocol: "https:",
  username: "",
  password: "",
  host: "example.com",
  hostname: "example.com",
  port: "",
  pathname: "/didier/rocks",
  hash: "",
  search: ""
}
In [ ]: