Skip to content

Commit

Permalink
(yegor256#1475) Evaluate source once per AvgOf invocation
Browse files Browse the repository at this point in the history
  • Loading branch information
victornoel authored and Olivier B. OURA committed Jan 8, 2021
1 parent 019f965 commit 23372c2
Showing 1 changed file with 8 additions and 20 deletions.
28 changes: 8 additions & 20 deletions src/main/java/org/cactoos/scalar/AvgOf.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.List;
import org.cactoos.Scalar;
import org.cactoos.iterable.IterableOf;
import org.cactoos.iterable.Mapped;
import org.cactoos.list.ListOf;

/**
* Average of numbers.
Expand All @@ -50,16 +52,7 @@
* <p>There is no thread-safety guarantee.
*
* @since 0.24
* @checkstyle ExecutableStatementCountCheck (500 lines)
* @checkstyle NPathComplexityCheck (500 lines)
*/
@SuppressWarnings(
{
"PMD.CallSuperInConstructor",
"PMD.OnlyOneConstructorShouldDoInitialization",
"PMD.ConstructorOnlyInitializesOrCallOtherConstructors"
}
)
public final class AvgOf extends NumberEnvelope {

/**
Expand Down Expand Up @@ -136,22 +129,17 @@ public AvgOf(final Scalar<Number>... src) {
public AvgOf(final Iterable<Scalar<Number>> src) {
super(
new Ternary<>(
new LengthOf(src),
(Double len) -> len > 0,
len -> new Folded<BigDecimal, BigDecimal>(
new ScalarOf<>(() -> new ListOf<>(new Mapped<Number>(Scalar::value, src))),
(List<Number> list) -> !list.isEmpty(),
list -> new Folded<BigDecimal, BigDecimal>(
BigDecimal.ZERO,
(sum, value) -> sum.add(value, MathContext.DECIMAL128),
new Mapped<>(
number -> BigDecimal.valueOf(
number.value().doubleValue()
),
src
)
new Mapped<>(s -> new BigDecimal(s.doubleValue()), list)
).value().divide(
BigDecimal.valueOf(len),
BigDecimal.valueOf(list.size()),
MathContext.DECIMAL128
).doubleValue(),
len -> 0.0
list -> 0.0
)
);
}
Expand Down

0 comments on commit 23372c2

Please sign in to comment.