Reputation: 51
Here is my code:
var arr = [];
class Art {
constructor() {
this.values = Array();
}
add(date, amount, currency, product) {
this.values.push([date, amount, currency, product].toString());
}
list() {
return this.values;
}
clear(date) {
for (let i = this.values.length - 1; i >= 0; --i) {
if (this.values[i][0] == date) {
this.values.splice(i, 1);
}
}
}
total() {
return this.values[this.amount + this.currency];
}
}
const art = new Art();
art.add('2017-04-25', 2, 'USD', 'Jogurt');
art.add('2017-04-25', 3, 'USD', 'French fries');
art.add('2017-04-27', 4.75, 'USD', 'Beer');
art.clear('2017-04-27');
console.log(art.list());
console.log(art.total());
total(); should return amount and currency which i've added to art.add. But it output undefined. I've tried to do my best. But all times i have undefined or NaN. Could you please help me?
Upvotes: 2
Views: 49
Reputation: 386578
You need to store the values in an array, not a string representation of the data array.
For keeping an amount, you could add it when you insert a new data set or delete the value if you splice an item.
this.totals
is implemented as an object with the currency as key and the value as amount.
class Art {
constructor() {
this.values = Array();
this.totals = Object.create(null);
}
add(date, amount, currency, product) {
this.totals[currency] = this.totals[currency] || 0;
this.totals[currency] += amount;
this.values.push([date, amount, currency, product]); //.toString());
}
list() {
return this.values;
}
clear(date) {
var amount, currency;
for (let i = this.values.length - 1; i >= 0; --i) {
if (this.values[i][0] == date) {
[, amount, currency] = this.values.splice(i, 1)[0]
this.totals[currency] -= amount;
}
}
}
total() {
return this.totals;
}
}
const art = new Art();
art.add('2017-04-25', 2, 'USD', 'Jogurt');
art.add('2017-04-25', 3, 'USD', 'French fries');
art.add('2017-04-27', 4.75, 'USD', 'Beer');
art.clear('2017-04-27');
console.log(art.list());
console.log(art.total());
Upvotes: 2