Skip to content
This repository was archived by the owner on Aug 5, 2024. It is now read-only.

JavaScript: Diff is not iterable #39

Open
JackuB opened this issue Sep 3, 2018 · 3 comments · Fixed by dmsnell/diff-match-patch#9
Open

JavaScript: Diff is not iterable #39

JackuB opened this issue Sep 3, 2018 · 3 comments · Fixed by dmsnell/diff-match-patch#9

Comments

@JackuB
Copy link

JackuB commented Sep 3, 2018

There was a change in JS version cd60d24#diff-5270d640a6c9c1b0590326b029d71ec8R76 from plain Array to a diff_match_patch.Diff Object that's trying to emulate Array.

The new object is not iterable, which messes up for example with Array destructing:

const a = dmp.diff_main('abc', 'ab123c', false);
const [eq, str] = a[0]; // => Uncaught TypeError: a[0] is not iterable
  1. was this change necessary? Tested that plain array works just fine with current version
  2. To really emulate array here, adding [Symbol.iterator] would do the trick, but its browser support is questionable
@bebbi
Copy link

bebbi commented Sep 19, 2018

@NeilFraser A quick comment on whether the new JS API behaviour which breaks Array destructuring is intentional or whether it's a bug and will be fixed would be very helpful - thanks!

@GrosSacASac
Copy link

I think the API behaviour change is not intentional
Here is a fix that could help:
After

/**
 * Emulate the output of a two-element array.
 * @return {string} Diff operation as a string.
 */
diff_match_patch.Diff.prototype.toString = function() {
  return this[0] + ',' + this[1];
};

add the following


if (typeof Symbol === 'function') {
    diff_match_patch.Diff.prototype[Symbol.iterator] = function* () {
      yield this[0];
      yield this[1];
    };
}

Another possible is to cast to a real Array:

const [eq, str] = Array.from(a[0]);

dmsnell added a commit to dmsnell/diff-match-patch that referenced this issue May 2, 2024

Verified

This commit was signed with the committer’s verified signature. The key has expired.
dmsnell Dennis Snell
Resolves google#39

It can be useful to extract `Diff` elements using destructuring
assignment. For example:

```js
const a = dmp.diff_main('abc', 'ab123c', false);
const [eq, str] = a[0];
```

Because the `Diff` object is not an array, however, this is not
possible, even though it acts like an array.

In this patch a new `Symbol.iterator` method is added to the `Diff`
class so that this pattern can be used.

Props: @JackuB, @GrosSacASac, @TheSpyder
Co-authored-by: Cyril Walle <cyril.walle@protonmail.com>
@dmsnell
Copy link

dmsnell commented May 2, 2024

I've incorporated a Symbol.iterator method on Diff in my fork: https://github.com/dmsnell/diff-match-patch

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants