Repository navigation
Expand file tree
/
Copy pathencode.js
More file actions
109 lines (98 loc) · 2.32 KB
/
Copy pathencode.js
File metadata and controls
109 lines (98 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
'use strict';
const path = require('path');
/** @typedef {number} Card52 Deck id 0..51: rank*4+suit (rank 0=2..12=A, suit 0=c..3=s). */
/** @returns {import('./index.js')} */
function nativeAddon() {
return require('node-gyp-build')(path.join(__dirname));
}
const RANKS = '23456789TJQKA';
const SUITS = 'cdhs';
/**
* @param {string} s
* @returns {Card52}
*/
function cardStringToDeckIndex(s) {
const raw = String(s).trim();
if (!raw) {
throw new Error('invalid card string');
}
let rank = -1;
let i = 0;
if (raw.length >= 3 && raw[0] === '1' && raw[1] === '0') {
rank = 8;
i = 2;
} else if (raw.length >= 2) {
const r = raw[0].toUpperCase();
const idx = RANKS.indexOf(r);
if (idx >= 0) {
rank = idx;
}
i = 1;
}
if (rank < 0 || i >= raw.length) {
throw new Error(`invalid card string: ${s}`);
}
const su = raw[i].toLowerCase();
const suit = SUITS.indexOf(su);
if (suit < 0) {
throw new Error(`invalid card string: ${s}`);
}
return rank * 4 + suit;
}
/**
* @param {Card52} idx
* @returns {string}
*/
function deckIndexToCardString(idx) {
if (!Number.isInteger(idx) || idx < 0 || idx > 51) {
throw new Error('deck index must be integer 0..51');
}
const rank = Math.floor(idx / 4);
const suit = idx % 4;
return RANKS[rank] + SUITS[suit];
}
/**
* @param {string[]} strings
* @returns {Uint8Array}
*/
function packCards(strings) {
const out = new Uint8Array(strings.length);
for (let i = 0; i < strings.length; i++) {
out[i] = cardStringToDeckIndex(strings[i]);
}
return out;
}
/**
* @param {Uint8Array} packed
* @returns {string[]}
*/
function unpackCards(packed) {
const out = new Array(packed.length);
for (let i = 0; i < packed.length; i++) {
out[i] = deckIndexToCardString(packed[i]);
}
return out;
}
/**
* PKST packed binary state (native `encodePokerState`).
* @param {import('./index').NativePokerState} state
* @returns {Uint8Array}
*/
function packPokerState(state) {
return nativeAddon().encodePokerState(state);
}
/**
* @param {Uint8Array} bytes
* @returns {import('./index').NativePokerState}
*/
function unpackPokerState(bytes) {
return nativeAddon().decodePokerState(bytes);
}
module.exports = {
cardStringToDeckIndex,
deckIndexToCardString,
packCards,
unpackCards,
packPokerState,
unpackPokerState,
};