• Vue2 diff simplified the Vue2 diff process, mainly focused on the diFF between child nodes, the following is a handwritten diFF algorithm, with the source has subtle differences, mainly for understanding.
const insertBefore = (ele, refer, nodes) => { const target = nodes.findIndex(e => e === ele); if (~target) { nodes.splice(target, 1); } nodes.splice(nodes.findIndex(e => e === refer), 0, ele); } const insertAfter = (ele, refer, nodes) => { const target = nodes.findIndex(e => e === ele); if (~target) { nodes.splice(target, 1); } nodes.splice(nodes.findIndex(e => e === refer) + 1, 0, ele); } // const makeIndexMap = (nodes, startIndex, endIndex) => { // let ret = {}; // for (let i = startIndex; i <= endIndex; i++) { // ret[nodes[i]] = i; // } // return ret; // } const oldNodes = ['e', 'd', 'g', 'j', 'b', 'c', 'a']; const newNodes = ['g', 'c']; Function vue2Diff(oldNodes, newNodes) {let oldStartIndex = 0, newStartIndex = 0; // let oldNodesIndex; let [oldEndIndex, newEndIndex] = [oldNodes.length - 1, newNodes.length - 1]; // The new node is used to compare the old node. // If one of the elements has been traversed, then the diff of the individual element has been completed, While (oldStartIndex <= oldEndIndex && newStartIndex <= newEndIndex) {let [oldStartNode, newStartNode] = [oldNodes[oldStartIndex], newNodes[newStartIndex]]; let [oldEndNode, newEndNode] = [oldNodes[oldEndIndex], newNodes[newEndIndex]]; If (oldStartNode === newStartNode) {oldStartIndex++; if (oldStartNode == newStartNode) {oldStartIndex++; newStartIndex++; Else if (oldEndNode === newEndNode) {oldEndIndex--; newEndIndex--; } // If the first digit of the old node is equal to the end of the new node, then move the first digit of the old node to the end of oldEndIndex. Else if (oldStartNode === newEndNode) {insertAfter(oldStartNode, oldEndNode, oldNodes) oldEndIndex--; newStartIndex++; } // If the end of the old node is equal to the first of the new node, Else if (oldEndNode === newStartNode) {insertBefore(oldEndNode, insertBefore) oldStartNode, oldNodes); oldStartIndex++; newStartIndex++; } else {if (!) {if (!) {if (! oldNodesIndex) oldNodesIndex = makeIndexMap(oldNodes, oldStartIndex, oldEndIndex); Const newInOldIndex = oldNodes.indexof (newStartNode); // If the new node is inside the old node, move the old node to the front of newStartIndex. If (~newInOldIndex) {insertBefore(oldNodes[newInOldIndex], oldStartNode, oldNodes);  oldStartIndex++; newStartIndex++; } // If the new node is not in the old node, move the old node to the front of newStartIndex. Else {insertBefore(newStartNode, oldStartNode, oldNodes); oldStartIndex++; oldEndIndex ++; newStartIndex++; }}} // If there are extra elements at the end, If (oldEndindex-oldStartIndex >= 0) {oldNodes.splice(oldStartIndex, oldEndindex-oldStartIndex + 1); } else { oldNodes.splice(oldStartIndex, 0, ... newNodes.slice(newStartIndex, newEndIndex + 1)); } } vue2Diff(oldNodes, newNodes);Copy the code