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.

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