localStorage.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict'
  2. const valuesMap = new Map()
  3. class LocalStorage {
  4. getItem (key) {
  5. const stringKey = String(key)
  6. if (valuesMap.has(key)) {
  7. return String(valuesMap.get(stringKey))
  8. }
  9. return null
  10. }
  11. setItem (key, val) {
  12. valuesMap.set(String(key), String(val))
  13. }
  14. removeItem (key) {
  15. valuesMap.delete(key)
  16. }
  17. clear () {
  18. valuesMap.clear()
  19. }
  20. key (i) {
  21. if (arguments.length === 0) {
  22. throw new TypeError("Failed to execute 'key' on 'Storage': 1 argument required, but only 0 present.") // this is a TypeError implemented on Chrome, Firefox throws Not enough arguments to Storage.key.
  23. }
  24. var arr = Array.from(valuesMap.keys())
  25. return arr[i]
  26. }
  27. get length () {
  28. return valuesMap.size
  29. }
  30. }
  31. const instance = new LocalStorage()
  32. global.localStorage = new Proxy(instance, {
  33. set: function (obj, prop, value) {
  34. if (LocalStorage.prototype.hasOwnProperty(prop)) {
  35. instance[prop] = value
  36. } else {
  37. instance.setItem(prop, value)
  38. }
  39. return true
  40. },
  41. get: function (target, name) {
  42. if (LocalStorage.prototype.hasOwnProperty(name)) {
  43. return instance[name]
  44. }
  45. if (valuesMap.has(name)) {
  46. return instance.getItem(name)
  47. }
  48. }
  49. })