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.

1006 lines
27 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. if(Array.isArray(fields)){
  612. for (var field in item) {
  613. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  614. filteredItem[field] = item[field];
  615. }
  616. }
  617. }else{
  618. for (var field in item) {
  619. if (item.hasOwnProperty(field) && fields.hasOwnProperty(field)) {
  620. filteredItem[fields[field]] = item[field];
  621. }
  622. }
  623. }
  624. return filteredItem;
  625. };
  626. /**
  627. * Sort the provided array with items
  628. * @param {Object[]} items
  629. * @param {String | function} order A field name or custom sort function.
  630. * @private
  631. */
  632. DataSet.prototype._sort = function (items, order) {
  633. if (util.isString(order)) {
  634. // order by provided field name
  635. var name = order; // field name
  636. items.sort(function (a, b) {
  637. var av = a[name];
  638. var bv = b[name];
  639. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  640. });
  641. }
  642. else if (typeof order === 'function') {
  643. // order by sort function
  644. items.sort(order);
  645. }
  646. // TODO: extend order by an Object {field:String, direction:String}
  647. // where direction can be 'asc' or 'desc'
  648. else {
  649. throw new TypeError('Order must be a function or a string');
  650. }
  651. };
  652. /**
  653. * Remove an object by pointer or by id
  654. * @param {String | Number | Object | Array} id Object or id, or an array with
  655. * objects or ids to be removed
  656. * @param {String} [senderId] Optional sender id
  657. * @return {Array} removedIds
  658. */
  659. DataSet.prototype.remove = function (id, senderId) {
  660. var removedIds = [],
  661. i, len, removedId;
  662. if (Array.isArray(id)) {
  663. for (i = 0, len = id.length; i < len; i++) {
  664. removedId = this._remove(id[i]);
  665. if (removedId != null) {
  666. removedIds.push(removedId);
  667. }
  668. }
  669. }
  670. else {
  671. removedId = this._remove(id);
  672. if (removedId != null) {
  673. removedIds.push(removedId);
  674. }
  675. }
  676. if (removedIds.length) {
  677. this._trigger('remove', {items: removedIds}, senderId);
  678. }
  679. return removedIds;
  680. };
  681. /**
  682. * Remove an item by its id
  683. * @param {Number | String | Object} id id or item
  684. * @returns {Number | String | null} id
  685. * @private
  686. */
  687. DataSet.prototype._remove = function (id) {
  688. if (util.isNumber(id) || util.isString(id)) {
  689. if (this._data[id]) {
  690. delete this._data[id];
  691. this.length--;
  692. return id;
  693. }
  694. }
  695. else if (id instanceof Object) {
  696. var itemId = id[this._fieldId];
  697. if (itemId && this._data[itemId]) {
  698. delete this._data[itemId];
  699. this.length--;
  700. return itemId;
  701. }
  702. }
  703. return null;
  704. };
  705. /**
  706. * Clear the data
  707. * @param {String} [senderId] Optional sender id
  708. * @return {Array} removedIds The ids of all removed items
  709. */
  710. DataSet.prototype.clear = function (senderId) {
  711. var ids = Object.keys(this._data);
  712. this._data = {};
  713. this.length = 0;
  714. this._trigger('remove', {items: ids}, senderId);
  715. return ids;
  716. };
  717. /**
  718. * Find the item with maximum value of a specified field
  719. * @param {String} field
  720. * @return {Object | null} item Item containing max value, or null if no items
  721. */
  722. DataSet.prototype.max = function (field) {
  723. var data = this._data,
  724. max = null,
  725. maxField = null;
  726. for (var id in data) {
  727. if (data.hasOwnProperty(id)) {
  728. var item = data[id];
  729. var itemField = item[field];
  730. if (itemField != null && (!max || itemField > maxField)) {
  731. max = item;
  732. maxField = itemField;
  733. }
  734. }
  735. }
  736. return max;
  737. };
  738. /**
  739. * Find the item with minimum value of a specified field
  740. * @param {String} field
  741. * @return {Object | null} item Item containing max value, or null if no items
  742. */
  743. DataSet.prototype.min = function (field) {
  744. var data = this._data,
  745. min = null,
  746. minField = null;
  747. for (var id in data) {
  748. if (data.hasOwnProperty(id)) {
  749. var item = data[id];
  750. var itemField = item[field];
  751. if (itemField != null && (!min || itemField < minField)) {
  752. min = item;
  753. minField = itemField;
  754. }
  755. }
  756. }
  757. return min;
  758. };
  759. /**
  760. * Find all distinct values of a specified field
  761. * @param {String} field
  762. * @return {Array} values Array containing all distinct values. If data items
  763. * do not contain the specified field are ignored.
  764. * The returned array is unordered.
  765. */
  766. DataSet.prototype.distinct = function (field) {
  767. var data = this._data;
  768. var values = [];
  769. var fieldType = this._options.type && this._options.type[field] || null;
  770. var count = 0;
  771. var i;
  772. for (var prop in data) {
  773. if (data.hasOwnProperty(prop)) {
  774. var item = data[prop];
  775. var value = item[field];
  776. var exists = false;
  777. for (i = 0; i < count; i++) {
  778. if (values[i] == value) {
  779. exists = true;
  780. break;
  781. }
  782. }
  783. if (!exists && (value !== undefined)) {
  784. values[count] = value;
  785. count++;
  786. }
  787. }
  788. }
  789. if (fieldType) {
  790. for (i = 0; i < values.length; i++) {
  791. values[i] = util.convert(values[i], fieldType);
  792. }
  793. }
  794. return values;
  795. };
  796. /**
  797. * Add a single item. Will fail when an item with the same id already exists.
  798. * @param {Object} item
  799. * @return {String} id
  800. * @private
  801. */
  802. DataSet.prototype._addItem = function (item) {
  803. var id = item[this._fieldId];
  804. if (id != undefined) {
  805. // check whether this id is already taken
  806. if (this._data[id]) {
  807. // item already exists
  808. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  809. }
  810. }
  811. else {
  812. // generate an id
  813. id = util.randomUUID();
  814. item[this._fieldId] = id;
  815. }
  816. var d = {};
  817. for (var field in item) {
  818. if (item.hasOwnProperty(field)) {
  819. var fieldType = this._type[field]; // type may be undefined
  820. d[field] = util.convert(item[field], fieldType);
  821. }
  822. }
  823. this._data[id] = d;
  824. this.length++;
  825. return id;
  826. };
  827. /**
  828. * Get an item. Fields can be converted to a specific type
  829. * @param {String} id
  830. * @param {Object.<String, String>} [types] field types to convert
  831. * @return {Object | null} item
  832. * @private
  833. */
  834. DataSet.prototype._getItem = function (id, types) {
  835. var field, value;
  836. // get the item from the dataset
  837. var raw = this._data[id];
  838. if (!raw) {
  839. return null;
  840. }
  841. // convert the items field types
  842. var converted = {};
  843. if (types) {
  844. for (field in raw) {
  845. if (raw.hasOwnProperty(field)) {
  846. value = raw[field];
  847. converted[field] = util.convert(value, types[field]);
  848. }
  849. }
  850. }
  851. else {
  852. // no field types specified, no converting needed
  853. for (field in raw) {
  854. if (raw.hasOwnProperty(field)) {
  855. value = raw[field];
  856. converted[field] = value;
  857. }
  858. }
  859. }
  860. return converted;
  861. };
  862. /**
  863. * Update a single item: merge with existing item.
  864. * Will fail when the item has no id, or when there does not exist an item
  865. * with the same id.
  866. * @param {Object} item
  867. * @return {String} id
  868. * @private
  869. */
  870. DataSet.prototype._updateItem = function (item) {
  871. var id = item[this._fieldId];
  872. if (id == undefined) {
  873. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  874. }
  875. var d = this._data[id];
  876. if (!d) {
  877. // item doesn't exist
  878. throw new Error('Cannot update item: no item with id ' + id + ' found');
  879. }
  880. // merge with current item
  881. for (var field in item) {
  882. if (item.hasOwnProperty(field)) {
  883. var fieldType = this._type[field]; // type may be undefined
  884. d[field] = util.convert(item[field], fieldType);
  885. }
  886. }
  887. return id;
  888. };
  889. /**
  890. * Get an array with the column names of a Google DataTable
  891. * @param {DataTable} dataTable
  892. * @return {String[]} columnNames
  893. * @private
  894. */
  895. DataSet.prototype._getColumnNames = function (dataTable) {
  896. var columns = [];
  897. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  898. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  899. }
  900. return columns;
  901. };
  902. /**
  903. * Append an item as a row to the dataTable
  904. * @param dataTable
  905. * @param columns
  906. * @param item
  907. * @private
  908. */
  909. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  910. var row = dataTable.addRow();
  911. for (var col = 0, cols = columns.length; col < cols; col++) {
  912. var field = columns[col];
  913. dataTable.setValue(row, col, item[field]);
  914. }
  915. };
  916. module.exports = DataSet;