2

Is there a convenience method in ES5 to determine whether a property is a getter or setter, or is the following idiomatic?

var o = {
  get foo() { return 'foo'; },
  set bar(value) {},
  bam: 'bam',
};

function isGetterOrSetter(o, k) {
  var descriptor = Object.getOwnPropertyDescriptor(o, k);
  return !!(descriptor.get || descriptor.set);
}

isGetterOrSetter(o, 'foo'); // true
isGetterOrSetter(o, 'bar'); // true
isGetterOrSetter(o, 'bam'); // false
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 1
    It seems that your code currently works, and you are looking to improve it. Generally these questions are too opinionated for this site, but you might find better luck at [CodeReview.SE](http://codereview.stackexchange.com/tour). Remember to read [their question requirements](http://codereview.stackexchange.com/help/on-topic) as they are more strict than this site. – Kyll Sep 17 '15 at 10:25
  • 2
    I am asking whether there is a pre-existing API to determine whether a property is a getter or setter. I'll ammend the question. – Ben Aston Sep 17 '15 at 10:27
  • 2
    How is it different from [this](http://stackoverflow.com/q/30742312/1903116) question of yours? – thefourtheye Sep 17 '15 at 10:30
  • @thefourtheye I forgot I asked it! – Ben Aston Sep 17 '15 at 10:38
  • @BenAston: I took the previous question to mean something different from this one ("how do I do this" vs. "Is there a built-in that does this rather than my code below"). But if you think they're the same, let me know, and I'll delete my answer so you can delete your question. – T.J. Crowder Sep 17 '15 at 10:46
  • Concur with your analysis. Different questions. – Ben Aston Sep 17 '15 at 10:54

1 Answers1

3

No, there's no built-in ES5 (or ES6, I don't think) function that reduces it further than in your question.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 3
    Downvoter: *"Is there a convenience method in ES5 to determine whether a property is a getter or setter"* The answer is no. If you think the answer is yes, I'd love to hear what it is. If you have a problem with the *question*, address the problem to the question, not the answer. – T.J. Crowder Sep 17 '15 at 10:31