vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

998 lines
26 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. var util = require('./util');
  2. var Queue = require('./Queue');
  3. /**
  4. * DataSet
  5. *
  6. * Usage:
  7. * var dataSet = new DataSet({
  8. * fieldId: '_id',
  9. * type: {
  10. * // ...
  11. * }
  12. * });
  13. *
  14. * dataSet.add(item);
  15. * dataSet.add(data);
  16. * dataSet.update(item);
  17. * dataSet.update(data);
  18. * dataSet.remove(id);
  19. * dataSet.remove(ids);
  20. * var data = dataSet.get();
  21. * var data = dataSet.get(id);
  22. * var data = dataSet.get(ids);
  23. * var data = dataSet.get(ids, options, data);
  24. * dataSet.clear();
  25. *
  26. * A data set can:
  27. * - add/remove/update data
  28. * - gives triggers upon changes in the data
  29. * - can import/export data in various data formats
  30. *
  31. * @param {Array | DataTable} [data] Optional array with initial data
  32. * @param {Object} [options] Available options:
  33. * {String} fieldId Field name of the id in the
  34. * items, 'id' by default.
  35. * {Object.<String, String} type
  36. * A map with field names as key,
  37. * and the field type as value.
  38. * {Object} queue Queue changes to the DataSet,
  39. * flush them all at once.
  40. * Queue options:
  41. * - {number} delay Delay in ms, null by default
  42. * - {number} max Maximum number of entries in the queue, Infinity by default
  43. * @constructor DataSet
  44. */
  45. // TODO: add a DataSet constructor DataSet(data, options)
  46. function DataSet (data, options) {
  47. // correctly read optional arguments
  48. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  49. options = data;
  50. data = null;
  51. }
  52. this._options = options || {};
  53. this._data = {}; // map with data indexed by id
  54. this.length = 0; // number of items in the DataSet
  55. this._fieldId = this._options.fieldId || 'id'; // name of the field containing id
  56. this._type = {}; // internal field types (NOTE: this can differ from this._options.type)
  57. // all variants of a Date are internally stored as Date, so we can convert
  58. // from everything to everything (also from ISODate to Number for example)
  59. if (this._options.type) {
  60. for (var field in this._options.type) {
  61. if (this._options.type.hasOwnProperty(field)) {
  62. var value = this._options.type[field];
  63. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  64. this._type[field] = 'Date';
  65. }
  66. else {
  67. this._type[field] = value;
  68. }
  69. }
  70. }
  71. }
  72. // TODO: deprecated since version 1.1.1 (or 2.0.0?)
  73. if (this._options.convert) {
  74. throw new Error('Option "convert" is deprecated. Use "type" instead.');
  75. }
  76. this._subscribers = {}; // event subscribers
  77. // add initial data when provided
  78. if (data) {
  79. this.add(data);
  80. }
  81. this.setOptions(options);
  82. }
  83. /**
  84. * @param {Object} [options] Available options:
  85. * {Object} queue Queue changes to the DataSet,
  86. * flush them all at once.
  87. * Queue options:
  88. * - {number} delay Delay in ms, null by default
  89. * - {number} max Maximum number of entries in the queue, Infinity by default
  90. * @param options
  91. */
  92. DataSet.prototype.setOptions = function(options) {
  93. if (options && options.queue !== undefined) {
  94. if (options.queue === false) {
  95. // delete queue if loaded
  96. if (this._queue) {
  97. this._queue.destroy();
  98. delete this._queue;
  99. }
  100. }
  101. else {
  102. // create queue and update its options
  103. if (!this._queue) {
  104. this._queue = Queue.extend(this, {
  105. replace: ['add', 'update', 'remove']
  106. });
  107. }
  108. if (typeof options.queue === 'object') {
  109. this._queue.setOptions(options.queue);
  110. }
  111. }
  112. }
  113. };
  114. /**
  115. * Subscribe to an event, add an event listener
  116. * @param {String} event Event name. Available events: 'put', 'update',
  117. * 'remove'
  118. * @param {function} callback Callback method. Called with three parameters:
  119. * {String} event
  120. * {Object | null} params
  121. * {String | Number} senderId
  122. */
  123. DataSet.prototype.on = function(event, callback) {
  124. var subscribers = this._subscribers[event];
  125. if (!subscribers) {
  126. subscribers = [];
  127. this._subscribers[event] = subscribers;
  128. }
  129. subscribers.push({
  130. callback: callback
  131. });
  132. };
  133. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  134. DataSet.prototype.subscribe = DataSet.prototype.on;
  135. /**
  136. * Unsubscribe from an event, remove an event listener
  137. * @param {String} event
  138. * @param {function} callback
  139. */
  140. DataSet.prototype.off = function(event, callback) {
  141. var subscribers = this._subscribers[event];
  142. if (subscribers) {
  143. this._subscribers[event] = subscribers.filter(function (listener) {
  144. return (listener.callback != callback);
  145. });
  146. }
  147. };
  148. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  149. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  150. /**
  151. * Trigger an event
  152. * @param {String} event
  153. * @param {Object | null} params
  154. * @param {String} [senderId] Optional id of the sender.
  155. * @private
  156. */
  157. DataSet.prototype._trigger = function (event, params, senderId) {
  158. if (event == '*') {
  159. throw new Error('Cannot trigger event *');
  160. }
  161. var subscribers = [];
  162. if (event in this._subscribers) {
  163. subscribers = subscribers.concat(this._subscribers[event]);
  164. }
  165. if ('*' in this._subscribers) {
  166. subscribers = subscribers.concat(this._subscribers['*']);
  167. }
  168. for (var i = 0; i < subscribers.length; i++) {
  169. var subscriber = subscribers[i];
  170. if (subscriber.callback) {
  171. subscriber.callback(event, params, senderId || null);
  172. }
  173. }
  174. };
  175. /**
  176. * Add data.
  177. * Adding an item will fail when there already is an item with the same id.
  178. * @param {Object | Array | DataTable} data
  179. * @param {String} [senderId] Optional sender id
  180. * @return {Array} addedIds Array with the ids of the added items
  181. */
  182. DataSet.prototype.add = function (data, senderId) {
  183. var addedIds = [],
  184. id,
  185. me = this;
  186. if (Array.isArray(data)) {
  187. // Array
  188. for (var i = 0, len = data.length; i < len; i++) {
  189. id = me._addItem(data[i]);
  190. addedIds.push(id);
  191. }
  192. }
  193. else if (util.isDataTable(data)) {
  194. // Google DataTable
  195. var columns = this._getColumnNames(data);
  196. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  197. var item = {};
  198. for (var col = 0, cols = columns.length; col < cols; col++) {
  199. var field = columns[col];
  200. item[field] = data.getValue(row, col);
  201. }
  202. id = me._addItem(item);
  203. addedIds.push(id);
  204. }
  205. }
  206. else if (data instanceof Object) {
  207. // Single item
  208. id = me._addItem(data);
  209. addedIds.push(id);
  210. }
  211. else {
  212. throw new Error('Unknown dataType');
  213. }
  214. if (addedIds.length) {
  215. this._trigger('add', {items: addedIds}, senderId);
  216. }
  217. return addedIds;
  218. };
  219. /**
  220. * Update existing items. When an item does not exist, it will be created
  221. * @param {Object | Array | DataTable} data
  222. * @param {String} [senderId] Optional sender id
  223. * @return {Array} updatedIds The ids of the added or updated items
  224. */
  225. DataSet.prototype.update = function (data, senderId) {
  226. var addedIds = [];
  227. var updatedIds = [];
  228. var updatedData = [];
  229. var me = this;
  230. var fieldId = me._fieldId;
  231. var addOrUpdate = function (item) {
  232. var id = item[fieldId];
  233. if (me._data[id]) {
  234. // update item
  235. id = me._updateItem(item);
  236. updatedIds.push(id);
  237. updatedData.push(item);
  238. }
  239. else {
  240. // add new item
  241. id = me._addItem(item);
  242. addedIds.push(id);
  243. }
  244. };
  245. if (Array.isArray(data)) {
  246. // Array
  247. for (var i = 0, len = data.length; i < len; i++) {
  248. addOrUpdate(data[i]);
  249. }
  250. }
  251. else if (util.isDataTable(data)) {
  252. // Google DataTable
  253. var columns = this._getColumnNames(data);
  254. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  255. var item = {};
  256. for (var col = 0, cols = columns.length; col < cols; col++) {
  257. var field = columns[col];
  258. item[field] = data.getValue(row, col);
  259. }
  260. addOrUpdate(item);
  261. }
  262. }
  263. else if (data instanceof Object) {
  264. // Single item
  265. addOrUpdate(data);
  266. }
  267. else {
  268. throw new Error('Unknown dataType');
  269. }
  270. if (addedIds.length) {
  271. this._trigger('add', {items: addedIds}, senderId);
  272. }
  273. if (updatedIds.length) {
  274. this._trigger('update', {items: updatedIds, data: updatedData}, senderId);
  275. }
  276. return addedIds.concat(updatedIds);
  277. };
  278. /**
  279. * Get a data item or multiple items.
  280. *
  281. * Usage:
  282. *
  283. * get()
  284. * get(options: Object)
  285. * get(options: Object, data: Array | DataTable)
  286. *
  287. * get(id: Number | String)
  288. * get(id: Number | String, options: Object)
  289. * get(id: Number | String, options: Object, data: Array | DataTable)
  290. *
  291. * get(ids: Number[] | String[])
  292. * get(ids: Number[] | String[], options: Object)
  293. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  294. *
  295. * Where:
  296. *
  297. * {Number | String} id The id of an item
  298. * {Number[] | String{}} ids An array with ids of items
  299. * {Object} options An Object with options. Available options:
  300. * {String} [returnType] Type of data to be
  301. * returned. Can be 'DataTable' or 'Array' (default)
  302. * {Object.<String, String>} [type]
  303. * {String[]} [fields] field names to be returned
  304. * {function} [filter] filter items
  305. * {String | function} [order] Order the items by
  306. * a field name or custom sort function.
  307. * {Array | DataTable} [data] If provided, items will be appended to this
  308. * array or table. Required in case of Google
  309. * DataTable.
  310. *
  311. * @throws Error
  312. */
  313. DataSet.prototype.get = function (args) {
  314. var me = this;
  315. // parse the arguments
  316. var id, ids, options, data;
  317. var firstType = util.getType(arguments[0]);
  318. if (firstType == 'String' || firstType == 'Number') {
  319. // get(id [, options] [, data])
  320. id = arguments[0];
  321. options = arguments[1];
  322. data = arguments[2];
  323. }
  324. else if (firstType == 'Array') {
  325. // get(ids [, options] [, data])
  326. ids = arguments[0];
  327. options = arguments[1];
  328. data = arguments[2];
  329. }
  330. else {
  331. // get([, options] [, data])
  332. options = arguments[0];
  333. data = arguments[1];
  334. }
  335. // determine the return type
  336. var returnType;
  337. if (options && options.returnType) {
  338. var allowedValues = ["DataTable", "Array", "Object"];
  339. returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType;
  340. if (data && (returnType != util.getType(data))) {
  341. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  342. 'does not correspond with specified options.type (' + options.type + ')');
  343. }
  344. if (returnType == 'DataTable' && !util.isDataTable(data)) {
  345. throw new Error('Parameter "data" must be a DataTable ' +
  346. 'when options.type is "DataTable"');
  347. }
  348. }
  349. else if (data) {
  350. returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  351. }
  352. else {
  353. returnType = 'Array';
  354. }
  355. // build options
  356. var type = options && options.type || this._options.type;
  357. var filter = options && options.filter;
  358. var items = [], item, itemId, i, len;
  359. // convert items
  360. if (id != undefined) {
  361. // return a single item
  362. item = me._getItem(id, type);
  363. if (filter && !filter(item)) {
  364. item = null;
  365. }
  366. }
  367. else if (ids != undefined) {
  368. // return a subset of items
  369. for (i = 0, len = ids.length; i < len; i++) {
  370. item = me._getItem(ids[i], type);
  371. if (!filter || filter(item)) {
  372. items.push(item);
  373. }
  374. }
  375. }
  376. else {
  377. // return all items
  378. for (itemId in this._data) {
  379. if (this._data.hasOwnProperty(itemId)) {
  380. item = me._getItem(itemId, type);
  381. if (!filter || filter(item)) {
  382. items.push(item);
  383. }
  384. }
  385. }
  386. }
  387. // order the results
  388. if (options && options.order && id == undefined) {
  389. this._sort(items, options.order);
  390. }
  391. // filter fields of the items
  392. if (options && options.fields) {
  393. var fields = options.fields;
  394. if (id != undefined) {
  395. item = this._filterFields(item, fields);
  396. }
  397. else {
  398. for (i = 0, len = items.length; i < len; i++) {
  399. items[i] = this._filterFields(items[i], fields);
  400. }
  401. }
  402. }
  403. // return the results
  404. if (returnType == 'DataTable') {
  405. var columns = this._getColumnNames(data);
  406. if (id != undefined) {
  407. // append a single item to the data table
  408. me._appendRow(data, columns, item);
  409. }
  410. else {
  411. // copy the items to the provided data table
  412. for (i = 0; i < items.length; i++) {
  413. me._appendRow(data, columns, items[i]);
  414. }
  415. }
  416. return data;
  417. }
  418. else if (returnType == "Object") {
  419. var result = {};
  420. for (i = 0; i < items.length; i++) {
  421. result[items[i].id] = items[i];
  422. }
  423. return result;
  424. }
  425. else {
  426. // return an array
  427. if (id != undefined) {
  428. // a single item
  429. return item;
  430. }
  431. else {
  432. // multiple items
  433. if (data) {
  434. // copy the items to the provided array
  435. for (i = 0, len = items.length; i < len; i++) {
  436. data.push(items[i]);
  437. }
  438. return data;
  439. }
  440. else {
  441. // just return our array
  442. return items;
  443. }
  444. }
  445. }
  446. };
  447. /**
  448. * Get ids of all items or from a filtered set of items.
  449. * @param {Object} [options] An Object with options. Available options:
  450. * {function} [filter] filter items
  451. * {String | function} [order] Order the items by
  452. * a field name or custom sort function.
  453. * @return {Array} ids
  454. */
  455. DataSet.prototype.getIds = function (options) {
  456. var data = this._data,
  457. filter = options && options.filter,
  458. order = options && options.order,
  459. type = options && options.type || this._options.type,
  460. i,
  461. len,
  462. id,
  463. item,
  464. items,
  465. ids = [];
  466. if (filter) {
  467. // get filtered items
  468. if (order) {
  469. // create ordered list
  470. items = [];
  471. for (id in data) {
  472. if (data.hasOwnProperty(id)) {
  473. item = this._getItem(id, type);
  474. if (filter(item)) {
  475. items.push(item);
  476. }
  477. }
  478. }
  479. this._sort(items, order);
  480. for (i = 0, len = items.length; i < len; i++) {
  481. ids[i] = items[i][this._fieldId];
  482. }
  483. }
  484. else {
  485. // create unordered list
  486. for (id in data) {
  487. if (data.hasOwnProperty(id)) {
  488. item = this._getItem(id, type);
  489. if (filter(item)) {
  490. ids.push(item[this._fieldId]);
  491. }
  492. }
  493. }
  494. }
  495. }
  496. else {
  497. // get all items
  498. if (order) {
  499. // create an ordered list
  500. items = [];
  501. for (id in data) {
  502. if (data.hasOwnProperty(id)) {
  503. items.push(data[id]);
  504. }
  505. }
  506. this._sort(items, order);
  507. for (i = 0, len = items.length; i < len; i++) {
  508. ids[i] = items[i][this._fieldId];
  509. }
  510. }
  511. else {
  512. // create unordered list
  513. for (id in data) {
  514. if (data.hasOwnProperty(id)) {
  515. item = data[id];
  516. ids.push(item[this._fieldId]);
  517. }
  518. }
  519. }
  520. }
  521. return ids;
  522. };
  523. /**
  524. * Returns the DataSet itself. Is overwritten for example by the DataView,
  525. * which returns the DataSet it is connected to instead.
  526. */
  527. DataSet.prototype.getDataSet = function () {
  528. return this;
  529. };
  530. /**
  531. * Execute a callback function for every item in the dataset.
  532. * @param {function} callback
  533. * @param {Object} [options] Available options:
  534. * {Object.<String, String>} [type]
  535. * {String[]} [fields] filter fields
  536. * {function} [filter] filter items
  537. * {String | function} [order] Order the items by
  538. * a field name or custom sort function.
  539. */
  540. DataSet.prototype.forEach = function (callback, options) {
  541. var filter = options && options.filter,
  542. type = options && options.type || this._options.type,
  543. data = this._data,
  544. item,
  545. id;
  546. if (options && options.order) {
  547. // execute forEach on ordered list
  548. var items = this.get(options);
  549. for (var i = 0, len = items.length; i < len; i++) {
  550. item = items[i];
  551. id = item[this._fieldId];
  552. callback(item, id);
  553. }
  554. }
  555. else {
  556. // unordered
  557. for (id in data) {
  558. if (data.hasOwnProperty(id)) {
  559. item = this._getItem(id, type);
  560. if (!filter || filter(item)) {
  561. callback(item, id);
  562. }
  563. }
  564. }
  565. }
  566. };
  567. /**
  568. * Map every item in the dataset.
  569. * @param {function} callback
  570. * @param {Object} [options] Available options:
  571. * {Object.<String, String>} [type]
  572. * {String[]} [fields] filter fields
  573. * {function} [filter] filter items
  574. * {String | function} [order] Order the items by
  575. * a field name or custom sort function.
  576. * @return {Object[]} mappedItems
  577. */
  578. DataSet.prototype.map = function (callback, options) {
  579. var filter = options && options.filter,
  580. type = options && options.type || this._options.type,
  581. mappedItems = [],
  582. data = this._data,
  583. item;
  584. // convert and filter items
  585. for (var id in data) {
  586. if (data.hasOwnProperty(id)) {
  587. item = this._getItem(id, type);
  588. if (!filter || filter(item)) {
  589. mappedItems.push(callback(item, id));
  590. }
  591. }
  592. }
  593. // order items
  594. if (options && options.order) {
  595. this._sort(mappedItems, options.order);
  596. }
  597. return mappedItems;
  598. };
  599. /**
  600. * Filter the fields of an item
  601. * @param {Object | null} item
  602. * @param {String[]} fields Field names
  603. * @return {Object | null} filteredItem or null if no item is provided
  604. * @private
  605. */
  606. DataSet.prototype._filterFields = function (item, fields) {
  607. if (!item) { // item is null
  608. return item;
  609. }
  610. var filteredItem = {};
  611. for (var field in item) {
  612. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  613. filteredItem[field] = item[field];
  614. }
  615. }
  616. return filteredItem;
  617. };
  618. /**
  619. * Sort the provided array with items
  620. * @param {Object[]} items
  621. * @param {String | function} order A field name or custom sort function.
  622. * @private
  623. */
  624. DataSet.prototype._sort = function (items, order) {
  625. if (util.isString(order)) {
  626. // order by provided field name
  627. var name = order; // field name
  628. items.sort(function (a, b) {
  629. var av = a[name];
  630. var bv = b[name];
  631. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  632. });
  633. }
  634. else if (typeof order === 'function') {
  635. // order by sort function
  636. items.sort(order);
  637. }
  638. // TODO: extend order by an Object {field:String, direction:String}
  639. // where direction can be 'asc' or 'desc'
  640. else {
  641. throw new TypeError('Order must be a function or a string');
  642. }
  643. };
  644. /**
  645. * Remove an object by pointer or by id
  646. * @param {String | Number | Object | Array} id Object or id, or an array with
  647. * objects or ids to be removed
  648. * @param {String} [senderId] Optional sender id
  649. * @return {Array} removedIds
  650. */
  651. DataSet.prototype.remove = function (id, senderId) {
  652. var removedIds = [],
  653. i, len, removedId;
  654. if (Array.isArray(id)) {
  655. for (i = 0, len = id.length; i < len; i++) {
  656. removedId = this._remove(id[i]);
  657. if (removedId != null) {
  658. removedIds.push(removedId);
  659. }
  660. }
  661. }
  662. else {
  663. removedId = this._remove(id);
  664. if (removedId != null) {
  665. removedIds.push(removedId);
  666. }
  667. }
  668. if (removedIds.length) {
  669. this._trigger('remove', {items: removedIds}, senderId);
  670. }
  671. return removedIds;
  672. };
  673. /**
  674. * Remove an item by its id
  675. * @param {Number | String | Object} id id or item
  676. * @returns {Number | String | null} id
  677. * @private
  678. */
  679. DataSet.prototype._remove = function (id) {
  680. if (util.isNumber(id) || util.isString(id)) {
  681. if (this._data[id]) {
  682. delete this._data[id];
  683. this.length--;
  684. return id;
  685. }
  686. }
  687. else if (id instanceof Object) {
  688. var itemId = id[this._fieldId];
  689. if (itemId && this._data[itemId]) {
  690. delete this._data[itemId];
  691. this.length--;
  692. return itemId;
  693. }
  694. }
  695. return null;
  696. };
  697. /**
  698. * Clear the data
  699. * @param {String} [senderId] Optional sender id
  700. * @return {Array} removedIds The ids of all removed items
  701. */
  702. DataSet.prototype.clear = function (senderId) {
  703. var ids = Object.keys(this._data);
  704. this._data = {};
  705. this.length = 0;
  706. this._trigger('remove', {items: ids}, senderId);
  707. return ids;
  708. };
  709. /**
  710. * Find the item with maximum value of a specified field
  711. * @param {String} field
  712. * @return {Object | null} item Item containing max value, or null if no items
  713. */
  714. DataSet.prototype.max = function (field) {
  715. var data = this._data,
  716. max = null,
  717. maxField = null;
  718. for (var id in data) {
  719. if (data.hasOwnProperty(id)) {
  720. var item = data[id];
  721. var itemField = item[field];
  722. if (itemField != null && (!max || itemField > maxField)) {
  723. max = item;
  724. maxField = itemField;
  725. }
  726. }
  727. }
  728. return max;
  729. };
  730. /**
  731. * Find the item with minimum value of a specified field
  732. * @param {String} field
  733. * @return {Object | null} item Item containing max value, or null if no items
  734. */
  735. DataSet.prototype.min = function (field) {
  736. var data = this._data,
  737. min = null,
  738. minField = null;
  739. for (var id in data) {
  740. if (data.hasOwnProperty(id)) {
  741. var item = data[id];
  742. var itemField = item[field];
  743. if (itemField != null && (!min || itemField < minField)) {
  744. min = item;
  745. minField = itemField;
  746. }
  747. }
  748. }
  749. return min;
  750. };
  751. /**
  752. * Find all distinct values of a specified field
  753. * @param {String} field
  754. * @return {Array} values Array containing all distinct values. If data items
  755. * do not contain the specified field are ignored.
  756. * The returned array is unordered.
  757. */
  758. DataSet.prototype.distinct = function (field) {
  759. var data = this._data;
  760. var values = [];
  761. var fieldType = this._options.type && this._options.type[field] || null;
  762. var count = 0;
  763. var i;
  764. for (var prop in data) {
  765. if (data.hasOwnProperty(prop)) {
  766. var item = data[prop];
  767. var value = item[field];
  768. var exists = false;
  769. for (i = 0; i < count; i++) {
  770. if (values[i] == value) {
  771. exists = true;
  772. break;
  773. }
  774. }
  775. if (!exists && (value !== undefined)) {
  776. values[count] = value;
  777. count++;
  778. }
  779. }
  780. }
  781. if (fieldType) {
  782. for (i = 0; i < values.length; i++) {
  783. values[i] = util.convert(values[i], fieldType);
  784. }
  785. }
  786. return values;
  787. };
  788. /**
  789. * Add a single item. Will fail when an item with the same id already exists.
  790. * @param {Object} item
  791. * @return {String} id
  792. * @private
  793. */
  794. DataSet.prototype._addItem = function (item) {
  795. var id = item[this._fieldId];
  796. if (id != undefined) {
  797. // check whether this id is already taken
  798. if (this._data[id]) {
  799. // item already exists
  800. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  801. }
  802. }
  803. else {
  804. // generate an id
  805. id = util.randomUUID();
  806. item[this._fieldId] = id;
  807. }
  808. var d = {};
  809. for (var field in item) {
  810. if (item.hasOwnProperty(field)) {
  811. var fieldType = this._type[field]; // type may be undefined
  812. d[field] = util.convert(item[field], fieldType);
  813. }
  814. }
  815. this._data[id] = d;
  816. this.length++;
  817. return id;
  818. };
  819. /**
  820. * Get an item. Fields can be converted to a specific type
  821. * @param {String} id
  822. * @param {Object.<String, String>} [types] field types to convert
  823. * @return {Object | null} item
  824. * @private
  825. */
  826. DataSet.prototype._getItem = function (id, types) {
  827. var field, value;
  828. // get the item from the dataset
  829. var raw = this._data[id];
  830. if (!raw) {
  831. return null;
  832. }
  833. // convert the items field types
  834. var converted = {};
  835. if (types) {
  836. for (field in raw) {
  837. if (raw.hasOwnProperty(field)) {
  838. value = raw[field];
  839. converted[field] = util.convert(value, types[field]);
  840. }
  841. }
  842. }
  843. else {
  844. // no field types specified, no converting needed
  845. for (field in raw) {
  846. if (raw.hasOwnProperty(field)) {
  847. value = raw[field];
  848. converted[field] = value;
  849. }
  850. }
  851. }
  852. return converted;
  853. };
  854. /**
  855. * Update a single item: merge with existing item.
  856. * Will fail when the item has no id, or when there does not exist an item
  857. * with the same id.
  858. * @param {Object} item
  859. * @return {String} id
  860. * @private
  861. */
  862. DataSet.prototype._updateItem = function (item) {
  863. var id = item[this._fieldId];
  864. if (id == undefined) {
  865. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  866. }
  867. var d = this._data[id];
  868. if (!d) {
  869. // item doesn't exist
  870. throw new Error('Cannot update item: no item with id ' + id + ' found');
  871. }
  872. // merge with current item
  873. for (var field in item) {
  874. if (item.hasOwnProperty(field)) {
  875. var fieldType = this._type[field]; // type may be undefined
  876. d[field] = util.convert(item[field], fieldType);
  877. }
  878. }
  879. return id;
  880. };
  881. /**
  882. * Get an array with the column names of a Google DataTable
  883. * @param {DataTable} dataTable
  884. * @return {String[]} columnNames
  885. * @private
  886. */
  887. DataSet.prototype._getColumnNames = function (dataTable) {
  888. var columns = [];
  889. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  890. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  891. }
  892. return columns;
  893. };
  894. /**
  895. * Append an item as a row to the dataTable
  896. * @param dataTable
  897. * @param columns
  898. * @param item
  899. * @private
  900. */
  901. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  902. var row = dataTable.addRow();
  903. for (var col = 0, cols = columns.length; col < cols; col++) {
  904. var field = columns[col];
  905. dataTable.setValue(row, col, item[field]);
  906. }
  907. };
  908. module.exports = DataSet;