使用函数比较2个属性" some"

时间:2017-02-21 23:56:32

标签: javascript node.js

var e = require("./myApp.js");

var myServer = e.CreateServer(1337);

myServer.Register("/", "GET", function (req, res) { res.end("J") }); 
myServer.Register("/", "GET", function (req, res) { res.end("Ja") });

myServer.Start();

这是我的#34; Wrapper":

module.exports = (function () {

function _createServer(port) {
    var routingTable = [];
    var port = port;
    var server = require('http').createServer();

    function _start() {
        server.listen(port);
        console.log("Server was started");
    };

    function RegisterRecord(url, method, fnc) {
        this.url = url;
        this.method = method;
        this.fnc = fnc;
    };

    function _register(newUrl, newMethod, newFnc) {

        if (_checkInput(newUrl, newMethod))
            console.log("Register failed! Record with same URL and Method already exist");
        else {

            routingTable.push(new RegisterRecord(newUrl, newMethod, newFnc));
            console.log("Register success!");                    
        }
    };

    function _checkInput(newUrl, newMethod) {
        return routingTable.some(function fnc(record) { record.url == newUrl && record.method == newMethod });  
    };

    return {
        Start: _start,
        Register: _register,
        ShutDown: _shutDown
    };
};

return { CreateServer: _createServer };

})();

所以最重要的功能是" _register"和" checkInput"。

我的目标是只允许在数组routingTable中按时使用相同的URL和方法。所以当我执行程序时,Command Promp会打印两次Register成功。但" /"和" GET"应该只允许一次。

如何比较网址和方法,以便它们可以是唯一的?

PS:" Wrapper"在JS文件" ./ MyApp.js"

1 个答案:

答案 0 :(得分:1)

您需要filter

function _checkInput(newUrl, newMethod) {
    return routingTable
             .filter( function(el) {
               return el.url === newUrl && el.method === newMethod;
             })
             .length > 0;
};

更新。当然,你可以使用some - 你只是忘了从中返回一个值:

function _checkInput(newUrl, newMethod) {
    return routingTable
             .some( function(el) {
               // Need return
               return el.url === newUrl && el.method === newMethod;
             })
};