【问题标题】:How can I create functions to reduce redundancy in my code? [JS]如何创建函数以减少代码中的冗余? [JS]
【发布时间】:2019-11-29 05:37:56
【问题描述】:

我的代码运行良好,但我重复了太多次,考虑到我只处理了一个集合的查询,代码会太大。
我曾尝试使用函数来处理一些代码,但它不起作用,因为某些变量无法全局访问。
这是代码

 var markers = [];

        function addMarker(coords, content, animation){

            var marker = new google.maps.Marker({
                position:  coords,

                map: map,
                icon: icon = {
                    url : isBouncing ? red_icon : green_icon,
                    scaledSize: new google.maps.Size(40, 40), // scaled size

                },
                // IF THERE'S AN ERROR, BOUNCE IT
                animation: animation
            });

            var infoWindow = new google.maps.InfoWindow({
                content: content

            });


            marker.addListener('spider_click', function() {
                map.panTo(this.getPosition());
                infoWindow.open(map,marker);
            });
            oms.addMarker(marker); 

            markers.push(marker);
        }



      function clearMarkers() {
        setMapOnAll(null);
      }


      function deleteMarkers() {
        clearMarkers();
        markers = [];

      }



 db.collection('Nairobi').onSnapshot(function(snapshot) {

        snapshot.forEach(function(child){
                var name_loc = child.id;
                var loc = child.data().marker;
                var forward = child.data().ForwardPower;
                var reflected = child.data().ReflectedPower;

                var ups = child.data().UPSError;
                var upsDesc = child.data().UPSDesc;
                var trans = child.data().TransmitterError;
                var transDesc = child.data().TransDesc;
                 var kplc = child.data().KPLC;
                var kplcDesc = child.data().KPLCDesc;
                var sat = child.data().SatelliteReceiver;
                var satDesc = child.data().SatDesc;


                       if(ups === true && trans ===true && sat ===true && kplc ===true){
                        isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<p> UPSError: ${upsDesc} </p>`
                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`
                         +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }   


                  else if(ups === false && trans ===true && sat ===true && kplc ===true){
                        isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`
                         +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                } 



               else if(ups === true && trans ===false && sat ===true && kplc ===true){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<p> UPSError: ${upsDesc} </p>`
                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`


                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }


               else if(ups === false && trans ===false && sat ===false && kplc ===false){
                    isBouncing = false;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },


                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<h2> Running well </h2>` 

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'

                    );
                }


                console.log(child.id, child.data());
            });


                 snapshot.docChanges().forEach((change) => {

                 if (change.type === "modified") {

                    deleteMarkers();
                    snapshot.forEach(function(child){

      /***************************REDUNDANT CODE****************************************/
                var name_loc = child.id;
                var loc = child.data().marker;
                var forward = child.data().ForwardPower;
                var reflected = child.data().ReflectedPower;

                var ups = child.data().UPSError;
                var upsDesc = child.data().UPSDesc;
                var trans = child.data().TransmitterError;
                var transDesc = child.data().TransDesc;
                 var kplc = child.data().KPLC;
                var kplcDesc = child.data().KPLCDesc;
                var sat = child.data().SatelliteReceiver;
                var satDesc = child.data().SatDesc;


                       if(ups === true && trans ===true && sat ===true && kplc ===true){
                        isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<p> UPSError: ${upsDesc} </p>`
                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`
                         +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }   




                else if(ups === false && trans ===true && sat ===false && kplc ===true){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> KPLC: ${kplcDesc} </p>` 
                        +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                else if(ups === true && trans ===false && sat ===true && kplc ===false){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> UPSError: ${upsDesc} </p>` 
                        +  `<p> SatelliteReceiver: ${satDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                else  if(ups === true && trans ===false&& sat ===false && kplc ===false){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> UPSError: ${upsDesc} </p>` 

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                else if(ups === false && trans ===true && sat ===false && kplc ===false){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> TransmitterError: ${transDesc} </p>` 

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                console.log(child.id, child.data());
            });

          }
       });

     })

还有更好的方法来处理那些 IF 语句,让我的代码更干净。

【问题讨论】:

  • 为什么没有返回addMarker的函数呢?每次都调用它。
  • 这是一个很难的问题 - 很多代码供人们尝试理解。但这里有一些提示:您可以使用这个小技巧将 ifs 重构为开关:使用 switch(true) 然后使用 case !ups &amp;&amp; !trans &amp;&amp; sat &amp;&amp; !kplc:(例如)。注意我去掉了所有的 === true 和 false!
  • @Spangle 已经有 addMarker 的函数了。
  • @seesharper 我会试试的。但是,我有没有办法将所有这些 IF 语句/ SWITCH 案例放在一个函数中?因为我需要再使用 20 次?
  • 我看到有一个名为 addMarker 的函数,请再次阅读我在上面的评论中所说的内容:) 智能设置,您不需要一遍又一遍地写 &lt;div id="iw-container"&gt; Etc

标签: javascript firebase function if-statement google-cloud-firestore


【解决方案1】:

这是您可以制作的方法。另外,我创建了getHtml 函数来获取 HTML。为其他添加条件以将getHtml 用于其他类似upsError

var markers = [];

function addMarker(coords, content, animation) {

    var marker = new google.maps.Marker({
        position: coords,

        map: map,
        icon: icon = {
            url: isBouncing ? red_icon : green_icon,
            scaledSize: new google.maps.Size(40, 40), // scaled size

        },
        // IF THERE'S AN ERROR, BOUNCE IT
        animation: animation
    });

    var infoWindow = new google.maps.InfoWindow({
        content: content

    });


    marker.addListener('spider_click', function () {
        map.panTo(this.getPosition());
        infoWindow.open(map, marker);
    });
    oms.addMarker(marker);

    markers.push(marker);
}


function clearMarkers() {
    setMapOnAll(null);
}


function deleteMarkers() {
    clearMarkers();
    markers = [];

}

function getHtml(name_loc,data) {
    return '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +
                        `<p> TransmitterError: ${data} </p>`

                        +
                        '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'
}


function calculateEachData(snapshot,child){
    /***************************REDUNDANT CODE HERE****************************************/
                var name_loc = child.id;
                var loc = child.data().marker;
                var forward = child.data().ForwardPower;
                var reflected = child.data().ReflectedPower;

                var ups = child.data().UPSError;
                var upsDesc = child.data().UPSDesc;
                var trans = child.data().TransmitterError;
                var transDesc = child.data().TransDesc;
                var kplc = child.data().KPLC;
                var kplcDesc = child.data().KPLCDesc;
                var sat = child.data().SatelliteReceiver;
                var satDesc = child.data().SatDesc;


                if (ups === true && trans === true && sat === true && kplc === true) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>" +
                        `<p> UPSError: ${upsDesc} </p>` +
                        `<p> SatelliteReceiver: ${satDesc} </p>` +
                        `<p> KPLC: ${kplcDesc} </p>` +
                        `<p> TransmitterError: ${transDesc} </p>`

                        +
                        '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        , google.maps.Animation.BOUNCE
                    );
                } else if (ups === false && trans === true && sat === false && kplc === true) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +
                        `<p> KPLC: ${kplcDesc} </p>` +
                        `<p> TransmitterError: ${transDesc} </p>`

                        +
                        '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        , google.maps.Animation.BOUNCE
                    );
                } else if (ups === true && trans === false && sat === true && kplc === false) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +
                        `<p> UPSError: ${upsDesc} </p>` +
                        `<p> SatelliteReceiver: ${satDesc} </p>`

                        +
                        '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        , google.maps.Animation.BOUNCE
                    );
                } else if (ups === true && trans === false && sat === false && kplc === false) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        }, getHtml(name_loc,upsDesc), google.maps.Animation.BOUNCE
                    );
                } else if (ups === false && trans === true && sat === false && kplc === false) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        },getHtml(name_loc,transDesc), google.maps.Animation.BOUNCE
                    );
                }


                console.log(child.id, child.data());
}
function childSanp(snapshot) {
    snapshot.forEach(function (child) {
        calculateEachData(snapshot,child)
    });
}

function docSnap(snapshot) {
    snapshot.docChanges().forEach((change) => {
        if (change.type === "modified") {
            deleteMarkers();
            snapshot.forEach(function (child) {
                calculateEachData(snapshot,child)
            });

        }
    });
}

db.collection('Nairobi').onSnapshot(async function (snapshot) {

    await childSanp(snapshot)
    await docSnap(snapshot)

})

【讨论】:

  • 这太棒了,它为我节省了很多空间和时间。我唯一需要澄清的是 getHTML 函数。
  • 啊,是的,我明白了。多谢。我的 950 行代码现在变成了 300 行。
【解决方案2】:

创建一个函数来创建 HTML 内容并传递必要的变量/占位符来生成内容。

使用 string ``创建一个完整的 HTML 字符串,如下所示。

<div id="iw-container"> <div class="iw-title"> ${name_loc}</div> <div class="iw-content"> <p> UPSError: ${upsDesc} </p> <p> SatelliteReceiver: ${satDesc} </p> <p> KPLC(: ${kplcDesc} </p> <p> TransmitterError: ${transDesc} </p> </div> <div class="iw-bottom-gradient"></div> </div>

【讨论】:

    【解决方案3】:

    使用嵌套的 if 语句。正如你所说,代码目前太长了。从现在开始的一个月或一年后,如果不不断滚动浏览,您将不会记得发生了什么。

    使用几个变量。

    if( ups == true ){
       if( trans == true ){
          bBouncing = true;
          ...
       }else{ // trans == false
          ...
    }else{ // ups == false
       bBouncing = false;
       ...
    } // End of all if's
    
    addMarker(
       ...
       ,(bBouncing ? google.maps.Animation.BOUNCE : google.maps.Animation.NONE)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 2015-01-27
      相关资源
      最近更新 更多