All Downloads are FREE. Search and download functionalities are using the official Maven repository.

co.easimart.EasimartIncrementOperation Maven / Gradle / Ivy

package co.easimart;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * An operation that increases a numeric field's value by a given amount.
 */
/** package */ class EasimartIncrementOperation implements EasimartFieldOperation {
  private final Number amount;

  public EasimartIncrementOperation(Number amount) {
    this.amount = amount;
  }

  @Override
  public JSONObject encode(EasimartEncoder objectEncoder) throws JSONException {
    JSONObject output = new JSONObject();
    output.put("__op", "Increment");
    output.put("amount", amount);
    return output;
  }

  @Override
  public EasimartFieldOperation mergeWithPrevious(EasimartFieldOperation previous) {
    if (previous == null) {
      return this;
    } else if (previous instanceof EasimartDeleteOperation) {
      return new EasimartSetOperation(amount);
    } else if (previous instanceof EasimartSetOperation) {
      Object oldValue = ((EasimartSetOperation) previous).getValue();
      if (oldValue instanceof Number) {
        return new EasimartSetOperation(Numbers.add((Number) oldValue, amount));
      } else {
        throw new IllegalArgumentException("You cannot increment a non-number.");
      }
    } else if (previous instanceof EasimartIncrementOperation) {
      Number oldAmount = ((EasimartIncrementOperation) previous).amount;
      return new EasimartIncrementOperation(Numbers.add(oldAmount, amount));
    } else {
      throw new IllegalArgumentException("Operation is invalid after previous operation.");
    }
  }

  @Override
  public Object apply(Object oldValue, String key) {
    if (oldValue == null) {
      return amount;
    } else if (oldValue instanceof Number) {
      return Numbers.add((Number) oldValue, amount);
    } else {
      throw new IllegalArgumentException("You cannot increment a non-number.");
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy