Skip to content

Commit

Permalink
Support negative collection index in spec
Browse files Browse the repository at this point in the history
  • Loading branch information
leeonky committed Oct 17, 2023
1 parent a21c7c9 commit 050a0b6
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,21 @@ protected C produce() {
@Override
public Optional<Producer<?>> child(String property) {
int index = valueOf(property);
if (index < 0)
index = children.size() + index;
index = transformNegativeIndex(index);
return Optional.ofNullable(index < children.size() ? children.get(index) : null);
}

@Override
public void setChild(String property, Producer<?> producer) {
int index = valueOf(property);
fillCollectionWithDefaultValue(index);
children.set(transformNegativeIndex(index), producer);
}

private int transformNegativeIndex(int index) {
if (index < 0)
index = children.size() + index;
children.set(index, producer);
return index;
}

public int fillCollectionWithDefaultValue(int index) {
Expand All @@ -69,7 +72,7 @@ public int fillCollectionWithDefaultValue(int index) {
public Producer<?> childOrDefault(String property) {
int index = valueOf(property);
fillCollectionWithDefaultValue(index);
return children.get(index);
return children.get(transformNegativeIndex(index));
}

@Override
Expand Down
34 changes: 33 additions & 1 deletion src/test/resources/features/4-spec-property.feature
Original file line number Diff line number Diff line change
Expand Up @@ -899,6 +899,38 @@ Feature: define spec
]
"""

Scenario: support negative index in spec
Given the following bean class:
"""
public class Bean {
public String value;
public Bean setValue(String v) {
this.value = v;
return this;
}
}
"""
And the following bean class:
"""
public class Beans {
public Bean[] beans;
}
"""
When register:
"""
jFactory.factory(Beans.class).spec(instance -> instance.spec()
.property("beans[0]").value(new Bean().setValue("world"))
.property("beans[-2]").value(new Bean().setValue("hello")));
"""
When build:
"""
jFactory.create(Beans.class);
"""
Then the result should:
"""
beans.value[]= [hello world]
"""

# Scenario: collection element property should override collection spec
Scenario: to be implement
Given the following bean class:
Expand Down Expand Up @@ -935,7 +967,7 @@ Feature: define spec
"""
class.simpleName: IllegalArgumentException
"""
# TODO
# TODO ?
# Then the result should:
# """
# beans.value[]: [ hello ]
Expand Down

0 comments on commit 050a0b6

Please sign in to comment.