dtlのnode.jsバインディング

https://github.com/cubicdaiya/node-dtl

最近、久々にJavaScriptを勉強し直してる関係でnode.jsで遊んでみたんだけど、結局C++で書いてしまった。
そんなにほかの言語のバインディング書いた経験はないけど、node.jsのバインディング書くのは結構簡単。

node-dtlのダウンロード・インストール

$ git clone https://github.com/cubicdaiya/node-dtl.git 
$ node-waf configure build
$ node-waf install

node-dtlで文字列の差分を取る

// diff_str.js
var dtl = require('dtl')
var a = process.argv[2];
var b = process.argv[3];
var diff = new dtl.Diff(a, b);
diff.compose();
console.log("editdistance:" + diff.editdistance());
diff.printSES();
console.log("Unified Diff:");
diff.composeUnifiedHunks();
diff.printUnifiedFormat();

実行結果

$ node diff_str.js acbdeacbed acebdabbabed
editdistance:6
 a
 c
+e
 b
 d
-e
 a
-c
 b
+b
+a
+b
 e
 d
Unified Diff:
@@ -1,10 +1,12 @@
 a
 c
+e
 b
 d
-e
 a
-c
 b
+b
+a
+b
 e
 d
$

ちゃんと動いてるようだ。もちろん、diff template libraryとしての特徴を活かして文字列だけでなく数値の配列同士でも差分が取れる。

node-dtlで数値の配列の差分を取る

// diff_int_array.js
var dtl = require('dtl')
var a = [1,2,3];
var b = [1,2,5];
var diff = new dtl.Diff(a, b);
diff.compose();
console.log("editdistance:" + diff.editdistance());
diff.printSES();
console.log("Unified Diff:");
diff.composeUnifiedHunks();
diff.printUnifiedFormat();
$ node diff_int_array.js
editdistance:2
 1
 2
-3
+5
Unified Diff:
@@ -1,3 +1,3 @@
 1
 2
-3
+5
$