You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Right now if you use something like a math library that defines a Symbol class for math operations and do isSymbol() on it, there is a serious non-zero chance that it will return true! 😱
This happens because isSymbol() relies on Symbol.toStringTag via Object#toString() to "sniff" the type. There are other more robust ways for this particular type, though, and I think they should be used.
Example:
// Returns TRUE for Symbol() primitives// Returns TRUE for Object(Symbol()) boxed primitives// Returns TRUE for Object.create(Symbol.prototype)// Returns TRUE for classes that extend Symbol// Returns FALSE for the FancyMath.Symbol// Returns TRUE for FancyMath.Symbol if it's from another realmfunctionisSymbol(x){if(typeofx==="symbol"){returntrue}elseif(x&&typeofx==="object"){if(xinstanceofObject){// Same realm objectreturnxinstanceofSymbol}elseif(!Object.getPrototypeOf(x)){// Null-prototype objectreturnfalse}else{// Object that is probably cross-realmreturnObject.prototype.toString.call(x).slice(8,-1)==="Symbol"}}else{returnfalse}}
Or, you could get fancier and do a branch check on the .description getter! If it throws, it's not a symbol.
// Returns TRUE for Symbol() primitives// Returns TRUE for Object(Symbol()) boxed primitives// Returns FALSE for Object.create(Symbol.prototype)// Returns TRUE for classes that extend Symbol// Returns FALSE for the FancyMath.Symbol// Returns idk for FancyMath.Symbol if it's from another realmfunctionisSymbol(x){try{Object.getOwnPropertyDescriptor(Symbol.prototype,"description").get.call(x)}catch{returnfalse}returntrue}
The text was updated successfully, but these errors were encountered:
My vote is to follow the existing known conventions and try to mirror the Node.js node:utilisSymbol() and friends APIs and how they detect things. https://nodejs.org/api/util.html
In this case, for isSymbol(), that means typeof x === "symbol" instead of the current version that uses Symbol.toStringTag
Right now if you use something like a math library that defines a
Symbol
class for math operations and doisSymbol()
on it, there is a serious non-zero chance that it will return true! 😱This happens because
isSymbol()
relies onSymbol.toStringTag
viaObject#toString()
to "sniff" the type. There are other more robust ways for this particular type, though, and I think they should be used.Example:
Or, you could get fancier and do a branch check on the
.description
getter! If it throws, it's not a symbol.The text was updated successfully, but these errors were encountered: