Update Enum .eq to be more exhaustive (#1455)
* Update Enum .eq to be more exhaustive * Add basic compare test
This commit is contained in:
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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));
|
||||
|
||||
Reference in New Issue
Block a user