From 5f2dba72774c444538ed10aa5f2096104cb0b4bb Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Thu, 3 Mar 2022 15:58:06 +0800 Subject: [PATCH] feat: new `hasChanged` method (#202) --- README.md | 4 ++++ index.d.ts | 5 +++++ src/MagicString.js | 4 ++++ test/MagicString.js | 20 ++++++++++++++++++++ 4 files changed, 33 insertions(+) diff --git a/README.md b/README.md index e7e1eef..1f12867 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,10 @@ The returned sourcemap has two (non-enumerable) methods attached for convenience code += '\n//# sourceMappingURL=' + map.toUrl(); ``` +### s.hasChanged() + +Indicates if the string has been changed. + ### s.indent( prefix[, options] ) Prefixes each line of the string with `prefix`. If `prefix` is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. Returns `this`. diff --git a/index.d.ts b/index.d.ts index fd62cd8..0dca468 100644 --- a/index.d.ts +++ b/index.d.ts @@ -217,6 +217,11 @@ export default class MagicString { isEmpty(): boolean; length(): number; + /** + * Indicates if the string has been changed. + */ + hasChanged(): boolean; + original: string; /** * Returns the generated string. diff --git a/src/MagicString.js b/src/MagicString.js index 6632043..b67bf18 100644 --- a/src/MagicString.js +++ b/src/MagicString.js @@ -713,6 +713,10 @@ export default class MagicString { return this; } + hasChanged() { + return this.original !== this.toString(); + } + replace(searchValue, replacement) { function getReplacement(match) { if (typeof replacement === 'string') { diff --git a/test/MagicString.js b/test/MagicString.js index a97f157..25472ff 100644 --- a/test/MagicString.js +++ b/test/MagicString.js @@ -1278,6 +1278,26 @@ describe('MagicString', () => { }); }); + describe('hasChanged', () => { + it('should works', () => { + const s = new MagicString(' abcde fghijkl '); + + assert.ok(!s.hasChanged()); + + assert.ok(s.clone().prepend(' ').hasChanged()); + assert.ok(s.clone().overwrite(1, 2, 'b').hasChanged()); + assert.ok(s.clone().remove(1, 6).hasChanged()); + + s.trim(); + + assert.ok(s.hasChanged()); + + const clone = s.clone(); + + assert.ok(clone.hasChanged()); + }); + }); + describe('replace', () => { it('works with string replace', () => { const code = '1 2 1 2';