|
| 1 | +package currency; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.math.BigDecimal; |
| 5 | +import java.math.RoundingMode; |
| 6 | +import java.nio.file.Files; |
| 7 | +import java.nio.file.Path; |
| 8 | +import java.nio.file.Paths; |
| 9 | +import java.time.LocalDate; |
| 10 | +import java.util.Map; |
| 11 | +import java.util.stream.Collectors; |
| 12 | +import java.util.stream.Stream; |
| 13 | + |
| 14 | +/** |
| 15 | + * Created by mtumilowicz on 2019-05-15. |
| 16 | + * <p> |
| 17 | + * TO-DO |
| 18 | + */ |
| 19 | +public interface CurrencyConverter { |
| 20 | + |
| 21 | + BigDecimal convert(BigDecimal amount); |
| 22 | + |
| 23 | + interface BiFunction { |
| 24 | + BigDecimal convert(BigDecimal amount, String toCurrency); |
| 25 | + |
| 26 | + default CurrencyConverter to(String toCurrency) { |
| 27 | + return amount -> convert(amount, toCurrency); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + interface TriFunction { |
| 32 | + BigDecimal convert(BigDecimal amount, String fromCurrency, String toCurrency); |
| 33 | + |
| 34 | + default BiFunction from(String fromCurrency) { |
| 35 | + return (amount, toCurrency) -> convert(amount, fromCurrency, toCurrency); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + static TriFunction of(LocalDate date) { |
| 40 | + |
| 41 | + return (amount, fromCurrency, toCurrency) -> { |
| 42 | + |
| 43 | + Path path = Paths.get("src/main/resources/currency.txt"); |
| 44 | + try (Stream<String> lines = Files.lines(path)) { |
| 45 | + |
| 46 | + Map<String, BigDecimal> converterMap = |
| 47 | + lines.skip(1L) |
| 48 | + .collect( |
| 49 | + Collectors.toMap( |
| 50 | + line -> line.substring(0, 3), |
| 51 | + line -> new BigDecimal(line.substring(4)) |
| 52 | + ) |
| 53 | + ); |
| 54 | + |
| 55 | + return amount.multiply(converterMap.get(toCurrency).divide(converterMap.get(fromCurrency), |
| 56 | + RoundingMode.DOWN)); |
| 57 | + |
| 58 | + } catch (IOException e) { |
| 59 | + e.printStackTrace(); |
| 60 | + } |
| 61 | + |
| 62 | + return null; |
| 63 | + }; |
| 64 | + } |
| 65 | + |
| 66 | + static void main(String[] args) { |
| 67 | + System.out.println(CurrencyConverter.of(LocalDate.of(2018, 11, 5)) |
| 68 | + .from("EUR") |
| 69 | + .to("GBP").convert(BigDecimal.valueOf(1000))); |
| 70 | + } |
| 71 | +} |
0 commit comments