Code Monkey home page Code Monkey logo

cocktail's Introduction

Cocktail JS

Build Status npm version bitHound Score Code Climate

Cocktail is a small but yet powerful library with very simple principles:

  • Reuse code
  • Keep it simple

Reuse code

Cocktail explores three mechanisms to share/reuse/mix code:

  • Extends: OOP inheritance implemented in Javascript.
  • Traits: Traits are composable behavior units that can be added to a Class.
  • Talents: Same idea as Traits but applied to instances of a Class.

Keep it simple

Cocktail has only one public method cocktail.mix() but it relies on annotations to tag some meta-data that describe the mix.

Annotations

Annotations are simple meta-data Cocktail uses to perform some tasks over the given mix. They become part of the process but usually they are not kept in the result of a mix.

	var cocktail = require('cocktail'),
		MyClass  = function(){};

	cocktail.mix(MyClass, {
		'@properties': {
			name: 'default name'
		}
	});

In the example above we created a "Class" named MyClass, and we use the @properties annotation to create the property name and the corresponding setName and getName methods.

As it was mentioned before, annotations are meta-data, which means that they are not part of MyClass or its prototype.

Defining a Class / Module

Using cocktail to define a class is easy and elegant.

var cocktail = require('cocktail');

cocktail.mix({
	'@exports': module,
	'@as': 'class',

	'@properties': {
		name: 'default name'
	},

	constructor: function(name){
		this.setName(name);
	},

	sayHello: function() {
		return 'Hello, my name is ' + this.getName();
	}
});

In this example our class definition uses @exports to tell the mix we want to export the result in the module.exports and @as tells it is a class.

Traits

Traits are Composable Units of Behaviour (You can read more from this paper). Basically, a Trait is a Class, but a special type of Class that has only behaviour (methods) and no state. Traits are an alternative to reuse behaviour in a more predictable manner. They are more robust than Mixins, or Multiple Inheritance since name collisions must be solved by the developer beforehand. If you compose your class with one or more Traits and you have a method defined in more than one place, your program will fail giving no magic rule or any kind of precedence definition.

Enumerable.js

var cocktail = require('cocktail');

cocktail.mix({
	'@exports': module,
	'@as': 'class',

	'@requires': ['getItems'],

	first: function() {
		var items = this.getItems();
		return items[0] || null;
	},

	last: function() {
		var items = this.getItems(),
			l = items.length;
		return items[l-1];
	}

});

The class above is a Trait declaration for an Enumerable functionality. In this case we only defined first and last methods to retrieve the corresponding elements from an array retrieved by getItems methods.

List.js

var cocktail = require('cocktail'),
	Enumerable = require('./Enumerable');

cocktail.mix({
	'@exports': module,
	'@as': 'class',
	'@traits': [Enumerable],

	'@properties': {
		items: undefined
	},

	'@static': {
		/* factory method*/
		create: function(options) {
			var List = this;
			return new List(options);
		}
	},

	constructor: function (options) {
		this.items = options.items || [];
	}
});

The List class uses the Enumerable Trait, the getItems is defined by the @properties annotation.

index.js

var List = require('./List'),
	myArr = ['one', 'two', 'three'],
	myList;

myList = List.create({items: myArr});

console.log(myList.first()); // 'one'
console.log(myList.last());  // 'three'

Talents

Talents are very similar to Traits, in fact a Trait can be applied as a Talent in CocktailJS. The main difference is that a Talent can be applied to an object or module. So we can define a Talent as a Dynamically Composable Unit of Reuse (you can read more from this paper).

Using the Enumerable example, we can use a Trait as a Talent.

index.js

var cocktail = require('cocktail'),
    enumerable = require('./Enumerable'),
	myArr;

myArr = ['one', 'two', 'three'];

cocktail.mix(myArr, {
    '@talents': [enumerable],

	/* glue code for enumerable talent*/
    getItems: function () {
        return this;
    }
});

console.log(myArr.first());  // 'one'
console.log(myArr.last());   // 'three'

We can also create a new Talent to define the getItems method for an Array to retrive the current instance.

ArrayAsItems.js

var cocktail = require('cocktail');

cocktail.mix({
    '@exports': module,
    '@as': 'class',

    getItems: function () {
        return this;
    }
});

And then use it with Enumerable:

var cocktail     = require('cocktail'),
	enumerable   = require('./Enumerable'),
	arrayAsItems = require('./ArrayAsItems');

var myArr = ['one', 'two', 'three'];

cocktail.mix(myArr, { '@talents': [enumerable, arrayAsItems] });

console.log(myArr.first());  // 'one'
console.log(myArr.last());   // 'three'

Getting Started

  • Install the module with: npm install cocktail or add cocktail to your package.json and then npm install
  • Start playing by just adding a var cocktail = require('cocktail') in your file.

Guides

Guides can be found at CocktailJS Guides

Documentation

The latest documentation is published at CocktailJS Documentation

Examples

A Cocktail playground can be found in cocktail recipes repo.

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality.

Running Lint & Tests

Add your unit and/or integration tests and execute

$ npm test

Run unit tests

$npm run unit

Run integration tests

$npm run integration 

Lint your code

$ npm run lint

Before Commiting

Run npm test to check lint and execute tests

$ npm test

Check test code coverage with instanbul

$ npm run coverage

Release History

see CHANGELOG

License

Copyright (c) 2013 - 2016 Maximiliano Fierro
Licensed under the MIT license.

cocktail's People

Contributors

elmasse 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

Watchers

 avatar  avatar  avatar  avatar

cocktail's Issues

Recursive loop when nesting callSuper() (call stack exceeded)

Got myself in some trouble when trying to extend a few classes.
And since the proof is in eating the pudding, here's some code:

  • Abstract class Algorithm
cocktail.mix({
    '@exports': module,
    '@as': 'class',
    '@traits': [AlgorithmInterface],
    '@logger' : [console, "Algorithm Base:"],

    constructor: function() {
      //Should be initialized by some especification of this class.
      this._victims = undefined;
      this._requirements = undefined;
      this._finalized = new Queue();
      this._filters = [];
    },

    initialize: function(requirements) {
      this._requirements = requirements;
      this._finalized = new Queue();
    }
});
  • Concrete base class Fifo
cocktail.mix({
    '@exports': module,
    '@as': 'class',
    '@extends': Algorithm,
    '@traits': [AlgorithmInterface],
    '@logger' : [console, "Algorithm Fifo:"],

    constructor: function() {
      this.callSuper("constructor");
      this._victims = new Queue();
      this.log("Created.");
    },

    initialize: function(requirements) {
      this.callSuper("initialize", requirements);
      this._victims = new Queue();
    }
});
  • Most derived class, LRU
cocktail.mix({
    '@exports': module,
    '@as': 'class',
    '@extends': Fifo,
    '@traits': [AlgorithmInterface],
    '@logger' : [console, "Algorithm Lru:"],

    constructor: function() {
      this.callSuper("constructor");
      this._victims = new ReQueueQueue();
      this.log("Created.");
    },

    initialize: function(requirements) {
      this.callSuper("initialize", requirements);
      this._victims = new ReQueueQueue();
    }
});

As you can see, there are 2 chains of callSuper methods, one in the constructor call, the other in the initialize method call, but the call only starts looping when initialize is called.

Refactor Cocktail test helper methods

Move:

  • restoreDefaultProcessors()
  • clearProcessors()

methods form Cocktail into a Test Helper Trait/Talent and refactor integration test to mix the Cocktail test instance to add the helper methods.

Add '@static' annotation to define static properties and functions on a class

The '@static' annotation should be able to define properties and methods that will be attached to the class as class methods and properties:

  • implement properties
  • implement methods
  • implement static reference from static methods
  • implement static reference from object deferred for a future release to analyse if it is necessary
var Cocktail = require('Cocktail'),
      Class;

Class = Cocktail.mix({
   '@static': {
        value: 'someValue',

        someStaticMethod: function(){return this.value;} // <- this should be referencing the Class
   }
});

console.log(Class.value); // 'someValue'
console.log(Class.someStaticMethod()); // 'someValue'

Add and test @exports annotation

The @exports annotation should accept the module as a parameter and export the current mix as module.exports.

Cocktail.mix(MyClass, {
    '@exports': module,
     //.....
     someFunc: function(){}
});

This will avoid to do:

module.exports = MyClass;

Trait aliases not being applied correctly

When composing a TraitA with TraitB both having same method definition 'methA', when aliasing TraitA 'methA' on TraitB a same method definition error is thrown.

cocktail.mix({
   //...
   '@traits': [
       {
           trait: TraitA,
           alias: {methA: 'methodA'}
       }
   ],

    methA: function(){/**/}
});

change examples and docs to use lowercase module name

In Linux OS the filesystem is case sensitive. The module is declared as 'cocktail' and then having a require('Cocktail') will fail.

Rename Cocktail in favor of cocktail in all docs, examples, guides, etc.

  • lib/Cocktail -> lib/cocktail
  • Tests
  • Docs
  • Guides
  • Home Page
  • recipes repo
  • Readme file

@properties: When subject is an Object do not override value if property is already defined in subject.

The default value defined in properties annotation should not override the value if subject is an object and there is a property already defined with the same name:

var o1 = {anyProp: 'any'};

cocktail.mix(o1, {
    '@properties': {
        propName: 'default'
    }
});

o1.getPropName(); // default
o1.propName; /// default

var o2 = {propName: 'defined'};

cocktail.mix(o2, {
    '@properties': {
        propName: 'default'
    }
});

o2.getPropName(); // defined
o2.propName; /// defined

Arrays, Dates and plain Objects properties defined in @properties should be cloned

When defining a [], {} or a Date inside the @properties annotation those should be cloned when read/assign into the class instance.

Since they are assigned to the Class.prototype, this causes all instances to use the same value from prototype if it was not assigned into constructor or via setter.

Even though it can be solved by setting default values in construction time, only for properties in @properties we want to avoid this issue.

Add single parameter class/trait definition

The single parameter class/trait definition will work when the parameter subject has any of the following annotations:

  • extends
  • traits
  • annotation
  • requires
  • Or has a constructor method
Cocktail.mix({

   constructor: function(params) {/*body*/},

    someAwesomeFun: function(){/*body*/}
});

Refactor '@annotation' procesor

Annotation processor is not working between modules. The method cocktail.use() has been added - see #16 - and Annotation processor should be refactored to add a name property to the Processor prototype adding the annotation symbol.

Have you considered AOP support?

Hi,

just came across CoctailJS - nice job!

Right away, though, I thought - wouldn't it be nice if it also supported AOP. Anyway, it is also kind of a cross-cutting "trait" that you would like to maintain separately and not pollute your nice little classes with logging etc.

So, the question is - have you been considering adding AOP support using some nice annotations like:

@before : {
    'get.*' : function (methodName, args) {
         console.log("Method " + methodName + " going to be called with args:", args)     
    }
}

Similarly for @after and @around.

Any thoughts?

Vilem

Make cocktail work in requirejs environment

Hi,
I am having a hard time getting cocktail to work with requirejs. I thought I just wrap it up into the usual

if (typeof define === 'function' && define.amd) {
    define(["require" ], function (require){
        return factory(require('../sequence'));
    });
} else if (typeof module !== 'undefined' && module.exports) {
    module.exports = factory(require('../sequence'));
}

But I always hit a wall with the relative path configurations. It is really hard to debug this problem. I thought I patch cocktail to submit a pull request but I can not get it to work. For now I will try to use browserify but it would be nice to have cocktailjs be compatible with the most common module loaders.

@talents should be applied as static method when defined in a class

The @talent annotation should be applied differently when it is applied to a Class definition. The method defined in the talent should be part of the function as a property and not as a part of the prototype as it should be the case with @trait

Example:

cocktail.mix({
  '@exports': module,
  '@as'       : 'class',

  '@talents': [Create],  // 1
  '@traits'   : [Configurable] // 2

});

In case (1) the methods defined in Create talent should be added as static methods of the class. In (2) the Configurable behaviour should be added to the class prototype.

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.