Hey guys I am trying to build a function that counts the number of employees in each store. As you can see I have a class for stores, and a class for employees down below.
class Stores {
constructor(place, employees) {
this.place = place;
this.employees = employees;
}
}
class Employees {
constructor(name) {
this.name = name;
this._EmployeeID = Employees.counter; //ID for the employee
}
get EmployeeID() {
return this._EmployeeID
}
static get counter() {
Employees._counter = (Employees._counter || 0) + 1;
return Employees._counter
}
}
Here I have listed some employees and stored them into lists
//employees
const employee1 = new Employees("Torben")
const employee2 = new Employees("Mike")
const employee3 = new Employees("Rikke")
const employee4 = new Employees("Walid")
const employee5 = new Employees("Jens")
I have tried to build this function that loops over the objects, to count them, however for some reason I am not getting the correct result.
const copenhagenstore = new Stores("Copenhagenstore", {employee1, employee2, employee5})
function countemployees(store) {
var length = 0;
for(var key in store) {
console.log(key)
if(store.hasOwnProperty(key) ) {
++length;
}
}
return length;
};
console.log("the number of employees are: " + countemployees(copenhagenstore))
Below is my output, and as you can see, there should be 3 employees instead of two. I am pretty sure my function needs a bit of rework to account for this, and I was hoping that you guys could help me with that.
//OUTPUT
the number of employees are: 2
Stores {
place: 'Copenhagenstore',
employees: {
employee1: Employees { name: 'Torben', _EmployeeID: 1 },
employee2: Employees { name: 'Mike', _EmployeeID: 2 },
employee5: Employees { name: 'Jens', _EmployeeID: 5 }
}
}
Related
I have all of the components for this project with the exception of a class method to show the first two images in the array (the Pokeball, and the default eevee) then randomly choose from an array one more image(eevee evolutions) and then stop.
Please be patient I am very new to this.
class Pokemon {
constructor() {
this.listOfCharmander = [
"./images/pokeball.png",
"./images/charmander/charmander0.png",
"./images/charmander/charmander1.png",
"./images/charmander/charmander2.png",
];
this.index = 0;
this.pokemon = document.createElement("img");
}
handleClick = () => {
if (this.index < 3) {
++this.index;
this.pokemon.src = this.listOfCharmander[this.index];
}
};
buildPokemon = () => {
this.pokemon.src = this.listOfCharmander[0];
this.pokemon.classList.add("pokemon");
this.pokemon.addEventListener("click", this.handleClick);
main.appendChild(this.pokemon);
};
}
const pokemon = new Pokemon();
const pokemon1 = new Pokemon();
pokemon.buildPokemon();
pokemon1.buildPokemon();
class Eevee {
constructor() {
this.eeveeEvolutions = [
"/images/pokeball.png",
"images/eevee/eevee0.png",
"images/eevee/eevee1.png",
"images/eevee/eevee2.png",
"images/eevee/eevee3.png",
"images/eevee/eevee4.png",
"images/eevee/eevee5.png",
"images/eevee/eevee6.png",
"images/eevee/eevee7.png",
"images/eevee/eevee8.png",
];
this.index = 0;
this.eevee = document.createElement("img");
}
handleClick = () => {
if (this.index < 9) {
++this.index;
this.eevee.src = this.eeveeEvolutions[this.index];
}
};
buildEevee = () => {
this.eevee.src = this.eeveeEvolutions[0];
this.eevee.classList.add("eevee");
this.eevee.addEventListener("click", this.handleClick);
main.appendChild(this.eevee);
};
}
const eevee = new Eevee();
const eevee1 = new Eevee();
eevee.buildEevee();
eevee1.buildEevee();
...
I apologize if my question isnt exactly clear. I need to add to my handClick method. A way display the first image (the Pokeball) and then the 2nd image (default eevee) And then randomly choose (including having it stay the same there could be no evolution at all) one more evolution from the remaining array.
if you always need first two images in your array then you can add extra attribute to your Eevee class to store those images path, and for random image you can add this code to your handleClick()
handleClick = () => {
this.index=Math.floor(Math.random(2,9)*10)
this.eevee.src = this.eeveeEvolutions[this.index];
};
I built two classes, a product with name and price and a shopping cart for an array of products; for the ShoppingCart get totPrice method I'm using the reduce() function on the array cart of the constructor, but I'm always getting the error above and I don't get why.
class Product {
constructor(name,price) {
this.name = name;
this.price = price;
}
toString() {
console.log(this.name + ' - ' + this.price);
}
}
class ShoppingCart {
constructor(cart) {
this.cart = cart;
}
get totPrice() {
return this.cart.reduce((el1,el2) => {el1.price + el2.price});
}
addProd = function(prod) {
this.cart.push(prod);
this.cart.totPrice += prod.price;
if(this.cart.length >= 5){
this.totPrice = this.totPrice * 0.9;
}
if(this.cart.filter(tmp => tmp.name === prod.name).length % 4 === 0){
this.totPrice -= prod.price;
}
}
removeProd = function(prod) {
let i = this.cart.findIndex(el => {prod.name === el.name});
this.cart.splice(i,1);
console.log(`The product ${prod.name} has been removed from your shopping cart`);
}
}
let prod1 = new Product('Apple',15);
let prod2 = new Product('Banana',20);
let prod3 = new Product('Melon',25);
let shopCart = new ShoppingCart([prod1,prod2,prod3]);
console.log(shopCart.totPrice);
There is already an answer for this one explained here.
After the first iteration your're returning a number and then trying to get property sum.price of it to add it to the next object which is undefined. Also you need a initial value for the sum.
get totPrice() {
return this.cart.reduce((acc,el) => acc + el.price,0);
}
i really don't know what I'm doing wrong... it returns an array with the number of rows in the collection but all null.
i followed the documentation perfectly but i'm just extremely confused
basically i have a collection in my database called mytest, and i'm trying to add the valuses in each document (token) to return when i call the route /mytest-sum
module.exports = {
/**
* Retrieve records.
*
* #return {Array}
*/
async Sum(ctx) {
let entities;
if (ctx.query._q) {
entities = await strapi.services.mytest.search(ctx.query);
} else {
entities = await strapi.services.mytest.find(ctx.query);
}
//return entities.map(entity => sanitizeEntity(entity, { model: strapi.models.mytest}));
entities = entities.map(entity => (entity, { model: strapi.models.mytest }));
entities = entities.map(entry => {
entry = Object.assign(entry, {
sumField: entry.token
});
});
return entities;
},
};``
module.exports = {
async Add(ctx) {
let add = 0;
let fruits = []
// get data from database
let entities;
if (ctx.query._q) {
entities = await strapi.services.mytest.search(ctx.query);
} else {
entities = await strapi.services.mytest.find(ctx.query);
}
//get specific data-field from data and map it to an array
fruits = entities.map(entity => sanitizeEntity(entity, { model: strapi.models.mytest }).token);
// add array values in for loop
for (let i = 0; i < fruits.length; i++) {
add += fruits[i];
}
//return sum as a number
return add;
}};
I'm trying to make language learn app and i have a problem. I have class "Word"
class Word {
constructor(englishWord, polishWord){
this.englishWord = englishWord
this.polishWord = polishWord
this.displayTranslation = () =>{
console.log(`${englishWord} = ${polishWord}`)
}
}
}
and lots of objects like
const intimate = new Word('intimate', 'intymny/prywatny')
const insurance = new Word('insurance', 'ubezpieczenie')
and I honestly don't have idea how to push all objects into one array. Can I use 'foreach' on every class object? Or is there a better solution for this?
You have to declare a global array where all instances will be pushed to
const instances = [];
class Word {
constructor(englishWord, polishWord){
this.englishWord = englishWord;
this.polishWord = polishWord;
this.displayTranslation = () =>{
console.log(`${englishWord} = ${polishWord}`);
};
instances.push(this);
}
static GetWords() {
instances.forEach( x => {
x.displayTranslation();
});
}
}
new Word('intimate', 'intymny/prywatny');
new Word('insurance', 'ubezpieczenie');
Word.GetWords();
Let's build up your problem in natural language before we write some code:
A Word has its nativ and translation. A Word is stored in a Dictionary. You can add translations to a Dictionary and so on..
For that the array would be hide in a Dictionary like
class Dictionary {
constructor() {
this.words = []
}
addTranslation(word) {
this.words.push(word)
}
// more ..
}
Code Snippet
class Word {
constructor(englishWord, polishWord) {
this.englishWord = englishWord
this.polishWord = polishWord
this.displayTranslation = () => {
console.log(`${englishWord} = ${polishWord}`)
}
}
}
class Dictionary {
constructor() {
this.words = []
}
addTranslation(word) {
this.words.push(word)
}
print() {
for (let i = 0; i < this.words.length; i++) {
this.words[i].displayTranslation()
}
}
}
const dictionary = new Dictionary()
const intimate = new Word('intimate', 'intymny/prywatny')
const insurance = new Word('insurance', 'ubezpieczenie')
dictionary.addTranslation(intimate)
dictionary.addTranslation(insurance)
dictionary.print()
Improvement
I suggest to use a Map instead of an Array. If the Dictionary will be extended by methods for finding words than you have to find the words in an Array by your self..
class Word {
constructor(englishWord, polishWord) {
this.englishWord = englishWord
this.polishWord = polishWord
this.displayTranslation = () => {
console.log(`${englishWord} = ${polishWord}`)
}
}
}
class Dictionary {
constructor() {
this.words = {}
}
addTranslation(word) {
this.words[word.englishWord] = word.polishWord
}
getTranslation(english) {
return this.words[english]
}
print() {
for (let i = 0; i < this.words.length; i++) {
this.words[i].displayTranslation()
}
}
}
const dictionary = new Dictionary()
const intimate = new Word('intimate', 'intymny/prywatny')
dictionary.addTranslation(intimate)
console.log(dictionary.getTranslation('intimate'))
You can push class objects into an Array without any issue:
// using your class declared above
const intimate = new Word('intimate', 'intymny/prywatny')
var array = [];
array.push(intimate);
But depending on your needs, you could put something like this directly into the constructor and have it collect all of the items it's constructed for you:
const instances = [];
class Word {
constructor(englishWord, polishWord){
this.englishWord = englishWord
this.polishWord = polishWord
this.displayTranslation = () =>{
console.log(`${englishWord} = ${polishWord}`)
}
Word.addInstance(this);
}
static addInstance(item){
instances.push(item);
}
static getInstances(){
return instances;
}
static clearInstances(){
instances.length = 0;
}
}
With this every time you construct an instance it's added to the external array. If you need to get everything from the array you can call Word.getInstances() or Word.clearInstances() if you want to empty it.
I need to be able to add a student and a grade. however, I am having a difficult time figuring out how to enter a grade. This is what I have so far. When I run the program like this I get: [ Student { name: 'Bob', grades: [], totalGrades: 0 } ] Any help would be appreciated!
The commented out section was an attempt at adding grades, however, I did not work at all.
function Student(name){
this.name = name;
this.grades = [];
this.totalGrades = function(){
this.totalGrades = 0;
this.grades.forEach(grade => {
this.totalGrade += grade;
})
}
}
function Students(){
this.students = [];
// this.grades = [];
/* this.addGrade = function(grade){
this.grades.push(grade);
}*/
this.addStudent = function(student){
this.students.push(student);
}
this.calcTotalGrades = function(){
this.students.forEach(student => {
student.totalGrades();
})
}
}
let students = new Students();
students.addStudent(new Student('Bob'));
students.calcTotalGrades();
console.log(students.students);
Try this function, as a method of your Students:
this.addGrade = function(student,grade) {
this.students.forEach(student => {
if(student.name === student)
student.grades.push(grade)
}
}
To add a new grade:
students.addGrade('Bob',10);