For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/proposal-generic-comparison.md.
  • 简体中文
  • Generic Comparison ?

    中文标题:通用比较

    提案概览
    提案速览

    该提案解决了 JavaScript 中缺乏标准数组比较方式的问题,包括嵌套结构。它提议了一个 Array.prototype.compare 方法,接受比较函数并返回 -1、0 或 1,还探讨了 <=> 三向比较运算符。该提案处于早期阶段,没有规范细节,成熟度仅是一个想法。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    通用比较

    作者: Hemanth HM

    推动者: Jordan HarbandHemanth HM

    动机

    比较数组是我们对数组执行的最常见操作之一,但目前没有一致的标准方法来比较两个数组,而且考虑到数组可能包含任何类型的原始值和嵌套结构,比较它们变得更加繁琐。

    目前如何处理?

    没有标准的方式,只有少数模块,如 array-equaldeep-equal,它们每周分别有约 500 万和 800 万次下载,这是深度比较的一个子集。

    考虑以下示例:

    // 模式验证
    const equal = require('deep-equal');
    
    const expectedSchema = {
      name: {
        type: String,
        required: true
      },
      score: {
        type: Number,
        default: 0
      }
    };
    
    equal(schemaCall.args[0], expectedSchema);
    

    node 内置:

    // assert.deepStrictEqual(actual, expected[, message])
    
    deepStrictEqual([new Uint32Array([1, 2, 3, 4]).subarray(1, 3), new Uint32Array([2, 3])]);
    // assert.deepEqual(actual, expected[, message])
    
    assert.deepEqual( tokenizer( "AD", "G", cldr ), [{
    		type: "G",
    		lexeme: "AD",
    		value: "1"
    	}] );

    我们能怎么做?

    Array.prototype.compare 接受一个比较函数,该函数接收两个参数。

    每个参数都是一个 [value, key] 的元组,它返回 < 0, 0, 或 > 1(当返回非有限非整数时抛出错误),然后它将返回 -1, 0, 或 1

    这样我们就可以编写自己的逻辑,如果相等则返回 0

    附注:这是一个从 Array.prototype.equals 演进的提案。

    将想法扩展到三向比较:

    我们也可以采用 <=> 三向比较运算符,它执行以下操作:

             true		      	   false
    a < b    (a <=> b) < 0		 (a <=> b) >= 0
    a <= b   (a <=> b) <= 0		 (a <=> b) > 0
    a > b    (a <=> b) > 0		 (a <=> b) <= 0
    a >= b   (a <=> b) >= 0		 (a <=> b) < 0