Giter Site home page Giter Site logo

brototype's Introduction

build status Codacy Badge Code Climate bitHound Score

brototype

Bro, do you even javascript?

Features

You've got a deeply-nested set of objects that may or may not always be there. We've all seen something like this: var myURL = app.config.environment.buildURL('dev'); which leads to one of our favorite javascript errors... error: undefined is not a function

And the solution only makes the code base ugly:

var myURL;
if (app && app.config && app.config.environment && app.config.environment.buildURL) {
    myURL = app.config.environment.buildURL('dev');
}

We all hate that, don't we?

So what if you could just type:

var myURL;
if (Bro(app).doYouEven('config.environment.buildURL')) {
    myURL = app.config.environment.buildURL('dev');
}

Or better yet, how about:

var myURL;
Bro(app)
    .iDontAlways('config.environment.buildURL')
    .butWhenIdo(function(buildURL){
        myURL = buildURL('dev');
    });

Well, now you can!

But what if you have something like this:

app['soap:Envelope']['soap:Body'][0].getResponse[0]['rval'][0].customerId[0]

We got you covered.

if (Bro(app).doYouEven("soap:Envelope.soap:Body.0.getResponse.0.rval.0.customerId.0")) {
    var thisVar = app['soap:Envelope']['soap:Body'][0].getResponse[0]['rval'][0].customerId[0];
}

Features

Testing nested members

if(Bro(object).doYouEven('lift') === Bro.TOTALLY) {
    console.log(object.lift);
}

Or, ensure that multiple nested members exist by passing an array of paths

if (Bro(object)
    .doYouEven(['property.one', 'property.two']) {
    // returns true if all referenced properties exist
    console.log(object.property.one, object.property.two);
})

Or, just use a callback...

Bro(object)
    .doYouEven('property.subproperty', function(subproperty) {
        console.log(subproperty);
    });

Fetching nested members

// get a value if it exists
var value = Bro(object).iCanHaz('cheezeburger');

// get an array of values for paths that exist
var values = Bro(object).iCanHaz(['cheezeburger', 'money', 'beer']);

Creating nested members

// add properties to an object
Bro(object).makeItHappen('cheezeburger.with.pickles');
// set a deeply nested property by the Bro string
Bro(object).makeItHappen('bro.props', 'high five');  // object.bro.props = 'high five'

Calling nested functions

Bro(object)
    .iDontAlways('method')
    .butWhenIdo(function(returnVal) {
        console.log('object.method() returned ', returnVal);
    });

Handling exceptions

Bro(object)
    .braceYourself('method.name')
    .hereComeTheErrors(function(e) {
        console.log('error ' + e + ' happened.');
    });

Bro-oleans

Bro.TOTALLY // true;
Bro.NOWAY   // false;

Check for undefined

if (Bro(someVar).isThatEvenAThing() === Bro.TOTALLY) {
    // do stuff
}

Get a list of object keys

var object = {foo: 1, bar: 2};
Bro(object).giveMeProps();
// returns ['foo', 'bar'];

Extending objects

var obj1 = {foo: 'boo', bar: 'bar'},
    obj2 = {foo: 'bar', yes: 'no'};
Bro(obj1).comeAtMe(obj2);

// now obj1.foo == 'bar' and obj1.yes == 'no'

Extending Brototype!

Yes, extend me, Bro!

var plugin = { foo: function() { whatever; }};
Bro.prototype.comeAtMe(plugin);

Installing

brototype is available via npm or bower

# via npm
$ npm install brototype

# via bower
$ bower install brototype

Contributing

Brototype.js may be funny, but it is also quite useful, as demonstrated by the number of people who have already installed it via npm.

Therefore, there is some responsibility to add/update the library responsibly. Please have a look at the guidelines for contributing to Brototype before submitting your pull request.

Bro-tie

For the brofessional. Want to use Brototype.js but it's too bro for your work environment? Just give it the Bro-tie treatment so you can bro down at the office! Alias some or all of the names to make your boss happy.

Do you even Brototype?

Are you using Brototype in the wild? If so, tell the world!

Also, don't forget to follow @BrototypeJS on Twitter!

Author

Randy Hunt

License

The MIT License

Copyright © 2014

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.

brototype's People

Contributors

adjohu avatar brandonscript avatar computmaxer avatar kkirsche avatar letsgetrandy avatar mehulatl avatar nchase avatar patrickjs avatar plloi avatar therebelrobot avatar ttaylorr avatar wx-ps avatar

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  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

brototype's Issues

.butIfIdont? for .iDontAlways.butWhenIdo

Bro(app)
    .iDontAlways('config.environment.buildURL')
    .butWhenIdo(function(buildURL){
        myURL = buildURL('dev');
    });

This is awesome, but sometimes it's great to not have to check the property again to handle an 'else' exception. Something like:

Bro(app)
    .iDontAlways('config.environment.buildURL')
    .butWhenIdo(function(buildURL){
        myURL = buildURL('dev');
    })
    .butIfIdont(function() {
        // do other stuff
    });

Tried to wire in something like this, but it blew up when trying to add in the fallback function.

Looks like `doYouEven()` doesn't support callback functions anymore

Looking at this example, the callback for subproperty is never called, though the readme suggests that it should work? I don't think this is related to #47, because looking at the commit history, before there was no options at all, and after optionsBro was added (which, does what exactly?), there's still no support for callback.

var Bro = require("brototype")

var object = {
    property: {
         subproperty: "foo"
    }
}

Bro(object)
    .doYouEven('property.subproperty', function(subproperty) {
        console.log('subproperty: ', subproperty);
    });

If you like, I can look into implementing this, but I'm skeptical that I'll implement it the way you guys want? Here's a test that should pass if it works:

it('should pass the nested property to a callback function', function(done) {
        var a = {
            foo: 'bar'
        }
        Bro(a).doYouEven('foo', function(foo) {
            assert.equal(foo, 'bar');
            done();
        })
    });

butWhenIdo

Took me awhile to realize this bro, .butWhenIdo is not consistently camelCased (do is lowercase when it should be uppercase). You should totally fix that, or add a note to the readme pointing it out.

Feature Request: Bro.pwn()

I wish there was a function Bro.pwn which deletes a key in an object. Like so:

Bro(object).pwn('key')

Clarification on iDontAlways/doYouEven

In this readme, these two examples are provided:

Intro

var myURL;
Bro(app)
    .iDontAlways('config.environment.buildURL')
    .butWhenIdo(function(buildURL){
        myURL = buildURL('dev');
    });

Calling nested functions

Bro(object)
    .iDontAlways('method')
    .butWhenIdo(function(returnVal) {
        console.log('object.method() returned ', returnVal);
    });

As far as I can tell, both are functionally identical and call a nested method. In the first example, the function is passed as a callback inside butWhenIdo and then called, whereas in the second example, the return value of the function is passed.

Looking at the code, this looks like the pertinent section:

if (returnValue) {
    (callback || function(){}).call(context || this.object, returnValue);
}

Am I correct in interpreting this that if the nested function returns a value, the return value is passed to the callback, and if it does not return a value, the function is passed to the callback?

If so, that seems like it may be of risky design - you're equally likely to call the function twice by accident as you are to expect it to be a function and instead have it be the returned value? If not, perhaps the readme can be improved to clarify the behavior?

Bro, do you even use Brototype?

Yo, Bro... are you using Brototype in the wild? If so, drop a comment in here so we can tell the world about how awesome it is!

Brace Yourself...

Here come the errors:

  1. Open a web browser
  2. Copy Brototype.js source
  3. Paste into console
  4. Console returns error:
    ReferenceError: exports is not defined

Expect conditionals to handle this error by falling back to window

Crashed on doYouEven with null

Hello, i created a small util for app

export const hasIn = (obj = {}, path) => {
  return bro(obj).doYouEven(path);
};

Then i try this code:

!hasIn(post, 'test.0.test')

post isn't undefined, post = { test: null }
After i have the message in console with text:

Cannot read property '0' of null

Can you help me resolve this problem?

Making .iCanHaz() recursive

iCanHaz() could be made to work recursively. Currently:

var rentProblems = {
  the: {
    rent: 'is too damn high'
  }
};
Bro( rentProblems ).iCanHaz( 'rent' );
// -> rent is not defined

It might be useful to allow the user to pass in a recursive boolean argument to search an entire object for a key, like:

Bro( rentProblems ).iCanHaz( 'rent', Bro.TOTALLY );
// -> 'is too damn high'
// or return an array of full paths that match the key and allow the user to decide when to get the value from the path:
// -> [rentProblems.the.rent]

angular support?

I finally got it working.

I got rid of the module pattern on one of my projects, and it now works as an angular module that provides a service, as well as in node and amd. See https://github.com/deltreey/wildstring/blob/master/wildstring.js

I use brototype with angular, which requires me to use $window and if I have it as a module dependency it doesn't get listed, which is also ugly. I'm wondering if you'd be amicable to me doing a similar pattern here. I'll attach a pull request from a branch I'll make.

I got the idea from here http://snook.ca/archives/javascript/no-love-for-module-pattern if you're interested. I love how clean and easy to read brototype's code is and I think this will make it even easier to understand.

Publish on npm

Please publish this package on npm. We actually want to use it :)

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.