gpt4 book ai didi

Javascript 逐行比较

转载 作者:行者123 更新时间:2023-11-28 02:28:27 26 4
gpt4 key购买 nike

我有来自用户 Harmen 的 JavaScript 代码。

令人惊奇的是,这么短的代码竟然能完成如此出色的工作。 http://jsfiddle.net/pfYtu/

我尝试编辑它以进行逐行比较,但代码没有注释,我很难理解逻辑(它是如何工作的)。希望原编码员能给我一些建议。

逐行是什么意思?目前,它将结果显示为表格的单列,好吧,我希望将其显示为两列。这是原始源代码。

// http://harmen.no-ip.org/javascripts/diff/
// http://stackoverflow.com/questions/4462609
function diff_text(text1, text2) {
var table = '';

function make_row(x, y, type, text) {
if (type == ' ') console.log(x, y);
var row = '<tr';
if (type == '+') row += ' class="add"';
else if (type == '-') row += ' class="del"';
row += '>';

row += '<td class="lineno">' + y;
row += '<td class="lineno">' + x;
row += '<td class="difftext">' + type + ' ' + text;

table += row;
}

function get_diff(matrix, a1, a2, x, y) {
if (x > 0 && y > 0 && a1[y-1] === a2[x-1]) {
get_diff(matrix, a1, a2, x-1, y-1);
make_row(x, y, ' ', a1[y-1]);
}
else {
if (x > 0 && (y === 0 || matrix[y][x-1] >= matrix[y-1][x])) {
get_diff(matrix, a1, a2, x-1, y);
make_row(x, '', '+', a2[x-1]);
}
else if (y > 0 && (x === 0 || matrix[y][x-1] < matrix[y-1][x])) {
get_diff(matrix, a1, a2, x, y-1);
make_row('', y, '-', a1[y-1]);
}
else {
return;
}
}
}

function diff(a1, a2) {
var matrix = new Array(a1.length + 1);
var x, y;

for (y = 0; y < matrix.length; y++) {
matrix[y] = new Array(a2.length + 1);

for (x = 0; x < matrix[y].length; x++) {
matrix[y][x] = 0;
}
}

for (y = 1; y < matrix.length; y++) {
for (x = 1; x < matrix[y].length; x++) {
if (a1[y-1] === a2[x-1]) {
matrix[y][x] = 1 + matrix[y-1][x-1];
}
else {
matrix[y][x] = Math.max(matrix[y-1][x], matrix[y][x-1]);
}
}
}

get_diff(matrix, a1, a2, x-1, y-1);
}

diff(text1.split('\n'), text2.split('\n'));
return '<table class="diff_text">' + table + '</table>';
}

最佳答案

尝试这个 make_row 函数...它给出 2 列结果。

function make_row(x, y, type, text) {
if (type == " ") console.log(x, y);
var row = "<tr";
if (type == "+") row += ' class="add"';
else if (type == "-") row += ' class="del"';
row += ">";

row += '<td class="lineno">' + y;
row += '<td class="lineno">' + x;
if (type == " ") {
row += '<td class="difftext">' + type + " " + text;
row += '<td class="difftext">' + type + " " + text;
}

if (type == "+") {
row += '<td class="difftext">' + " ";
row += '<td class="difftext">' + type + " " + text;
}

if (type == "-") {
row += '<td class="difftext">' + type + " " + text;
row += '<td class="difftext">' + " ";
}

table += row;
}

关于Javascript 逐行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com