复制代码 代码如下:
//灵感来自
//http://www.cnblogs.com/jkisjk/archive/2011/01/28/array_quickly_sortby.html
var hasDuplicate = false;
var sortBy = function(nodes){
var result = [], array = [], n = nodes.length, i = n, node;
while(node = nodes[–n]){
(array[n] = new Number(~~node.sourceIndex))._ = node;
}
array.sort(function(a,b){
if(a === b) hasDuplicate = true;
return a – b ;
});
while( i )
result[–i] = array[i]._;
return result;
}
下面是第二版,经过改进,终于比jQuery的那个快上三倍(测试对象为拥有260多个节点的文档)
复制代码 代码如下:
var hasDuplicate = false;
var Rage = {
getList : function(node){
var list = [];
while(node){
if(node.nodeType === 9){
break;
}
list.unshift(node);
node = node.parentNode;
}
return list;
},
getLists : function(nodes){
var lists = [], getList = Rage.getList, i=0, node;
while(node = nodes[i++]){
lists[ lists.length ] = getList(node);
}
return lists;
},
sliceList : function(lists,num){
var result = [], i = 0, list;
while(list = lists[i++]){
list = list.slice(num);
if(list.length){
result[ result.length ] = list;
}
}
return result;
},
sortList : function(a,b){
var n = Math.min(a.length,b.length),ap,bp;
for(var i=0; i < n; i++){
ap = a[i],bp = b[i]
if(ap !== bp){
while(ap = ap.nextSibling){
if(ap === bp){
return -1
}
}
return 1
}
}
return a.length-b.length;
},
uniqueSort : function(nodes){
var length = nodes.length;
var lists = Rage.getLists(nodes);
lists.sort(function(a,b){
return a.length – b.length;
});
var depth = lists[0].length, length = lists.length, parent, cut, ii = 0;
for(var i =0; i < depth; i++){
parent = lists[0][i];
cut = true;
for(var j = 1;j < length; j++){
if(parent !== lists[j][i]){
cut = false;
break;
}
}
if(cut){
ii++
}else{
break;
}
}
var LCA = lists[0][ii-1];
lists = Rage.sliceList(lists,ii);
lists.sort(Rage.sortList);
var list, i = 0, result = [];
while(list = lists[i++]){
result[result.length] = list.pop();
}
if(result.length !== length){
result.unshift(LCA);
if(result.length != length){
hasDuplicate = true;
}
}
return result;
}
}
代码如下:
//灵感来自 //https://www.cnblogs.com/jkisjk/archive/2011/01/28/array_quickly_sortby.html var hasDuplicate = false; var sortBy = function(nodes){ var result = [], array = [], n = nodes.length, i = n, node; while(node = nodes[–n]){ (array[n] = new Number(~~node.sourceIndex))._ = node; } array.sort(function(a,b){ if(a === b) hasDuplicate = true; return a – b ; }); while( i ) result[–i] = array[i]._; return result; }