Answer the question
In order to leave comments, you need to log in
SOLID Single responsibility - should I write a separate class in this case?
The goal is to calculate the sum of all two values of keys a and b in an object that are in an array, but also be able to calculate the sum for only one object.
const data = [{"id": 1, "a": 99, "b": 100}, {"id": 2, "a": 1 "b": 2}];
const oneEl = {"id": 3, "a": 2, "b": 10};
class Calc {
calcAmount (obj) {
const {a, b} = obj;
return a + b;
}
calcAmountOfArray(data) {
let sum = 0;
data.forEach((item) => {
sum += this.calcAmount(item);
});
return sum;
}
}
Answer the question
In order to leave comments, you need to log in
Well, let's start with the fact that you don't need a class here at all. Because there is no data in the Calc class, only methods. Here are the functions you need, not the class.
There is no need to invent and come up with something related to these principles, they are very abstract. Even the author of SOLID himself changed shoes a hundred times what he meant by this S.
A simple function
arrayAmount(data) {
let sum = 0;
data.forEach((item) => {
const {a, b} = item;
sum += a + b;
});
return sum;
}
calcAmount
by SOLID must be a method on an object with these keys.
Those. let's say it came from the server
const data = [{"id": 1, "a": 99, "b": 100}, {"id": 2, "a": 1 "b": 2}];
interface Calculable {
calcAmount(): number;
}
class CalculableAB implements Calculable {
constructor(obj) {
Object.assign(this, obj);
}
calcAmount() {
const {a, b} = this;
return a + b;
}
}
struct = data.map(obj => new CalculableAB(obj));
Calculable
you simply call from him calcAmount()
. How it is implemented there - you do not care. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question