Cite/log.js

  1. import Cite from './index'
  2. /**
  3. * @memberof Cite#
  4. *
  5. * @return {Number} The latest version of the object
  6. */
  7. const currentVersion = function () {
  8. return this.log.length
  9. }
  10. /**
  11. * Returns an image of the object in the version specified.
  12. *
  13. * @memberof Cite#
  14. *
  15. * @param {Number} [versnum=1] - The number of the version you want to retrieve. Illegal numbers: numbers under or equal to zero, floats, numbers above the current version of the object.
  16. *
  17. * @return {Cite} The version of the object with the version number passed. `undefined` if an illegal number is passed.
  18. */
  19. const retrieveVersion = function (versnum = 1) {
  20. if (versnum <= 0 || versnum > this.currentVersion()) {
  21. return null
  22. } else {
  23. const [data, options] = this.log[versnum - 1]
  24. const image = new Cite(JSON.parse(data), JSON.parse(options))
  25. image.log = this.log.slice(0, versnum)
  26. return image
  27. }
  28. }
  29. /**
  30. * Returns the second to last saved image of the object.
  31. *
  32. * @memberof Cite#
  33. *
  34. * @param {Number} [number=1] - number of versions to go back.
  35. *
  36. * @return {Cite} The second to last version of the object. `undefined` if used on first version.
  37. */
  38. const undo = function (number = 1) {
  39. return this.retrieveVersion(this.currentVersion() - number)
  40. }
  41. /**
  42. * Returns the last saved image of the object.
  43. *
  44. * @memberof Cite#
  45. *
  46. * @return {Cite} The last version of the object. `undefined` if used on first version.
  47. */
  48. const retrieveLastVersion = function () {
  49. return this.retrieveVersion(this.currentVersion())
  50. }
  51. /**
  52. * Save an image of the current version of the object.
  53. *
  54. * @memberof Cite#
  55. *
  56. * @return {Cite} The current version of the object.
  57. */
  58. const save = function () {
  59. this.log.push([JSON.stringify(this.data), JSON.stringify(this._options)])
  60. return this
  61. }
  62. export { currentVersion, retrieveVersion, retrieveLastVersion, undo, save }