Skip to content

Instantly share code, notes, and snippets.

@oshiro-kazuma
Last active October 3, 2016 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oshiro-kazuma/e1a8bf49deb8af5c3ec640f57d9bc40a to your computer and use it in GitHub Desktop.
Save oshiro-kazuma/e1a8bf49deb8af5c3ec640f57d9bc40a to your computer and use it in GitHub Desktop.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
</head>
<body>
developer consoleを確認
<!-- 共通ライブラリ的なところに -->
<script type="text/javascript">
// レーベンシュタイン距離でソートするオブジェクト
// 共通ライブラリとして何処かに格納してください
function DistanceSorter(brands, input) {
// 計算結果保持用
this.distances = [];
// DistanceSorterのファクトリ
this.init = function(brands, input) {
this.distances = [];
var self = this;
brands.forEach(function(v) {
// TODO: どのパラメーターでレーベンシュタイン距離を測るかは組み込むときに調整する必要あり
var distance_name = self.levenshtein(input, v.brand_name);
var distance_name2 = self.levenshtein(input, v.brand_name2);
// 距離が最も近い値だけが必要なので、Minimumを取得
var min_distance = Math.min.apply(null, [distance_name, distance_name2])
//console.log("distance:", min_distance, "brand:", v);
self.distances.push({distance: min_distance, brand: v});
});
return this;
}
// レーベンシュタイン距離でソート
this.sort = function() {
this.distances = this.distances.sort(function(a,b){
if( a.distance < b.distance ) return -1;
if( a.distance > b.distance ) return 1;
return 0;
});
return this;
}
// brand オブジェクトに変換
this.getBrands = function() {
var brands = [];
this.distances.forEach(function(v) {
brands.push(v.brand);
});
return brands;
}
// レーベンシュタイン距離計算メソッド
this.levenshtein = function(a, b) {
if(!a || !b) return (a || b).length;
var m = [];
for(var i = 0; i <= b.length; i++){
m[i] = [i];
if(i === 0) continue;
for(var j = 0; j <= a.length; j++){
m[0][j] = j;
if(j === 0) continue;
m[i][j] = b.charAt(i - 1) == a.charAt(j - 1) ? m[i - 1][j - 1] : Math.min(
m[i-1][j-1] + 1,
m[i][j-1] + 1,
m[i-1][j] + 1
);
}
}
return m[b.length][a.length];
}
return this.init(brands, input);
}
</script>
<!-- 呼び出し -->
<script type="text/javascript">
// ブランドオブジェクト
var brands = [
{brand_name: "GUILD PRIME", brand_name2: "ギルドプライム メンズ"},
{brand_name: "GU" , brand_name2: "ジーユー"},
{brand_name: "GUESS" , brand_name2: "ゲス"},
];
// 入力値
var input = "GU";
// 実行
var sorted_brands = new DistanceSorter(brands, input).sort().getBrands();
// 結果確認
console.log("before", brands);
console.log("after", sorted_brands);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment