Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

array.indexOf not working after filter #106

Open
jbakse opened this issue Mar 21, 2024 · 0 comments
Open

array.indexOf not working after filter #106

jbakse opened this issue Mar 21, 2024 · 0 comments

Comments

@jbakse
Copy link

jbakse commented Mar 21, 2024

I'm seeing some unexpected behavior when using indexOf on an array property of a "watched object" created with on-change.

watched.a.indexOf(watched.a[0]) should return 0, and does when i first create an array. But if I filter the array and resassign it, indexOf no longer works properly.

It is probably clearer to look at the code below to see the problem.

import onChange from "on-change";

const o = { a: [] };
const watched = onChange(o, () => {
  console.log("onChange");
});

watched.a = [{ a: 1 }, { a: 2 }, { a: 3 }];
// onChange
console.log("pre filter");
// pre filter
console.log("a", watched.a);
// a [ { a: 1 }, { a: 2 }, { a: 3 } ]
console.log("a.length", watched.a.length);
// a.length 3
console.log("indexOf[0]", watched.a.indexOf(watched.a[0]));
// indexOf[0] 0  <--- RIGHT!

watched.a = watched.a.filter(() => true);
// onChange
console.log("post filter");
// post filter
console.log("a", watched.a);
// a [ { a: 1 }, { a: 2 }, { a: 3 } ]
console.log("a.length", watched.a.length);
// a.length 3
console.log("indexOf[0]", watched.a.indexOf(watched.a[0]));
// indexOf[0] -1 <--- WRONG?!

I can sort of see how the proxy magic might confuse identity checks performed by indexOf, but I think that the behavior above is unintended.

I can work around the problem by using splice() instead of filter, but i'd like to use filter.

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

No branches or pull requests

1 participant