Skip to content

Commit

Permalink
feat: new hasChanged method (#202)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Mar 3, 2022
1 parent cd74ea2 commit 5f2dba7
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Expand Up @@ -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`.
Expand Down
5 changes: 5 additions & 0 deletions index.d.ts
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions src/MagicString.js
Expand Up @@ -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') {
Expand Down
20 changes: 20 additions & 0 deletions test/MagicString.js
Expand Up @@ -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';
Expand Down

0 comments on commit 5f2dba7

Please sign in to comment.