getParameterName.js.flow 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import _ from 'lodash';
  2. export default (identifierNode, context) => {
  3. if (_.has(identifierNode, 'name')) {
  4. return identifierNode.name;
  5. }
  6. if (_.has(identifierNode, 'left.name')) {
  7. return identifierNode.left.name;
  8. }
  9. if (_.has(identifierNode, 'key.name')) {
  10. return identifierNode.key.name;
  11. }
  12. if (identifierNode.type === 'RestElement') {
  13. return identifierNode.argument.name;
  14. }
  15. if (identifierNode.type === 'ObjectTypeProperty') {
  16. let tokenIndex;
  17. tokenIndex = 0;
  18. if (identifierNode.static) {
  19. tokenIndex += 1;
  20. }
  21. if (identifierNode.variance) {
  22. tokenIndex += 1;
  23. }
  24. if (identifierNode.kind === 'set' || identifierNode.kind === 'get') {
  25. tokenIndex += 1;
  26. }
  27. return context.getSourceCode().getFirstToken(identifierNode, tokenIndex).value;
  28. }
  29. if (identifierNode.type === 'ObjectTypeIndexer') {
  30. let tokenIndex;
  31. tokenIndex = 0;
  32. if (identifierNode.static) {
  33. tokenIndex += 1;
  34. }
  35. if (identifierNode.variance) {
  36. tokenIndex += 1;
  37. }
  38. tokenIndex += 1;
  39. const id = context.getSourceCode().getFirstToken(identifierNode, tokenIndex);
  40. const colonOrBrace = context.getSourceCode().getTokenAfter(id);
  41. if (colonOrBrace.value === ':') {
  42. return id.value;
  43. }
  44. return null;
  45. }
  46. if (identifierNode.type === 'FunctionTypeParam') {
  47. return context.getSourceCode().getFirstToken(identifierNode).value;
  48. }
  49. if (identifierNode.type === 'ObjectPattern' || identifierNode.type === 'ArrayPattern') {
  50. const text = context.getSourceCode().getText(identifierNode);
  51. if (identifierNode.typeAnnotation) {
  52. return text.replace(context.getSourceCode().getText(identifierNode.typeAnnotation), '').trim();
  53. }
  54. return text;
  55. }
  56. if (_.get(identifierNode, 'left.type') === 'ObjectPattern') {
  57. return context.getSourceCode().getText(identifierNode.left);
  58. }
  59. return null;
  60. };