Allow indexOf to work with Codec eq (#699)

* Allow indexOf to work with Codec eq

* Convert to type before check

* Swap compare (in case of empty/invalid values)
This commit is contained in:
Jaco Greeff
2019-02-15 10:52:00 +01:00
committed by GitHub
parent 2c80e90f90
commit 15b22dab1c
9 changed files with 53 additions and 26 deletions
+2 -2
View File
@@ -30,8 +30,8 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": {
"@babel/runtime": "^7.2.0",
"@polkadot/keyring": "^0.34.9",
"@polkadot/util": "^0.34.9",
"@polkadot/keyring": "^0.34.10",
"@polkadot/util": "^0.34.10",
"core-js": "^2.6.2"
}
}
+9
View File
@@ -127,5 +127,14 @@ describe('Vector', () => {
it('compares against codec + primitive types', () => {
expect(vec.eq(['123', new Text('456')])).toBe(true);
});
it('finds the index of an value', () => {
const myId = '5GfWeNe33QeyzVMV2uENuvSXLVfVXCiuLvfEP6WCDHADZhen';
const vec = new Vector(AccountId, [
'5H4787dXL43BaA6PvTwUTyA38JBbfC9r8QyK3ay8Nozc2Ta3', '5GeJHN5EcUGPoa5pUwYkXjymoDVN1DJHsBR4UGX4XRAwKBVk', '5Dn8F1SUX6SoLt1BTfKEPL5VY9wMvG1A6tEJTSCHpLsinThm', '5DPW1n4q2THUjKGj3QKkcqdh6oxY1bmLsSQ7t8FuiuNtRoUc', '5E8k3u7iRysqPPYsBK1UgetCquZznwRZxryTzynkDTzg3vNy', '5DteAmjoppNJ8rrBugKctCXM82UVWZSCHeU8pqFwQBbyAWyB', '5GfWeNe33QeyzVMV2uENuvSXLVfVXCiuLvfEP6WCDHADZhen'
]);
expect(vec.indexOf(myId)).toEqual(6);
});
});
});
+18
View File
@@ -81,6 +81,24 @@ export default class Vector<
return compareArray(this, other);
}
/**
* @description Finds the index of the value in the array
*/
indexOf (_other?: any): number {
// convert type first, this removes overhead from the eq
const other = _other instanceof this._Type
? _other
: new this._Type(_other);
for (let i = 0; i < this.length; i++) {
if (other.eq(this[i])) {
return i;
}
}
return -1;
}
/**
* @description Converts the Object to an standard JavaScript Array
*/