Skip to content

Commit

Permalink
feat: add fenced code block for md string class
Browse files Browse the repository at this point in the history
  • Loading branch information
syroegkin committed Dec 10, 2024
1 parent 8e25ade commit 04ec0d0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/lib/markdown/mdstring.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,37 @@ describe('MDstring', () => {
const s2 = MDstring.string('');
expect(s2.concat(b).concat(s).get()).to.be.equal(`${b}${a}${b}`);
});
describe('codeBlock', () => {
it('should wrap the existing string in a code block without language', () => {
const mdString = new MDstring('console.log("Hello, World!");');
mdString.codeBlock();
expect(mdString.get()).to.be.equal('```\nconsole.log("Hello, World!");\n```');
});

it('should wrap the existing string in a code block with specified language', () => {
const mdString = new MDstring('console.log("Hello, World!");');
mdString.codeBlock('javascript');
expect(mdString.get()).to.be.equal('```javascript\nconsole.log("Hello, World!");\n```');
});

it('should not modify an empty string', () => {
const mdString = new MDstring();
mdString.codeBlock('python');
expect(mdString.get()).to.be.equal('');
});

it('should handle multi-line code blocks', () => {
const mdString = new MDstring('const x = 1;\nconst y = 2;\nconsole.log(x + y);');
mdString.codeBlock('javascript');
expect(mdString.get()).to.be.equal(
'```javascript\nconst x = 1;\nconst y = 2;\nconsole.log(x + y);\n```',
);
});

it('should return the MDstring instance for method chaining', () => {
const mdString = new MDstring('Hello, World!');
const result = mdString.codeBlock();
expect(result).to.be.deep.equal(mdString);
});
});
});
11 changes: 11 additions & 0 deletions src/lib/markdown/mdstring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,17 @@ export class MDstring {
return this;
}

public codeBlock(language = ''): MDstring {
if (this._string !== '') {
this.set(
`\`\`\`${language}
${this._string}
\`\`\``,
);
}
return this;
}

public escape(): MDstring {
this.set(`${textEscape(this._string)}`);
return this;
Expand Down

0 comments on commit 04ec0d0

Please sign in to comment.