-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinterfaces-classes.ts
More file actions
74 lines (57 loc) · 1.64 KB
/
interfaces-classes.ts
File metadata and controls
74 lines (57 loc) · 1.64 KB
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
interface IProduct {
name: string;
price: number;
isActive: boolean;
}
interface IShopService {
products: IProduct[];
productsCount: number;
addProduct(product: IProduct): boolean;
sellProduct(productName: string): void;
}
class ShopService implements IShopService {
private _products: IProduct[] = [];
constructor() { }
public get products(): IProduct[] {
return this._products;
}
// no setter to keep it readonly
// public set products(value: IProduct[]) {
// this._products = value;
// }
public get productsCount(): number {
return this._products.length;
}
public addProduct(product: IProduct): boolean {
if (this._products === null || this._products === undefined) {
return false;
}
else {
this._products.push(product);
return true;
}
}
public sellProduct(productName: string): void {
const productToDeleteIndex: number = this._products
.findIndex((prod: IProduct) => prod.name === productName);
if (productToDeleteIndex > -1) {
this._products.splice(productToDeleteIndex, 1);
}
}
}
const shop: ShopService = new ShopService();
if (shop.addProduct({
name: "Coke",
price: 10,
isActive: true
})) {
console.log("Added successfully");
}
else {
console.log("Adding product failed");
}
console.log(`Products count: ${shop.productsCount}`);
shop.sellProduct("Bla bla"); // no such product
console.log(`Products count: ${shop.productsCount}`);
shop.sellProduct("Coke");
console.log(`Products count: ${shop.productsCount}`);