util.diff(actual, expected)


稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

  • actual <Array> | <string> 要比较的第一个值

    ¥actual <Array> | <string> The first value to compare

  • expected <Array> | <string> 要比较的第二个值

    ¥expected <Array> | <string> The second value to compare

  • 返回:<Array> 差异条目数组。每个条目都是一个包含两个元素的数组:

    ¥Returns: <Array> An array of difference entries. Each entry is an array with two elements:

    • 索引 0:<number> 操作代码:-1 表示删除,0 表示无操作/未更改,1 表示插入

      ¥Index 0: <number> Operation code: -1 for delete, 0 for no-op/unchanged, 1 for insert

    • 索引 1:<string> 与操作关联的值

      ¥Index 1: <string> The value associated with the operation

  • 算法复杂度:O(N*D),其中:

    ¥Algorithm complexity: O(N*D), where:

  • N 是两个序列的总长度(N = actual.length + expected.length)

    ¥N is the total length of the two sequences combined (N = actual.length + expected.length)

  • D 是编辑距离(将一个序列转换为另一个序列所需的最小操作数)。

    ¥D is the edit distance (the minimum number of operations required to transform one sequence into the other).

util.diff() 比较两个字符串或数组值并返回差异条目数组。它使用 Myers diff 算法来计算最小差异​​,这与断言错误消息内部使用的算法相同。

¥util.diff() compares two string or array values and returns an array of difference entries. It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm used internally by assertion error messages.

如果值相等,则返回一个空数组。

¥If the values are equal, an empty array is returned.

const { diff } = require('node:util');

// Comparing strings
const actualString = '12345678';
const expectedString = '12!!5!7!';
console.log(diff(actualString, expectedString));
// [
//   [0, '1'],
//   [0, '2'],
//   [1, '3'],
//   [1, '4'],
//   [-1, '!'],
//   [-1, '!'],
//   [0, '5'],
//   [1, '6'],
//   [-1, '!'],
//   [0, '7'],
//   [1, '8'],
//   [-1, '!'],
// ]
// Comparing arrays
const actualArray = ['1', '2', '3'];
const expectedArray = ['1', '3', '4'];
console.log(diff(actualArray, expectedArray));
// [
//   [0, '1'],
//   [1, '2'],
//   [0, '3'],
//   [-1, '4'],
// ]
// Equal values return empty array
console.log(diff('same', 'same'));
// []