Added the subtract method to the AssetAmount class

master
Nelson R. Perez 2017-02-23 19:53:02 -05:00
parent 93dd6ef1b2
commit 60dabfef31
2 changed files with 49 additions and 0 deletions

View File

@ -54,6 +54,25 @@ public class AssetAmount implements ByteSerializable, JsonSerializable {
return new AssetAmount(combined, asset);
}
/**
* Subtracts another instance of AssetAmount from this one. This method will always
* return absolute values.
* @param other: The other asset amount to subtract from this.
* @return: The absolute value of the subtraction of the other minus this asset amount.
*/
public AssetAmount subtract(AssetAmount other){
if(!this.getAsset().getObjectId().equals(other.getAsset().getObjectId())){
throw new IncompatibleOperation("Cannot subtract two AssetAmount instances that refer to different assets");
}
UnsignedLong result = null;
if(this.amount.compareTo(other.getAmount()) < 0){
result = other.getAmount().minus(this.amount);
}else{
result = this.amount.minus(other.getAmount());
}
return new AssetAmount(result, asset);
}
public void setAmount(UnsignedLong amount){
this.amount = amount;
}

View File

@ -0,0 +1,30 @@
package de.bitsharesmunich.graphenej;
import com.google.common.primitives.UnsignedLong;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by nelson on 2/23/17.
*/
public class AssetAmountTest {
private final int LARGE_VALUE = 1000;
private final int SMALL_VALUE = 500;
private AssetAmount large;
private AssetAmount small;
private Asset testAsset = new Asset("1.3.0");
@Before
public void setUp(){
large = new AssetAmount(UnsignedLong.valueOf(LARGE_VALUE), testAsset);
small = new AssetAmount(UnsignedLong.valueOf(SMALL_VALUE), testAsset);
}
@Test
public void testSubtraction(){
assertEquals(large.subtract(small).getAmount(), new AssetAmount(UnsignedLong.valueOf(LARGE_VALUE - SMALL_VALUE), testAsset).getAmount());
assertEquals(small.subtract(large).getAmount(), new AssetAmount(UnsignedLong.valueOf(Math.abs(SMALL_VALUE - LARGE_VALUE)), testAsset).getAmount());
}
}