baja/tag/RelationSet.js

/**
 * @copyright 2015 Tridium, Inc. All Rights Reserved.
 * @author Gareth Johnson
 */

/**
 * @module baja/tag/RelationSet
 */
define([ "bajaScript/sys",
        "bajaScript/baja/tag/Id" ], function (
        baja,
        Id) {
  
  "use strict";
     
  /**
   * Relations is used to store a collection of relation objects. A relations collection
   * is semantically equivalent to a mathematical set: it is an unordered collection of
   * distinct Relation objects.
   *
   * @class
   * @alias module:baja/tag/RelationSet
   *
   * @param {Array<module:baja/tag/Relation>} relations 
   * An array of relation objects.
   */  
  var RelationSet = function RelationSet(relations) {
    this.$relations = relations || [];
  };

  /**
   * Return an array of all of the relations objects.
   *
   * @param {String|module:baja/tag/Id} id The id or qname of the
   * Relation. If not defined, the relations will be returned.
   * @returns {Array<module:baja/tag/Relation>} An array of Relations.
   */
  RelationSet.prototype.getAll = function (id) {
    var array,
        relations = this.$relations,
        i;
        
    if (id) {
      id = typeof id === "string" ? new Id(id) : id;

      array = [];
      for (i = 0; i < relations.length; ++i) {
        if (relations[i].getId().equals(id)) {
          array.push(relations[i]);
        }
      }
    } else {
      array = Array.prototype.slice.call(relations);
    }

    return array;
  };

  /**
   * Return true if there are no relation objects.
   * 
   * @returns {Boolean} 
   */
  RelationSet.prototype.isEmpty = function () {
    return this.$relations.length === 0;
  };

  /**
   * Return a relation object for the specified id and entity.
   * 
   * @param {String|module:baja/tag/Id} id The id or qname of the
   * Relation.
   * @param {String|baja.Ord} [entityOrd] The Entity ORD we're looking for.
   * If this isn't defined, the first matching relation with specified tag is 
   * returned.
   * @returns module:baja/tag/Relation The relation object or null
   * if the relation can't be found.
   */
  RelationSet.prototype.get = function (id, entityOrd) {
    var i,
        relations = this.$relations;

    id = typeof id === "string" ? new Id(id) : id;

    for (i = 0; i < relations.length; ++i) {
      if (relations[i].getId().equals(id) && 
          (entityOrd ? relations[i].getEndpointOrd().toString() === entityOrd.toString() : true)) {
        return relations[i];
      }
    }

    return null;
  };

  return RelationSet;
});