index.js 866 B

12345678910111213141516171819202122232425262728293031
  1. const reserved = require('./reserved.js')
  2. // from https://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
  3. function hashCode(str) {
  4. let hash = 0
  5. for (let i = 0; i < str.length; ++i) {
  6. const char = str.charCodeAt(i)
  7. hash = (hash << 5) - hash + char
  8. hash |= 0 // Convert to 32bit integer
  9. }
  10. return hash
  11. }
  12. function identifier(key, unique) {
  13. if (unique) key += ' ' + hashCode(key).toString(36)
  14. const id = key.trim().replace(/\W+/g, '_')
  15. return reserved.ES3[id] || reserved.ESnext[id] || /^\d/.test(id)
  16. ? '_' + id
  17. : id
  18. }
  19. function property(obj, key) {
  20. if (/^[A-Z_$][0-9A-Z_$]*$/i.test(key) && !reserved.ES3[key]) {
  21. return obj ? obj + '.' + key : key
  22. } else {
  23. const jkey = JSON.stringify(key)
  24. return obj ? obj + '[' + jkey + ']' : jkey
  25. }
  26. }
  27. module.exports = { identifier, property }