Skip to content

Instantly share code, notes, and snippets.

@confused-Techie
Created August 2, 2023 23:32
Show Gist options
  • Save confused-Techie/37e177deae3a04c95f3fdf634a4d0323 to your computer and use it in GitHub Desktop.
Save confused-Techie/37e177deae3a04c95f3fdf634a4d0323 to your computer and use it in GitHub Desktop.
Convert tokens from Pulsar/Atom Spec into JS Spec expectations
/**
* Converts a 'tokens' array into a spec that can be dropped into your spec file.
* Assuming a setup with the following:
* `let { tokens } = grammar.tokenizeLine("your test text here"); const convert = require("convert-tokens-to-spec.js"); convert(tokens);`
*/
module.exports =
function convertTokensToSpec(tokens) {
let textOutput = "";
for (let i = 0; i < tokens.length; i++) {
let scopes = tokens[i].scopes;
let scopeArrayText = [];
scopes.forEach((element) => {
scopeArrayText.push(`"${element}"`);
});
let scopeText = scopeArrayText.join(", ");
let value;
if (tokens[i].value === '"') {
value = `'"'`;
} else if (tokens[i].value === "\n") {
value = `"\\n"`;
} else if (tokens[i].value.includes("\n")) {
value = `"\\n${tokens[i].value.replace("\n", "")}"`;
} else {
value = `"${tokens[i].value}"`;
}
textOutput +=
`\nexpect(tokens[${i}]).toEqual({\n value: ${value},\n scopes: [ ${scopeText} ]\n});\n`;
}
const fs = require("fs");
fs.writeFileSync("spec-example.js", textOutput, { encoding: "utf8" });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment