3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【2024年版】JavaScript(React)におけるリーダブルコードのチートシート10~13章

Last updated at Posted at 2024-03-20

2024/3/18
コードの再構成
10章 無関係の下位問題を抽出する

10.1 入門的な例: findClosestLocation()

こちらの記事の続編になります。

10.1 入門的な例: findClosestLocation()

const findClosestLocation = (lat, lng array) => {
     let closest;
     let closes_dist = Number.MAX_VALUE;

     for(var i = 0; i < arrya.length; i += i){
         //2つの地点をラジアンに変換する
         const lat_rad = radians(lat);
         const lat_rad = radians(lnt);
         const lat2_rad = radians(array[i].latitude);
         const lat2_rad = radians(array[i].longitude);
    
         //「球面三角法の第二余弦定理」の公式を使う
         const dist = Math.acos(Math.sin(lat_rad) * Math.sin(lat2_rad) +
                              Math.cos(lat_rad) * Math.cos(lat2_rad) *
                              Math.cos(lang2_rad - lng_rad));
    
         if(dist < closest_dist){
            closest = array[i];
            closest_dist = dist;
         }
     }
     
     return closest;
}
javascript:ループ内の無関係の下位問題を抽出
const sphericalDistance = (lat1, lng1, lat2, lng2) => {
     const lat1_rad = radians(lat1);
     const lng1_rad = radians(lng1);
     const lat2_rad = adians(lng2);
     const lng2_rad = radians(lng2);

     return Math.acos(Math.sin(lat1_rad) * Math.sin(lat2_rad) +
                               Math.cos(lat1_rad) * Math.cos(lat2_rad) *
                               Math.cos(lng2_rad - lng_rad));
} 

const findClosestLocation = (lat, lng array) => {
     let closest;
     let closes_dist = Number.MAX_VALUE;

     for(var i = 0; i < arrya.length; i += i){
         //関数に切り出した
-        const lat_rad = radians(lat);
-        const lnt_rad = radians(lng);
-        const lat2_rad = radians(array[i].latitude);
-        const lng2_rad = radians(array[i].longitude);
    
         //「球面三角法の第二余弦定理」の公式を使う
-        const dist = Math.acos(Math.sin(lat_rad) * Math.sin(lat2_rad) +
-                             Math.cos(lat_rad) * Math.cos(lat2_rad) *
-                             Math.cos(lng2_rad - lng_rad));
         //切り出した関数を使用
+        const dist =  sphericalDistance(lat, lng, array[i].latitude, array[i].longitude) 
         if(dist < closest_dist){
            closest = array[i];
            closest_dist = dist;
         }
     }
     
     return closest;
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?