Giter Site home page Giter Site logo

args.js's Introduction

#Args.js

Args.js lets you easily create functions with optional parameters, default parameters, parameter groups and named parameters. It checks types and will trigger exceptions if a function is called incorrectly.

See the homepage for more details.

License

Copyright (c) 2015, Joseph Bain

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

args.js's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

args.js's Issues

Need Clarifications

Hi,

I'm not sure if it's a bug or not, but there are couple of things that I found a bit odd

function addBook() {
    var args = Args([
        {title:       Args.STRING | Args.Required}
    ], arguments);

    console.log(args);
}

addBook(123)

Error: Argument 123 (title) should be type String, but it was type number with value 0

Shouldn't it says this instead?

Argument title should be type String, but it was type number with value 123

Also, if I switch from Args.Required to Args.Optional, then call addBook(123), shouldn't it throws an error as above, instead of giving me an empty args object?

possible coding mistake

on line 179:

for (a = 0, s = 0; a < args.length, s < scheme.length ; s++) {

..it looks like there's a mistake. I haven't looked properly at what the rest of the code is doing, but the a < args.length part can't have any effect on anything, it just gets evaluated then discarded. Is it meant to be && or || instead of ,?

Adding license to package.json

@joebain - I loved the work you have done. I have been looking for a library like this for some time.
My team at Microsoft is working on a code generator named AutoRest that consumes a Swagger spec and generates client side libraries for Azure SDK in NodeJS, C#, Java and Ruby. I wanted to use args.js for validating method parameters. The licenses field in package.json is missing. Can you please update it?

cleaner api

i think parsing a docblock-like string could make for a much nicer to read/write api:

var args = parse(arguments, 'event String, [properties Object], [fn Function]');

and you could even add default args back in with a special syntax if you wanted to. maybe a comma: '[steps Number, 8]' of course then you'd need to make sure to cast it into the right thing

anyways, was just a thought i had. feel free to close after reading

Argument groups not work as expected

Hi. I have the following function:

function show() {
    var args = Args([
        [
            {element:Args.OBJECT, _type:Element},
            {message:Args.STRING}
        ],
        {title:Args.STRING|Args.Optional},
        {fixed:Args.BOOL|Args.Optional, _default:false}
    ], arguments);

    //show something ...
}

And I expect all these should work:

show('message', 'title', true); //works
show('message', 'title'); //works
show('message'); //works too :D

var el = document.createElement('div');
show(el); //not working :(

The last line of code throw this error:

Uncaught Error: Argument 0 is null or undefined but it must be not null.

I am using the latest version of args-js (0.10.7).

Certain argument configurations unsupported?

In the following example, it doesn't seem to be able to differentiate between the filter and options, which makes some sense, however, passing in named options also throws.

function whatever(key, room, filter, options) {
  var a = new Args([
    { key: Args.OBJECT | Args.STRING | Args.Required },
    { room: Args.STRING | Args.Optional },
    { filter: Args.OBJECT | Args.Optional, _default: {} },
    { options: Args.OBJECT | Args.Required }
  ], arguments);
}

Objects in named arguments in argument group not working as expected

I've been trying to do the following:

function getAccessToken() {
    const args = Args([
        // Argument group, any one of the 3 parameters can be used.
        [
            { userId:        Args.STRING },
            { accessToken:   Args.STRING },
            { user:          Args.OBJECT },
        ],
    ], arguments);

    console.log(args);
}

const userObject = { _id: 123, name: "User Name" };
getAccessToken({ user: userObject });

I would expect the arguments to be:

{ user: { _id: 123, name: 'User Name' } }

But instead I'm getting:

{ user: { user: { _id: 123, name: 'User Name' } } }

Indeed, not using an argument group returns the correct response. I would believe it is because by using named arguments, arguments[0] is an object which is then parsed as a user argument (in the argument group), hence resulting in the incorrect response.

Is this a bug, or is there an option to make args.js only use named arguments, to avoid this problem? Thank you very much.

Inconsistency on named arguments

There's a inconsistency on named arguments.

On http://autographer.github.io/args.js/ says that the following code works, but it throws an exception.

function myFunc() {
    var args = Args([
        {title:       Args.STRING | Args.Required},
        {description: Args.STRING | Args.Optional},
        {rating:      Args.INT    | Args.Optional}
    ], arguments);
}
// or
myFunc({
    title: "Frankenstein",
    description: "A book about monsters",
    rating: 5
});
Error: Argument 0 (title) should be type String, but it was type object with value [object Object].

It only works when we specify the required param as argument 0.

What happens with decimals?

If i call a function requiring Args.INT passing for example 1.2, it throws exception.

Uncaught Error: Argument 0 (price) should be type Int, but it was type number with value 1.2.

Avoid or-ing integer constants

Or-ing integer constants is less type safe and limits extensibility. How about the following signature?

var myIntCheck = {
    isMember: function (x) {
        return Math.floor(x) === x;
    }
};
var args = Args([
    { arg: 'elements',  type: Array },
    { arg: 'qualifier', type: Function },
    { arg: 'node',      type: Node },
    { arg: 'regex',     type: 'string' },
    { arg: 'index1',    type: 'number', default: 0 },
    { arg: 'index2',    type: myIntCheck, optional: true }
], arguments);

For objects, you can use constructors to type-check, for primitive values, you’d use the results of typeof. myIntCheck demonstrates how you could keep things extensible. An alternative would be to use functions whose property prototype is deleted (to distinguish them from constructors) that return true if their arguments have the correct type.

optional: false would be the default; if there is a property default then that implies that the parameter is optional.

Lastly, support for options objects (“named parameters”) would be nice to have.

instanceof giving false negatives for arrays

From dmfay/massive-js#173

I'm afraid it's a something of an ordeal to set up the conditions necessary to reproduce the problem -- install Postgres and Massive, set up the test database, open the REPL from the test directory, and invoke db.productByName(['Product 1', 'Product 2'], console.log); -- but switching from instanceof to Array.isArray for array detection seems to resolve it completely.

Update homepage

Include example for _check: function() {} and explain precedence and ambiguity resolution.

Ambiguous arguments

Say we have a scheme definition:

[
  {a: Args.STRING},
  {b: Args.STRING}
]

And an argument list:

["string1", {a: "string2"}]

We can either have a match "string1" and b becomes undefined or a match "string2" and b match "string1".

I think this is basically a question of precedence for named arguments. I'm inclined to say named arguments should have precedence and should be used before and order based arguments.

Args.Optional + _check not throwing exception

The following code:

function foo() {
    let args = Args([
        {url:Args.STRING|Args.Optional, _check:(url) => url.match(/^\w+\:\/\//)}
    ], arguments);
    ...
}

expect foo('bar') to throw an exception because _check returns null (not true).
actually no exception is throw and args.url === null.

But if url is an Args.Required, then the code works as expected.

suggested enhancement

How about triggering the error if types mismatch only if certain custom function (maybe the function can return a promise instead of returning directly ) returns true . for ex apps might be want to trigger exceptions in dev mode only.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.