reconcile children in two passes
by mindplay
HTML
<ul id="fruit">
<li>Pear</li>
<li>Apple</li>
<li>Cherry</li>
<li>Plum</li>
<li>Peach</li>
</ul>
<button id="shuffle">Shuffle</button>
<button id="reverse">Reverse</button>
<br>
<button id="rotate-up">Rotate Up</button>
<button id="rotate-down">Rotate Down</button>
<br>
<button id="add-first">Add First</button>
<button id="add-last">Add Last</button>
<button id="add-random">Add Random</button>
<br>
<button id="delete-first">Delete First</button>
<button id="delete-last">Delete Last</button>
<button id="delete-random">Delete Random</button>
JavaScript
const parent = document.querySelector("#fruit");
let children = [...parent.children];
console.clear();
setChildren(parent, children);
//console.clear();
function shuffle(a) {
return a.map(n => [Math.random(), n]).sort().map(n => n[1]);
}
function rotate(arr, count) {
count -= arr.length * Math.floor(count / arr.length);
arr.push.apply(arr, arr.splice(0, count));
return arr;
}
let num = 1000;
function newLI() {
let el = document.createElement("li");
el.innerText = num++;
return el;
}
const splice = (a,index,count,...items) => {
a = a.slice();
a.splice(index, count, ...items);
return a;
}
const reverse = a => {
a = a.slice();
return a.reverse();
};
const randomIndex = a => Math.floor((a.length-1) * Math.random());
const addLast = a => a.concat(newLI());
const addFirst = a => [newLI()].concat(...a);
const addRandom = a => splice(a, randomIndex(a), 0, newLI());
const deleteRandom = a => splice(a, randomIndex(a), 1);
const deleteFirst = a => splice(a, 0, 1);
const deleteLast = a => splice(a, a.length-1, 1);
const update = fn => () => {
children = fn(children);
setChildren(parent, children);
}
document.querySelector("#shuffle").addEventListener("click", update(shuffle));
document.querySelector("#reverse").addEventListener("click", update(reverse));
document.querySelector("#rotate-up").addEventListener("click", update(a => rotate(a, 1)));
document.querySelector("#rotate-down").addEventListener("click", update(a => rotate(a, -1)));
document.querySelector("#add-first").addEventListener("click", update(addFirst));
document.querySelector("#add-last").addEventListener("click", update(addLast));
document.querySelector("#add-random").addEventListener("click", update(addRandom));
document.querySelector("#delete-random").addEventListener("click", update(deleteRandom));
document.querySelector("#delete-first").addEventListener("click", update(deleteFirst));
document.querySelector("#delete-last").addEventListener("click",...