Is there a code contract library for JavaScript? [closed]

大憨熊 提交于 2019-12-06 03:54:37

This is a runtime type contracts library which takes on some Haskell like syntax: http://code.google.com/p/ristretto-js.

strongriley

I was pretty impressed by the implementation put together for this question:

JavaScript Code Contract Libraries?

Example:

function syncTime(serverTime, now) {
  Verify.value(serverTime).always().isDate();   // Cannot be undefined or null.
  Verify.value(now).whenDefined().isDate();     // Cannot be null, but must be date when defined.

  //Code
}

Why not just roll a library yourself?

Using a strategy pattern, you can easily run a series of methods on a specific value.

Here is a semi-crude example. This obviously needs more error handling and modification, but it provides an idea for what you could build. http://jsfiddle.net/fBfgz/

var validator = (function() {
    // Available checks
    var types = {
        isNum: function(value) {
            return !isNaN(value);
        },

        isNull: function(value) {
            return value === null;
        }
    };

   return {
       validate: function (data) {

           var i, len, check, ret;
           for (i = 0, len = data.checks.length; i < len; i += 1) {

               if (types.hasOwnProperty(data.checks[i])) {
                   check = types[data.checks[i]]; 
                   ret = check(data.value);
                   alert(ret);
                   if (!ret) {
                       return false;
                   }
               }
           }
           return true;
       }
   };  
}());

validator.validate({ // will return true
    value: 32,
    checks: ['isNum']
});
validator.validate({ // will return false
    value: 32+'a',
    checks: ['isNum']
});

I would probably use QUnit for general purpose javascript testing. Also check out Tim Disney's contracts.js, which may be more specific to your use case.

Sweet-contracts does exactly what you want.

Sweet-contracts is a module requiring sweet.js, and uses macros to add contracts right into the language. This way you don't have to hack your contracts using existing (and usually insufficient/inefficient) language constructs.

sweet.js allows you to create macros that can expand the language modularly. This blog post gives a great introduction to sweet and the power of macros. You can try it out live in your browser at this address.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!