Product Class
Create new Javascript file named product.js. This file contains code demo as below:
class Product {
constructor(id, name, price, quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
toString() {
return 'Id: ' + this.id + '\nName: ' + this.name + '\nPrice: ' + this.price + '\nQuantity: ' + this.quantity;
}
total() {
return this.price * this.quantity;
}
}
module.exports = Product;
Create Index
Create new Javascript file named index.js. This file contains code demo as below:
let Product = require('./product');
let product1 = new Product("p01", "laptop 1", 4, 2);
let product2 = new Product("p02", "laptop 2", 11, 3);
let product3 = new Product("p03", "computer 1", 7, 8);
let products = [product1, product2, product3];
console.log("Starts With");
products.filter(p => p.name.startsWith("lap"))
.forEach(function (product, index) {
console.log("Product " + index + ' Info');
console.log(product.toString());
console.log('------------------------');
});
console.log("Ends With");
products.filter(p => p.name.endsWith("top 2"))
.forEach(function (product, index) {
console.log("Product " + index + ' Info');
console.log(product.toString());
console.log('------------------------');
});
console.log("Contains");
products.filter(p => p.name.includes("puter"))
.forEach(function (product, index) {
console.log("Product " + index + ' Info');
console.log(product.toString());
console.log('------------------------');
});
Output
Use node index.js statement run code demo
Starts With
Product 0 Info
Id: p01
Name: laptop 1
Price: 4
Quantity: 2
------------------------
Product 1 Info
Id: p02
Name: laptop 2
Price: 11
Quantity: 3
------------------------
Ends With
Product 0 Info
Id: p02
Name: laptop 2
Price: 11
Quantity: 3
------------------------
Contains
Product 0 Info
Id: p03
Name: computer 1
Price: 7
Quantity: 8
------------------------