Created
January 17, 2018 13:42
-
-
Save samoshkin/baf070ab19b73f4f39ec54149fb37c30 to your computer and use it in GitHub Desktop.
EcmaScript ToPrimitive internal operation pseudo-code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ToPrimitive(input, preferredType){ | |
switch (preferredType){ | |
case Number: | |
return toNumber(input); | |
break; | |
case String: | |
return toString(input); | |
break | |
default: | |
return toNumber(input); | |
} | |
function isPrimitive(value){ | |
return value !== Object(value); | |
} | |
function toString(){ | |
if (isPrimitive(input.toString())) return input.toString(); | |
if (isPrimitive(input.valueOf())) return input.valueOf(); | |
throw new TypeError(); | |
} | |
function toNumber(){ | |
if (isPrimitive(input.valueOf())) return input.valueOf(); | |
if (isPrimitive(input.toString())) return input.toString(); | |
throw new TypeError(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment