Javascript完整比较函数

Javascript完整比较函数,javascript,performance,comparison,Javascript,Performance,Comparison,我正在开发一个包含主要结构和算法的完整库(Javascript)。 我需要设计一个比较函数来比较各种数据 我将此函数用作: a=一些数据(字符串、数字、对象、数组等) b=一些数据(字符串、数字、对象、数组等) b、 比较(a): 如果a等于b,则为0 1如果b i大于 -如果b小于a,则为1 我设计了我的版本,并从underline.js框架的uq.eq中获得了灵感 你觉得怎么样? 有没有更好的方法来实施它 function compare (a, b, aStack, bStack) {

我正在开发一个包含主要结构和算法的完整库(Javascript)。 我需要设计一个比较函数来比较各种数据

我将此函数用作:

a=一些数据(字符串、数字、对象、数组等)

b=一些数据(字符串、数字、对象、数组等)

b、 比较(a):

  • 如果a等于b,则为0
  • 1如果b i大于
  • -如果b小于a,则为1
我设计了我的版本,并从underline.js框架的uq.eq中获得了灵感

你觉得怎么样? 有没有更好的方法来实施它

function compare (a, b, aStack, bStack) {

        // with this I can youse compare as b.compare(a)
        b = b || this.data;

        // Unwrap any wrapped objects.
        if (b instanceof ObjectNode) b = b.data;
        if (a instanceof ObjectNode) a = a.data;

        // Identical objects are equal. `0 === -0`, but they aren't identical.
        // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
        if (a === b) {
            if(a !== 0) return 0;
            else if(1 / a === 1 / b) return 0;
            else return (1 / b > 1 / a)? 1 : -1;
        }
        // A strict comparison is necessary because `null == undefined`.
        if (a == null || b == null || a == undefined || b == undefined) {
            if(a === b) return 0;
            /* Now I am defining:
            (NaN > null)
            null > undefined
            null < everything else
            undefined < everything */
            if(a == undefined) return 1;
            if(b == undefined) return -1;
            if(a == null)   return 1;
        }

        // Compare `[[Class]]` names.
        var className = toString.call(a);
        if (className !== toString.call(b)) {

            // In this case I compare strings;
            if(className < toString.call(b)) 1;
            if(className > toString.call(b)) -1;

        }
        switch (className) {
                // Strings, numbers, regular expressions, dates, and booleans are compared by value.
            case '[object RegExp]':
                // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
            case '[object String]':
                // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
                // equivalent to `new String("5")`.
                if('' + a === '' + b) return 0;
                if('' + a < '' + b) return 1;
                if('' + a > '' + b) return -1;

            case '[object Number]':
                // `NaN`s are equivalent, but non-reflexive.
                // Object(NaN) is equivalent to NaN
                // Nan is less than anyother but bigger than undefined and than null
                if (+a !== +a) return (+b !== +b)? 0 : 1;
                // An `egal` comparison is performed for other numeric values.
                if (+a === 0) return  (1 / +b === 1 / a)? 0 : ((1 / +b > 1 / a)? 1 : -1);
                return (+a === +b)? 0 : (+b > +a)? 1 : -1;
            case '[object Date]':
            case '[object Boolean]':
                // Coerce dates and booleans to numeric primitive values. Dates are compared by their
                // millisecond representations. Note that invalid dates with millisecond representations
                // of `NaN` are not equivalent.
                return (+a === +b) ? 0 : (+b > +a)? 1 : -1;
        }

        var areArrays = className === '[object Array]';
        if (!areArrays) {
            if (typeof a != 'object') return 1;
            if (typeof b != 'object') return -1;

            // Objects with different constructors are not equivalent, but `Object`s or `Array`s
            // from different frames are.
            var aCtor = a.constructor, bCtor = b.constructor;
            if (aCtor !== bCtor && !((typeof aCtor == 'function') && aCtor instanceof aCtor &&
                                     (typeof bCtor == 'function') && bCtor instanceof bCtor)
                && ('constructor' in a && 'constructor' in b)) {
                return b>a? 1 : -1;
            }
        }
        // Assume equality for cyclic structures. The algorithm for detecting cyclic
        // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

        // Initializing stack of traversed objects.
        // It's done here since we only need them for objects and arrays comparison.
        aStack = aStack || [];
        bStack = bStack || [];
        var length = aStack.length;
        while (length--) {
            // Linear search. Performance is inversely proportional to the number of
            // unique nested structures.
            if (aStack[length] === a) return bStack[length] === b;
        }

        // Add the first object to the stack of traversed objects.
        aStack.push(a);
        bStack.push(b);

        // Recursively compare objects and arrays.
        if (areArrays) {
            // Compare array lengths to determine if a deep comparison is necessary.
            length = a.length;
            if (length !== b.length) return b.length>a.length? 1 : -1;
            // Deep compare the contents, ignoring non-numeric properties.
            var res;
            while (length--) {
                if ( (res = this.compare(a[length], b[length], aStack, bStack)) != 0) return res;
            }
        } else {
            // Deep compare objects.
            var keys = Object.keys(a), key;
            length = keys.length;
            // Ensure that both objects contain the same number of properties before comparing deep equality.
            if (Object.keys(b).length !== length) return (Object.keys(b).length > length)? 1 : -1;
            while (length--) {
                // Deep compare each member
                key = keys[length];
                if (!(hasOwnProperty.call(b, key) && (res = this.compare(a[key], b[key], aStack, bStack)) === 0)) return res;
            }
        }
        // Remove the first object from the stack of traversed objects.
        aStack.pop();
        bStack.pop();
        return 0;
    }
函数比较(a、b、aStack、bStack){
//有了这个,我可以把你比作b
b=b | |此数据;
//打开所有包裹的对象。
如果(b instanceof ObjectNode)b=b.data;
如果(ObjectNode的实例)a=a.data;
//相同的对象是相等的。`0==-0`,但它们不相同。
//见[Harmony`egal`提案](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
如果(a==b){
如果(a!==0)返回0;
否则如果(1/a==1/b)返回0;
否则返回(1/b>1/a)?1:-1;
}
//必须进行严格的比较,因为`null==undefined`。
如果(a==null | | b==null | | a==undefined | | b==undefined){
如果(a==b)返回0;
/*现在我定义:
(NaN>null)
空>未定义
空<其他所有内容
未定义的<一切*/
如果(a==未定义)返回1;
如果(b==未定义)返回-1;
如果(a==null)返回1;
}
//比较`[[Class]]`名称。
var className=toString.call(a);
if(className!==toString.call(b)){
//在本例中,我比较字符串;
if(classNametoString.call(b))-1;
}
开关(类名){
//字符串、数字、正则表达式、日期和布尔值按值进行比较。
案例“[object RegExp]”:
//regexp被强制为字符串以进行比较(注意:'+/a/i==='/a/i')
案例“[对象字符串]”:
//原语及其对应的对象包装器是等价的;因此,`5`是等价的
//相当于`新字符串(“5”)`。
如果(''+a==''+b)返回0;
如果(“”+a<“”+b)返回1;
如果(“”+a>“”+b)返回-1;
案例“[对象编号]”:
//'NaN'是等价的,但不是反身的。
//对象(NaN)等价于NaN
//Nan小于任何其他值,但大于未定义值和空值
如果(+a!==+a)返回(+b!==+b)?0:1;
//对其他数值执行“egal”比较。
如果(+a==0)返回(1/+b==1/a)?0:((1/+b>1/a)?1:-1);
返回(+a===+b)?0:(+b>+a)?1:-1;
案例“[对象日期]”:
案例“[对象布尔]”:
//强制将日期和布尔值转换为数字基元值。日期按其值进行比较
//毫秒表示法。请注意,使用毫秒表示法的日期无效
//“NaN”的用法不相等。
返回(+a===+b)?0:(+b>+a)?1:-1;
}
var areArrays=className=='[object Array]';
如果(!区域阵列){
if(typeof a!=“object”)返回1;
if(typeof b!=“object”)返回-1;
//具有不同构造函数的对象不是等价的,而是'Object'或'Array'的
//从不同的框架是。
var aCtor=a.constructor,bCtor=b.constructor;
if(aCtor!==bCtor&&!((aCtor类型=='function')&&aCtor实例&&
(bCtor的类型==‘函数’&&bCtor实例bCtor)
&&(a中的“构造函数”和b中的“构造函数”){
返回b>a?1:-1;
}
}
//假设循环结构相等。检测循环结构的算法
//结构改编自ES 5.1第15.12.3节,抽象操作“JO”。
//初始化遍历对象的堆栈。
//这是在这里完成的,因为我们只需要它们来比较对象和数组。
aStack=aStack | |[];
bStack=bStack | |[];
变量长度=aStack.length;
while(长度--){
//线性搜索。性能与搜索次数成反比
//独特的嵌套结构。
如果(aStack[length]==a)返回bStack[length]==b;
}
//将第一个对象添加到遍历对象的堆栈中。
反推力(a);
b后退推(b);
//递归地比较对象和数组。
if(区域阵列){
//比较数组长度以确定是否需要进行深度比较。
长度=a.长度;
如果(长度!==b.length)返回b.length>a.length?1:-1;
//深入比较内容,忽略非数字属性。
var-res;
while(长度--){
如果((res=this.compare(a[length],b[length],aStack,bStack))!=0)返回res;
}
}否则{
//深度比较对象。
var keys=Object.keys(a),key;
长度=键。长度;
//在比较深度相等之前,请确保两个对象包含相同数量的属性。
if(Object.keys(b).length!==length)返回(Object.keys(b).length>length)?1:-1;
while(长度--){
//深入比较每个成员
键=键[长度];
如果(!(hasOwnProperty.call(b,key)&(res=this.compare)(a[ke