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.

921 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
  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} [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)) {
  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. var fields = Object.keys(this._options.type);
  61. for (var i = 0, len = fields.length; i < len; i++) {
  62. var field = fields[i];
  63. var value = this._options.type[field];
  64. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  65. this._type[field] = 'Date';
  66. }
  67. else {
  68. this._type[field] = value;
  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: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0)
  134. DataSet.prototype.subscribe = function () {
  135. throw new Error('DataSet.subscribe is deprecated. Use DataSet.on instead.');
  136. };
  137. /**
  138. * Unsubscribe from an event, remove an event listener
  139. * @param {String} event
  140. * @param {function} callback
  141. */
  142. DataSet.prototype.off = function(event, callback) {
  143. var subscribers = this._subscribers[event];
  144. if (subscribers) {
  145. this._subscribers[event] = subscribers.filter(listener => listener.callback != callback);
  146. }
  147. };
  148. // TODO: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0)
  149. DataSet.prototype.unsubscribe = function () {
  150. throw new Error('DataSet.unsubscribe is deprecated. Use DataSet.off instead.');
  151. };
  152. /**
  153. * Trigger an event
  154. * @param {String} event
  155. * @param {Object | null} params
  156. * @param {String} [senderId] Optional id of the sender.
  157. * @private
  158. */
  159. DataSet.prototype._trigger = function (event, params, senderId) {
  160. if (event == '*') {
  161. throw new Error('Cannot trigger event *');
  162. }
  163. var subscribers = [];
  164. if (event in this._subscribers) {
  165. subscribers = subscribers.concat(this._subscribers[event]);
  166. }
  167. if ('*' in this._subscribers) {
  168. subscribers = subscribers.concat(this._subscribers['*']);
  169. }
  170. for (var i = 0, len = subscribers.length; i < len; i++) {
  171. var subscriber = subscribers[i];
  172. if (subscriber.callback) {
  173. subscriber.callback(event, params, senderId || null);
  174. }
  175. }
  176. };
  177. /**
  178. * Add data.
  179. * Adding an item will fail when there already is an item with the same id.
  180. * @param {Object | Array} data
  181. * @param {String} [senderId] Optional sender id
  182. * @return {Array} addedIds Array with the ids of the added items
  183. */
  184. DataSet.prototype.add = function (data, senderId) {
  185. var addedIds = [],
  186. id,
  187. me = this;
  188. if (Array.isArray(data)) {
  189. // Array
  190. for (var i = 0, len = data.length; i < len; i++) {
  191. id = me._addItem(data[i]);
  192. addedIds.push(id);
  193. }
  194. }
  195. else if (data instanceof Object) {
  196. // Single item
  197. id = me._addItem(data);
  198. addedIds.push(id);
  199. }
  200. else {
  201. throw new Error('Unknown dataType');
  202. }
  203. if (addedIds.length) {
  204. this._trigger('add', {items: addedIds}, senderId);
  205. }
  206. return addedIds;
  207. };
  208. /**
  209. * Update existing items. When an item does not exist, it will be created
  210. * @param {Object | Array} data
  211. * @param {String} [senderId] Optional sender id
  212. * @return {Array} updatedIds The ids of the added or updated items
  213. */
  214. DataSet.prototype.update = function (data, senderId) {
  215. var addedIds = [];
  216. var updatedIds = [];
  217. var updatedData = [];
  218. var me = this;
  219. var fieldId = me._fieldId;
  220. var addOrUpdate = function (item) {
  221. var id = item[fieldId];
  222. if (me._data[id]) {
  223. // update item
  224. id = me._updateItem(item);
  225. updatedIds.push(id);
  226. updatedData.push(item);
  227. }
  228. else {
  229. // add new item
  230. id = me._addItem(item);
  231. addedIds.push(id);
  232. }
  233. };
  234. if (Array.isArray(data)) {
  235. // Array
  236. for (var i = 0, len = data.length; i < len; i++) {
  237. addOrUpdate(data[i]);
  238. }
  239. }
  240. else if (data instanceof Object) {
  241. // Single item
  242. addOrUpdate(data);
  243. }
  244. else {
  245. throw new Error('Unknown dataType');
  246. }
  247. if (addedIds.length) {
  248. this._trigger('add', {items: addedIds}, senderId);
  249. }
  250. if (updatedIds.length) {
  251. this._trigger('update', {items: updatedIds, data: updatedData}, senderId);
  252. }
  253. return addedIds.concat(updatedIds);
  254. };
  255. /**
  256. * Get a data item or multiple items.
  257. *
  258. * Usage:
  259. *
  260. * get()
  261. * get(options: Object)
  262. *
  263. * get(id: Number | String)
  264. * get(id: Number | String, options: Object)
  265. *
  266. * get(ids: Number[] | String[])
  267. * get(ids: Number[] | String[], options: Object)
  268. *
  269. * Where:
  270. *
  271. * {Number | String} id The id of an item
  272. * {Number[] | String{}} ids An array with ids of items
  273. * {Object} options An Object with options. Available options:
  274. * {String} [returnType] Type of data to be returned.
  275. * Can be 'Array' (default) or 'Object'.
  276. * {Object.<String, String>} [type]
  277. * {String[]} [fields] field names to be returned
  278. * {function} [filter] filter items
  279. * {String | function} [order] Order the items by a field name or custom sort function.
  280. * @throws Error
  281. */
  282. DataSet.prototype.get = function (args) {
  283. var me = this;
  284. // parse the arguments
  285. var id, ids, options;
  286. var firstType = util.getType(arguments[0]);
  287. if (firstType == 'String' || firstType == 'Number') {
  288. // get(id [, options])
  289. id = arguments[0];
  290. options = arguments[1];
  291. }
  292. else if (firstType == 'Array') {
  293. // get(ids [, options])
  294. ids = arguments[0];
  295. options = arguments[1];
  296. }
  297. else {
  298. // get([, options])
  299. options = arguments[0];
  300. }
  301. // determine the return type
  302. var returnType;
  303. if (options && options.returnType) {
  304. var allowedValues = ['Array', 'Object'];
  305. returnType = allowedValues.indexOf(options.returnType) == -1 ? 'Array' : options.returnType;
  306. }
  307. else {
  308. returnType = 'Array';
  309. }
  310. // build options
  311. var type = options && options.type || this._options.type;
  312. var filter = options && options.filter;
  313. var items = [], item, itemIds, itemId, i, len;
  314. // convert items
  315. if (id != undefined) {
  316. // return a single item
  317. item = me._getItem(id, type);
  318. if (filter && !filter(item)) {
  319. item = null;
  320. }
  321. }
  322. else if (ids != undefined) {
  323. // return a subset of items
  324. for (i = 0, len = ids.length; i < len; i++) {
  325. item = me._getItem(ids[i], type);
  326. if (!filter || filter(item)) {
  327. items.push(item);
  328. }
  329. }
  330. }
  331. else {
  332. // return all items
  333. itemIds = Object.keys(this._data);
  334. for (i = 0, len = itemIds.length; i < len; i++) {
  335. itemId = itemIds[i];
  336. item = me._getItem(itemId, type);
  337. if (!filter || filter(item)) {
  338. items.push(item);
  339. }
  340. }
  341. }
  342. // order the results
  343. if (options && options.order && id == undefined) {
  344. this._sort(items, options.order);
  345. }
  346. // filter fields of the items
  347. if (options && options.fields) {
  348. var fields = options.fields;
  349. if (id != undefined) {
  350. item = this._filterFields(item, fields);
  351. }
  352. else {
  353. for (i = 0, len = items.length; i < len; i++) {
  354. items[i] = this._filterFields(items[i], fields);
  355. }
  356. }
  357. }
  358. // return the results
  359. if (returnType == 'Object') {
  360. var result = {},
  361. resultant;
  362. for (i = 0, len = items.length; i < len; i++) {
  363. resultant = items[i];
  364. result[resultant.id] = resultant;
  365. }
  366. return result;
  367. }
  368. else {
  369. if (id != undefined) {
  370. // a single item
  371. return item;
  372. }
  373. else {
  374. // just return our array
  375. return items;
  376. }
  377. }
  378. };
  379. /**
  380. * Get ids of all items or from a filtered set of items.
  381. * @param {Object} [options] An Object with options. Available options:
  382. * {function} [filter] filter items
  383. * {String | function} [order] Order the items by
  384. * a field name or custom sort function.
  385. * @return {Array} ids
  386. */
  387. DataSet.prototype.getIds = function (options) {
  388. var data = this._data,
  389. filter = options && options.filter,
  390. order = options && options.order,
  391. type = options && options.type || this._options.type,
  392. itemIds = Object.keys(data),
  393. i,
  394. len,
  395. id,
  396. item,
  397. items,
  398. ids = [];
  399. if (filter) {
  400. // get filtered items
  401. if (order) {
  402. // create ordered list
  403. items = [];
  404. for (i = 0, len = itemIds.length; i < len; i++) {
  405. id = itemIds[i];
  406. item = this._getItem(id, type);
  407. if (filter(item)) {
  408. items.push(item);
  409. }
  410. }
  411. this._sort(items, order);
  412. for (i = 0, len = items.length; i < len; i++) {
  413. ids.push(items[i][this._fieldId]);
  414. }
  415. }
  416. else {
  417. // create unordered list
  418. for (i = 0, len = itemIds.length; i < len; i++) {
  419. id = itemIds[i];
  420. item = this._getItem(id, type);
  421. if (filter(item)) {
  422. ids.push(item[this._fieldId]);
  423. }
  424. }
  425. }
  426. }
  427. else {
  428. // get all items
  429. if (order) {
  430. // create an ordered list
  431. items = [];
  432. for (i = 0, len = itemIds.length; i < len; i++) {
  433. id = itemIds[i];
  434. items.push(data[id]);
  435. }
  436. this._sort(items, order);
  437. for (i = 0, len = items.length; i < len; i++) {
  438. ids.push(items[i][this._fieldId]);
  439. }
  440. }
  441. else {
  442. // create unordered list
  443. for (i = 0, len = itemIds.length; i < len; i++) {
  444. id = itemIds[i];
  445. item = data[id];
  446. ids.push(item[this._fieldId]);
  447. }
  448. }
  449. }
  450. return ids;
  451. };
  452. /**
  453. * Returns the DataSet itself. Is overwritten for example by the DataView,
  454. * which returns the DataSet it is connected to instead.
  455. */
  456. DataSet.prototype.getDataSet = function () {
  457. return this;
  458. };
  459. /**
  460. * Execute a callback function for every item in the dataset.
  461. * @param {function} callback
  462. * @param {Object} [options] Available options:
  463. * {Object.<String, String>} [type]
  464. * {String[]} [fields] filter fields
  465. * {function} [filter] filter items
  466. * {String | function} [order] Order the items by
  467. * a field name or custom sort function.
  468. */
  469. DataSet.prototype.forEach = function (callback, options) {
  470. var filter = options && options.filter,
  471. type = options && options.type || this._options.type,
  472. data = this._data,
  473. itemIds = Object.key(data),
  474. i,
  475. len,
  476. item,
  477. id;
  478. if (options && options.order) {
  479. // execute forEach on ordered list
  480. var items = this.get(options);
  481. for (i = 0, len = items.length; i < len; i++) {
  482. item = items[i];
  483. id = item[this._fieldId];
  484. callback(item, id);
  485. }
  486. }
  487. else {
  488. // unordered
  489. for (i = 0, len = itemIds.length; i < len; i++) {
  490. id = itemIds[i];
  491. item = this._getItem(id, type);
  492. if (!filter || filter(item)) {
  493. callback(item, id);
  494. }
  495. }
  496. }
  497. };
  498. /**
  499. * Map every item in the dataset.
  500. * @param {function} callback
  501. * @param {Object} [options] Available options:
  502. * {Object.<String, String>} [type]
  503. * {String[]} [fields] filter fields
  504. * {function} [filter] filter items
  505. * {String | function} [order] Order the items by
  506. * a field name or custom sort function.
  507. * @return {Object[]} mappedItems
  508. */
  509. DataSet.prototype.map = function (callback, options) {
  510. var filter = options && options.filter,
  511. type = options && options.type || this._options.type,
  512. mappedItems = [],
  513. data = this._data,
  514. itemIds = Object.keys(data),
  515. i,
  516. len,
  517. id,
  518. item;
  519. // convert and filter items
  520. for (i = 0, len = itemIds.length; i < len; i++) {
  521. id = itemIds[i];
  522. item = this._getItem(id, type);
  523. if (!filter || filter(item)) {
  524. mappedItems.push(callback(item, id));
  525. }
  526. }
  527. // order items
  528. if (options && options.order) {
  529. this._sort(mappedItems, options.order);
  530. }
  531. return mappedItems;
  532. };
  533. /**
  534. * Filter the fields of an item
  535. * @param {Object | null} item
  536. * @param {String[]} fields Field names
  537. * @return {Object | null} filteredItem or null if no item is provided
  538. * @private
  539. */
  540. DataSet.prototype._filterFields = function (item, fields) {
  541. if (!item) { // item is null
  542. return item;
  543. }
  544. var filteredItem = {},
  545. itemFields = Object.keys(item),
  546. len = itemFields.length,
  547. i,
  548. field;
  549. if(Array.isArray(fields)){
  550. for (i = 0; i < len; i++) {
  551. field = itemFields[i];
  552. if (fields.indexOf(field) != -1) {
  553. filteredItem[field] = item[field];
  554. }
  555. }
  556. }else{
  557. for (i = 0; i < len; i++) {
  558. field = itemFields[i];
  559. if (fields.hasOwnProperty(field)) {
  560. filteredItem[fields[field]] = item[field];
  561. }
  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. this.length--;
  632. return id;
  633. }
  634. }
  635. else if (id instanceof Object) {
  636. var itemId = id[this._fieldId];
  637. if (itemId && this._data[itemId]) {
  638. delete this._data[itemId];
  639. this.length--;
  640. return itemId;
  641. }
  642. }
  643. return null;
  644. };
  645. /**
  646. * Clear the data
  647. * @param {String} [senderId] Optional sender id
  648. * @return {Array} removedIds The ids of all removed items
  649. */
  650. DataSet.prototype.clear = function (senderId) {
  651. var ids = Object.keys(this._data);
  652. this._data = {};
  653. this.length = 0;
  654. this._trigger('remove', {items: ids}, senderId);
  655. return ids;
  656. };
  657. /**
  658. * Find the item with maximum value of a specified field
  659. * @param {String} field
  660. * @return {Object | null} item Item containing max value, or null if no items
  661. */
  662. DataSet.prototype.max = function (field) {
  663. var data = this._data,
  664. itemIds = Object.keys(data),
  665. max = null,
  666. maxField = null,
  667. i,
  668. len;
  669. for (i = 0, len = itemIds.length; i < len; i++) {
  670. var id = itemIds[i];
  671. var item = data[id];
  672. var itemField = item[field];
  673. if (itemField != null && (!max || itemField > maxField)) {
  674. max = item;
  675. maxField = itemField;
  676. }
  677. }
  678. return max;
  679. };
  680. /**
  681. * Find the item with minimum value of a specified field
  682. * @param {String} field
  683. * @return {Object | null} item Item containing max value, or null if no items
  684. */
  685. DataSet.prototype.min = function (field) {
  686. var data = this._data,
  687. itemIds = Object.keys(data),
  688. min = null,
  689. minField = null,
  690. i,
  691. len;
  692. for (i = 0, len = itemIds.length; i < len; i++) {
  693. var id = itemIds[i];
  694. var item = data[id];
  695. var itemField = item[field];
  696. if (itemField != null && (!min || itemField < minField)) {
  697. min = item;
  698. minField = itemField;
  699. }
  700. }
  701. return min;
  702. };
  703. /**
  704. * Find all distinct values of a specified field
  705. * @param {String} field
  706. * @return {Array} values Array containing all distinct values. If data items
  707. * do not contain the specified field are ignored.
  708. * The returned array is unordered.
  709. */
  710. DataSet.prototype.distinct = function (field) {
  711. var data = this._data;
  712. var itemIds = Object.keys(data);
  713. var values = [];
  714. var fieldType = this._options.type && this._options.type[field] || null;
  715. var count = 0;
  716. var i,
  717. j,
  718. len;
  719. for (i = 0, len = itemIds.length; i < len; i++) {
  720. var id = itemIds[i];
  721. var item = data[id];
  722. var value = item[field];
  723. var exists = false;
  724. for (j = 0; j < count; j++) {
  725. if (values[j] == value) {
  726. exists = true;
  727. break;
  728. }
  729. }
  730. if (!exists && (value !== undefined)) {
  731. values[count] = value;
  732. count++;
  733. }
  734. }
  735. if (fieldType) {
  736. for (i = 0, len = values.length; i < len; i++) {
  737. values[i] = util.convert(values[i], fieldType);
  738. }
  739. }
  740. return values;
  741. };
  742. /**
  743. * Add a single item. Will fail when an item with the same id already exists.
  744. * @param {Object} item
  745. * @return {String} id
  746. * @private
  747. */
  748. DataSet.prototype._addItem = function (item) {
  749. var id = item[this._fieldId];
  750. if (id != undefined) {
  751. // check whether this id is already taken
  752. if (this._data[id]) {
  753. // item already exists
  754. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  755. }
  756. }
  757. else {
  758. // generate an id
  759. id = util.randomUUID();
  760. item[this._fieldId] = id;
  761. }
  762. var d = {},
  763. fields = Object.keys(item),
  764. i,
  765. len;
  766. for (i = 0, len = fields.length; i < len; i++) {
  767. var field = fields[i];
  768. var fieldType = this._type[field]; // type may be undefined
  769. d[field] = util.convert(item[field], fieldType);
  770. }
  771. this._data[id] = d;
  772. this.length++;
  773. return id;
  774. };
  775. /**
  776. * Get an item. Fields can be converted to a specific type
  777. * @param {String} id
  778. * @param {Object.<String, String>} [types] field types to convert
  779. * @return {Object | null} item
  780. * @private
  781. */
  782. DataSet.prototype._getItem = function (id, types) {
  783. var field, value, i, len;
  784. // get the item from the dataset
  785. var raw = this._data[id];
  786. if (!raw) {
  787. return null;
  788. }
  789. // convert the items field types
  790. var converted = {},
  791. fields = Object.keys(raw);
  792. if (types) {
  793. for (i = 0, len = fields.length; i < len; i++) {
  794. field = fields[i];
  795. value = raw[field];
  796. converted[field] = util.convert(value, types[field]);
  797. }
  798. }
  799. else {
  800. // no field types specified, no converting needed
  801. for (i = 0, len = fields.length; i < len; i++) {
  802. field = fields[i];
  803. value = raw[field];
  804. converted[field] = value;
  805. }
  806. }
  807. return converted;
  808. };
  809. /**
  810. * Update a single item: merge with existing item.
  811. * Will fail when the item has no id, or when there does not exist an item
  812. * with the same id.
  813. * @param {Object} item
  814. * @return {String} id
  815. * @private
  816. */
  817. DataSet.prototype._updateItem = function (item) {
  818. var id = item[this._fieldId];
  819. if (id == undefined) {
  820. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  821. }
  822. var d = this._data[id];
  823. if (!d) {
  824. // item doesn't exist
  825. throw new Error('Cannot update item: no item with id ' + id + ' found');
  826. }
  827. // merge with current item
  828. var fields = Object.keys(item);
  829. for (var i = 0, len = fields.length; i < len; i++) {
  830. var field = fields[i];
  831. var fieldType = this._type[field]; // type may be undefined
  832. d[field] = util.convert(item[field], fieldType);
  833. }
  834. return id;
  835. };
  836. module.exports = DataSet;