Skip to content

Commit a418c51

Browse files
committed
Accepts more general data as results, maps unrecognized values as "-".
1 parent d86bc2c commit a418c51

File tree

1 file changed

+45
-7
lines changed

1 file changed

+45
-7
lines changed

source/npm/qsharp/ux/histogram.tsx

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,18 +67,56 @@ function getDefaultMenuSelection(
6767
return selection;
6868
}
6969

70-
const reKetResult = /^\[(?:(Zero|One|Loss), *)*(Zero|One|Loss)\]$/;
70+
// Matches a simple, single-level, bracketed CSV list with no empty elements, e.g.:
71+
// [Zero, One, Loss]
72+
// [0, 1, .]
73+
// [missing qubit, one, zero, result unknown]
74+
//
75+
// Tokens may be arbitrary strings so long as they don't include ',', '[' or ']'.
76+
// Empty values such as "[,,,]" or "[Zero,,One]" are rejected.
77+
//
78+
79+
// A word is any non-whitespace, non-comma, non-bracket sequence
80+
const ketCsvWord = "[^\\s,\\[\\]]+";
81+
82+
// A value is one or more words separated by whitespace
83+
const ketCsvValue = `\\s*(?:${ketCsvWord}\\s*)+`;
84+
85+
// The body is one or more values separated by commas and surrounded by brackets
86+
const ketCsvBody = `\\[(?:${ketCsvValue},)*${ketCsvValue}\\]`;
87+
88+
const reKetResult = new RegExp(`^\\s*${ketCsvBody}\\s*$`);
7189
function resultToKet(result: string): string {
7290
if (typeof result !== "string") return "ERROR";
7391

7492
if (reKetResult.test(result)) {
75-
// The result is a simple array of Zero and One
76-
// The below will return an array of "Zero" or "One" in the order found
77-
const matches = result.match(/(One|Zero|Loss)/g);
93+
// The result is a simple, bracketed CSV list. Convert each token to a ket digit:
94+
// Zero/0 -> 0
95+
// One/1 -> 1
96+
// else -> -
97+
const inner = result.trim().slice(1, -1).trim();
98+
const tokens = inner.length ? inner.split(",") : [];
99+
78100
let ket = "|";
79-
matches?.forEach(
80-
(digit) => (ket += digit == "One" ? "1" : digit == "Zero" ? "0" : "-"),
81-
);
101+
for (const token of tokens) {
102+
const trimmed = token.trim();
103+
const unquoted = trimmed
104+
.replace(/^"(.*)"$/, "$1")
105+
.replace(/^'(.*)'$/, "$1")
106+
.trim();
107+
108+
// If any element is empty after trimming/unquoting, don't treat it as a ket label.
109+
if (unquoted.length === 0) return result;
110+
111+
const normalized = unquoted.toLowerCase();
112+
113+
ket +=
114+
normalized === "zero" || normalized === "0"
115+
? "0"
116+
: normalized === "one" || normalized === "1"
117+
? "1"
118+
: "-";
119+
}
82120
ket += "⟩";
83121
return ket;
84122
} else {

0 commit comments

Comments
 (0)