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.

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