From 96624a6d66445039f3a451d37ad1cada862d7c1c Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Mon, 11 Feb 2019 12:52:15 +0100 Subject: [PATCH] Allow boolean decoding for Vote constructor (#677) --- packages/types/src/Vote.ts | 29 +++++++++++++++++++++++++++++ packages/types/src/Votes.spec.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 packages/types/src/Votes.spec.ts diff --git a/packages/types/src/Vote.ts b/packages/types/src/Vote.ts index f277825d0c..538ea3f130 100644 --- a/packages/types/src/Vote.ts +++ b/packages/types/src/Vote.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import { isBoolean } from '@polkadot/util'; + import I8 from './I8'; /** @@ -10,4 +12,31 @@ import I8 from './I8'; * A number of lock periods, plus a vote, one way or the other. */ export default class Vote extends I8 { + constructor (value?: any) { + super(Vote.decodeVote(value)); + } + + private static decodeVote (value?: any): any { + if (isBoolean(value)) { + return value ? -1 : 0; + } else if (value instanceof Boolean) { + return Vote.decodeVote(value.valueOf()); + } + + return value; + } + + /** + * @description true is the wrapped value is a positive vote + */ + get isAye (): boolean { + return this.ltn(0); + } + + /** + * @description true is the wrapped value is a negative vote + */ + get isNay (): boolean { + return !this.isAye; + } } diff --git a/packages/types/src/Votes.spec.ts b/packages/types/src/Votes.spec.ts new file mode 100644 index 0000000000..7db8ea6849 --- /dev/null +++ b/packages/types/src/Votes.spec.ts @@ -0,0 +1,31 @@ +// Copyright 2017-2019 @polkadot/types authors & contributors +// This software may be modified and distributed under the terms +// of the Apache-2.0 license. See the LICENSE file for details. + +import Vote from './Vote'; + +describe('Vote', () => { + it('constructs via boolean true', () => { + expect(new Vote(true).toNumber()).toEqual(-1); + }); + + it('constructs via boolean false', () => { + expect(new Vote(false).toNumber()).toEqual(0); + }); + + it('has isYay for positive', () => { + expect(new Vote(new Boolean(true)).isAye).toBe(true); + }); + + it('has isYay for negative', () => { + expect(new Vote(new Boolean(false)).isNay).toBe(true); + }); + + it('is positive for negative numbers', () => { + expect(new Vote(-999).isAye).toBe(true); + }); + + it('is negative for positive numbers', () => { + expect(new Vote(999).isNay).toBe(true); + }); +});