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.

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