fentastic
Version:
Validate and parse Forsyth-Edwards Notation (FEN) used to describe a chess game board position.
49 lines (48 loc) • 1.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateWhiteSpace = exports.correctWhiteSpace = exports.isWhiteSpace = void 0;
const token_js_1 = require("./token.js");
const ParseError_js_1 = require("./ParseError.js");
exports.isWhiteSpace = (0, token_js_1.tokenIs)(/ /);
const isAnyWhiteSpace = (0, token_js_1.tokenIs)(/\s/);
const prefix = 'Whitespace';
// Collapses string of white spaces into a single white space
const collapseWhiteSpace = (tokens) => {
return tokens.filter(((token, i) => (!isAnyWhiteSpace(token) || !tokens[i - 1] || !isAnyWhiteSpace(tokens[i - 1]))));
};
const forEachWsToken = (tokens, fn) => {
tokens.filter(isAnyWhiteSpace).forEach(fn);
};
const correctWhiteSpace = (tokens) => {
tokens = collapseWhiteSpace(tokens);
if (isAnyWhiteSpace(tokens[0])) {
tokens.shift();
}
if (isAnyWhiteSpace(tokens.at(-1))) {
tokens.pop();
}
forEachWsToken(tokens, (t) => {
t.value = ' ';
});
return tokens;
};
exports.correctWhiteSpace = correctWhiteSpace;
const validateWhiteSpace = (tokens) => {
if (isAnyWhiteSpace(tokens[0])) {
throw new ParseError_js_1.ParseError(prefix, tokens[0].value, 0);
}
const repeatedWsToken = tokens.find((token, i, tokens) => (isAnyWhiteSpace(token) && tokens[i - 1] && isAnyWhiteSpace(tokens[i - 1])));
if (repeatedWsToken) {
throw new ParseError_js_1.ParseError(prefix, repeatedWsToken.value, repeatedWsToken.index);
}
if (isAnyWhiteSpace(tokens.at(-1))) {
throw new ParseError_js_1.ParseError(prefix, tokens.at(-1).value, tokens.at(-1).index);
}
forEachWsToken(tokens, (t) => {
if (!(0, exports.isWhiteSpace)(t)) {
throw new ParseError_js_1.ParseError(prefix, t.value, t.index, ' ', 'ASCII space');
}
});
return tokens;
};
exports.validateWhiteSpace = validateWhiteSpace;