Consider the following situation:
items = [
{
id: 1
attributes: [
{ key: a, value: 2 }
{ key: b, value: 3 }
],
requirements: null
}
{
id: 2
attributes: [
{ key: b, value: 2 }
],
requirements: a > 2
}
{
id: 3
attributes: [
{ key: a, value: 1 }
{ key: c, value: 1 }
],
requirements: a > 1 and b > 2
}
{
id: 4
attributes: [
{ key: a, value: 2 }
{ key: d, value: 7 }
],
requirements: b > 5 and h < 10
}
]
The expected result, adding together (sum) the various attributes is:
result = [
{ key: a, value: 3 }
{ key: b, value: 5 }
{ key: c, value: 1 }
]
As you can observe, there are dependencies (requirements) between objects in the list. In particular, the object with id: 4 (last one of the series) is discarded from the calculation since the condition b > 5 and h < 10 is never checked. On the contrary, the object with id: 2, initially discarded, then falls in the calculation as a result of the object with id: 3 (which, by adding 1 to the attribute a, makes true the condition a > 2).
What is the algorithm needed to obtain the required result having N objects?
Disclaimer: the proposed structure is only an example. You can suggest any changes you believe to achieve the result. I’m working in JavaScript (CoffeeScript) programming language, but any other will be okay.
Let’s start by getting the data in a format we can use. We need to be able to test requirements at will, instead of only when the data object is instantiated:
While we’re at it, let’s get the attributes in a more useful state (note that this isn’t strictly necessary, but makes everything simpler):
Now I’ll go through the naive algorithm, which is simplest and should fit your needs. Essentially, we’ll keep looping over the data set, testing each one that hasn’t been used yet and adding it to the sum if it passes.
I’ll let you fill in the
addandinitfunctions. Theaddone should be simple; it adds each element in the second parameter to each element in the first. Theinitneeds to set each element insumthat may be used (tested or added to) to0.