Ingredient.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package org.leumasjaffe.recipe.model;
  2. import org.leumasjaffe.container.Either;
  3. import com.fasterxml.jackson.annotation.JsonIgnore;
  4. import com.fasterxml.jackson.annotation.JsonProperty;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import lombok.Getter;
  8. @Data @AllArgsConstructor
  9. public class Ingredient {
  10. @AllArgsConstructor @Getter
  11. public static enum Volume {
  12. ml("ml", 1),
  13. tsp("tsp", 5),
  14. Tbsp("Tbsp", 15),
  15. cup("cup", 240);
  16. final String displayName;
  17. final double atomicUnits;
  18. }
  19. @AllArgsConstructor @Getter
  20. public static enum Weight {
  21. g("g", 1),
  22. oz("oz", 28.3495),
  23. lb("lb", 453.592),
  24. kg("kg", 1000),
  25. pinch("pinch", 0.36),
  26. dash("dash", 0.72);
  27. final String displayName;
  28. final double atomicUnits;
  29. }
  30. String name;
  31. double value = 0;
  32. @JsonIgnore Either<Volume, Weight> measure;
  33. Ingredient plus(final Ingredient rhs) {
  34. if (!name.equals(rhs.name)) {
  35. throw new IllegalArgumentException("Combining ingredients of differing types");
  36. } else if (measure.getState() != rhs.measure.getState()) {
  37. throw new IllegalArgumentException("Cannot merge mass and volume together");
  38. }
  39. return new Ingredient(name, value + (rhs.value * conversionRatio(rhs.measure)), measure);
  40. }
  41. private double conversionRatio(Either<Volume, Weight> rhs) {
  42. return units(rhs) / units(measure);
  43. }
  44. private static double units(Either<Volume, Weight> measure) {
  45. return measure.unify(Volume::getAtomicUnits, Weight::getAtomicUnits);
  46. }
  47. @JsonProperty("unit")
  48. private String[] measureToString() {
  49. String[] rval = {null, null};
  50. return rval;
  51. }
  52. @JsonProperty("unit")
  53. private void measureFromString(String[] s) {
  54. if (s[0] != null) {
  55. measure = Either.ofLeft(Volume.valueOf(s[0]));
  56. } else if (s[1] != null) {
  57. measure = Either.ofRight(Weight.valueOf(s[1]));
  58. }
  59. }
  60. }