Update Enum .eq to be more exhaustive (#1455)

* Update Enum .eq to be more exhaustive

* Add basic compare test
This commit is contained in:
Jaco Greeff
2019-10-07 15:31:05 +02:00
committed by GitHub
parent eaa71e0097
commit fb7e067737
4 changed files with 41 additions and 14 deletions
+27 -10
View File
@@ -4,6 +4,8 @@
import '../injector';
import { u8aToHex } from '@polkadot/util';
import Enum from './Enum';
import Null from '../primitive/Null';
import Text from '../primitive/Text';
@@ -133,21 +135,36 @@ describe('Enum', (): void => {
});
describe('utils', (): void => {
const eqtest = new Enum(
{ U32, Text },
new Uint8Array([1, 3 << 2, 88, 89, 90])
);
const DEF = { num: U32, str: Text };
const u8a = new Uint8Array([1, 3 << 2, 88, 89, 90]);
const test = new Enum(DEF, u8a);
it('compares against index', (): void => {
expect(
eqtest.eq(1)
).toBe(true);
expect(test.eq(1)).toBe(true);
});
it('compares against u8a', (): void => {
expect(test.eq(u8a)).toBe(true);
});
it('compares against hex', (): void => {
expect(test.eq(u8aToHex(u8a))).toBe(true);
});
it('compares against another enum', (): void => {
expect(test.eq(new Enum(DEF, u8a))).toBe(true);
});
it('compares against another object', (): void => {
expect(test.eq({ str: 'XYZ' })).toBe(true);
});
it('compares against values', (): void => {
expect(
eqtest.eq('XYZ')
).toBe(true);
expect(test.eq('XYZ')).toBe(true);
});
it('compares basic enum on string', (): void => {
expect(new Enum(['A', 'B', 'C'], 1).eq('B')).toBe(true);
});
});
});
+8
View File
@@ -218,6 +218,14 @@ export default class Enum extends Base<Codec> {
return this.toNumber() === other;
} else if (this._isBasic && isString(other)) {
return this.type === other;
} else if (isU8a(other)) {
return !this.toU8a().some((entry, index): boolean => entry !== other[index]);
} else if (isHex(other)) {
return this.toHex() === other;
} else if (other instanceof Enum) {
return this.index === other.index && this.value.eq(other.value);
} else if (isObject(other)) {
return this.value.eq(other[this.type]);
}
// compare the actual wrapper value
+2 -3
View File
@@ -72,9 +72,8 @@ export default class U8a extends Uint8Array implements Codec {
*/
public eq (other?: any): boolean {
if (other instanceof Uint8Array) {
return (this.length === other.length) && isUndefined(
this.find((value, index): boolean => value !== other[index])
);
return (this.length === other.length) &&
!this.some((value, index): boolean => value !== other[index]);
}
return this.eq(U8a.decodeU8a(other));