model/binding/BindingList.js

/**
 * @copyright 2023 Tridium, Inc. All Rights Reserved.
 */

/**
 * API Status: **Development**
 * @module bajaux/model/binding/BindingList
 */
define([ 'Promise' ], function (Promise) {

  'use strict';

  /**
   * Data structure for storing a collection of Bindings.
   * @class
   * @alias module:bajaux/model/binding/BindingList
   */
  return class BindingList {
    constructor(bindings = []) {
      this.$setNewBindingsArray(bindings);
    }

    /**
     * @returns {Array.<module:bajaux/model/binding/IBinding>}
     */
    getBindings() {
      return this.$bindings.slice();
    }

    /**
     * Saves all bindings.
     * @returns {Promise}
     */
    saveAll() {
      return Promise.all(this.$bindings.map((b) => b.save()));
    }

    /**
     * Run an (optionally async) function against each binding in the list.
     * All function calls will run in serial, not parallel.
     * @param {Function} func function to receive the binding and the index in
     * the binding array
     * @returns {Promise.<Array.<*>>} results of each function call
     */
    map(func) {
      const results = [];
      return this.$bindings.reduce(
        (prom, b, i) => prom.then(() => func(b, i)).then((r) => results.push(r)),
        Promise.resolve())
        .then(() => results);
    }

    /**
     * @private
     * @param {Array.<module:bajaux/model/binding/IBinding>} bindings 
     */
    $setNewBindingsArray(bindings) {
      this.$bindings = bindings;
      bindings.forEach((binding) => {
        binding.$bindingList = this;
      });
    }
  };
});