In each run of my code, availableGoodsUrlSet may be assigned new value, which is of type Set(for simplicity , I assign it to a date object in the following code), from the second run I want to get the difference of the new availableGoodsUrlSet with its previous value, but when I clicked the Add a list item link for a second time in the following code to test, I got
Uncaught TypeError: lastAvailableGoodsUrlSet.has is not a function
at options.html:37
at Array.filter (<anonymous>)
at MutationObserver.<anonymous> (options.html:37)
So how to achieve my goal ?
Simple MutationObserver Example .invisible { opacity: 0; }<body>
<h1>Simple MutationObserver Example</h1>
<response class="invisible response">Success!</response>
<ul>
<li>Pre-existing list item</li>
<li>Pre-existing list item</li>
</ul>
<p><a data-click="add-list-item" href="#">Add a list item</a></p>
<script>
var unorderedList = document.getElementsByTagName("ul")[0];
if (unorderedList) {
var lastAvailableGoodsUrlSet = new Set();
var observer = new MutationObserver(
function (mutations) {
availableGoodsUrlSet = new Set();
date = new Date();
availableGoodsUrlSet.add(date);
// lastAvailableGoodsUrlSet.add(date);
difference =new Set([...availableGoodsUrlSet].filter(x => !lastAvailableGoodsUrlSet.has(x)));
console.log("difference--------", difference);
lastAvailableGoodsUrlSet=Object.assign({}, availableGoodsUrlSet);
});
// pass in the target node and the observer config options
observer.observe(unorderedList, { childList: true, subtree: true });
// listen for any clicks on the add-list-item link
document.querySelector('[data-click="add-list-item"]').onclick = function (event) {
var newLi = document.createElement("li");
newLi.innerText = "New list item";
unorderedList.appendChild(newLi);
event.preventDefault();
};
}
</script>
</body>
Don't use lastAvailableGoodsUrlSet=Object.assign({}, availableGoodsUrlSet);
You are changing Set object to pure object which has no method add.
In case you need to merge sets, you can do this:
const firstList = new Set([1,2,3]);
const secondList = new Set([3,4,5]);
const result = [...new Set([...firstList, ...secondList])];
console.log(result);
To get the difference:
const firstList = [1, 2, 3];
const secondList = [3, 4, 5];
const result = firstList.filter(x=> !secondList.includes(x));
console.log(result);