Skip to content

Commit dbbf4d4

Browse files
committed
feat(*): add and() function that acts as a && operator for controls
1 parent f071c99 commit dbbf4d4

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

src/core/and.spec.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { expect } from 'chai'
2+
import * as Mocha from 'mocha'
3+
import { and } from './and'
4+
import { Control } from './control'
5+
6+
describe('The `and()` chaining function', () => {
7+
8+
const controlA: Control<boolean> = {
9+
label: '[A]',
10+
icons: ['a'],
11+
query: () => false,
12+
}
13+
14+
const controlB: Control<boolean> = {
15+
label: '[B]',
16+
icons: ['b'],
17+
query: () => true,
18+
}
19+
20+
const control = and(controlA, controlB)
21+
22+
it('correctly combines labels', () => {
23+
expect(control.label).to.equal('[A] + [B]')
24+
})
25+
26+
it('correctly combines icons', () => {
27+
expect(control.icons).to.deep.equal(['a', 'plus', 'b'])
28+
})
29+
30+
it('makes the combined query work as expected', () => {
31+
expect(control.query()).to.equal(false)
32+
})
33+
34+
it('throws an error when less than two controls are specified', () => {
35+
expect(() => and(controlA)).to.throw(Error, 'Less than two controls specified!')
36+
})
37+
38+
})

src/core/and.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { Control } from './control'
2+
3+
export function and(...controls: Array<Control<boolean>>): Control<boolean> {
4+
if (controls.length < 2) throw new Error('Less than two controls specified!')
5+
6+
return {
7+
label: controls.map(control => control.label).join(' + '),
8+
icons: [].concat(...controls.map(control => control.icons)).join('?plus?').split('?'),
9+
query: () => {
10+
for (const control of controls) {
11+
/* istanbul ignore else */
12+
if (!control.query()) return false
13+
}
14+
/* istanbul ignore next */
15+
return true
16+
},
17+
}
18+
}

src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
export { Mouse } from './inputs/mouse'
22
export { Keyboard } from './inputs/keyboard'
33
export { Gamepad } from './inputs/gamepad'
4+
5+
export { and } from './core/and'

0 commit comments

Comments
 (0)