index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var assert = require('assert')
  2. /**
  3. * Get a list of all identifiers that are initialised by this (possibly destructuring)
  4. * node.
  5. *
  6. * eg with input:
  7. *
  8. * var { a: [b, ...c], d } = xyz
  9. *
  10. * this returns the nodes for 'b', 'c', and 'd'
  11. */
  12. module.exports = function getAssignedIdentifiers (node, identifiers) {
  13. assert.equal(typeof node, 'object', 'get-assigned-identifiers: node must be object')
  14. assert.equal(typeof node.type, 'string', 'get-assigned-identifiers: node must have a type')
  15. identifiers = identifiers || []
  16. if (node.type === 'ImportDeclaration') {
  17. node.specifiers.forEach(function (el) {
  18. getAssignedIdentifiers(el, identifiers)
  19. })
  20. }
  21. if (node.type === 'ImportDefaultSpecifier' || node.type === 'ImportNamespaceSpecifier' || node.type === 'ImportSpecifier') {
  22. node = node.local
  23. }
  24. if (node.type === 'RestElement') {
  25. node = node.argument
  26. }
  27. if (node.type === 'ArrayPattern') {
  28. node.elements.forEach(function (el) {
  29. // `el` might be `null` in case of `[x,,y] = whatever`
  30. if (el) {
  31. getAssignedIdentifiers(el, identifiers)
  32. }
  33. })
  34. }
  35. if (node.type === 'ObjectPattern') {
  36. node.properties.forEach(function (prop) {
  37. if (prop.type === 'Property') {
  38. getAssignedIdentifiers(prop.value, identifiers)
  39. } else if (prop.type === 'RestElement') {
  40. getAssignedIdentifiers(prop, identifiers)
  41. }
  42. })
  43. }
  44. if (node.type === 'Identifier') {
  45. identifiers.push(node)
  46. }
  47. return identifiers
  48. }