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.

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