Perhaps relevant to this audience: NetHack has a routine specifically for this.
https://github.com/NetHack/NetHack/blob/NetHack-5.0/src/objn...
I think I agree with the comment in NH5 that some of the new cases "probably shouldn't be handled here", and think maybe NH3.4.3's simpler version should've been fine for NetHack's purposes:
https://github.com/Vanilla-NetHack/NetHack-3.4.3/blob/master...