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.

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