Soyez le premier à donner votre avis sur cette source.
Snippet vu 6 974 fois - Téléchargée 15 fois
/******************************************************************************* * Title: Enum.js * Description:_ * Enum for JS. * * This class implements the Enum type as an Object's concrete type. * In fact, it is more a bypass to simulate the Enum paradigm than a real * implementation. * * By creating a new Enum object, each element of the enumeration is seen as * as an object (of type EnumItem) and not as a String or a number (like some * simple implementation). The static function 'compare' (a masquerade for to * ease the use of 'comparTo') act as a deep equality (identity). * * Example:_ * Type = new Enum('type1', 'type2', 'type3'); // init * Enum.compare(Type.type1, Type.type2); // return false * Type.type1 = ... // has no effect * Type.type1 // return an object of type 'EnumItem' * * Author: Thierry SORG a.k.a TriumpHS * E-mail: triumphs @ devmen.net * Date: 03.02.12 (EU date format) * * Revision date: 30.08.2012 (EU date format) function Enum(){ // Class of each item (useful for the identity operation of 'compareTo') EnumItem = function(label){ var label = label; // this.compareTo = function(t){ return this === t; }; // this.toString = function(){ return label }; Object.defineProperty(this, 'compareTo',{ value : function(t){ return this === t; } }); Object.defineProperty(this, 'toString',{ value : function(){ return label; } }); }; // PRIVATE CLASS: EnumElmt //if(arguments.length == 0) throw new Error('Empty enumeration.'); var labels = new Array(); // for optional method toArray var items = {}; var addItem = function(label){ items[label] = new EnumItem(label); } var getInstance = function(label){ return items[label]; } if(arguments.length == 1) labels = Array.prototype.slice.call(arguments[0]); else labels = Array.prototype.slice.call(arguments); labels.forEach(function(e, i, l){ addItem(e); Object.defineProperty(this,e,{value : getInstance(e) }); }, this); Object.defineProperties(this, { 'valueOf':{value : function(label){ return items[label]; } }, 'toArray': // Optional methods {value : function(){ return Array.prototype.slice.call(labels); } }, 'hasItem': // Optional methods {value : function(e){ return getInstance(e.toString())!= undefined; } } }); };// CLASS: Enum Enum.compare = function(t1, t2){ try{ return t1.compareTo(t2); } catch(ignored){ return false;} }; // STATIC FUNCTION: Enum.compare
Explications claire à la clé. Merci!
Et en plus je peux le mettre direct dans mon code directement. La fonction static compare, sa fait comme en java. Trop cool.
Baz
Beau travail. Merci!
Vous n'êtes pas encore membre ?
inscrivez-vous, c'est gratuit et ça prend moins d'une minute !
Les membres obtiennent plus de réponses que les utilisateurs anonymes.
Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.
Le fait d'être membre vous permet d'avoir des options supplémentaires.