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.

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