Skip to content

Instantly share code, notes, and snippets.

@samoshkin
Created January 17, 2018 13:42
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save samoshkin/baf070ab19b73f4f39ec54149fb37c30 to your computer and use it in GitHub Desktop.
EcmaScript ToPrimitive internal operation pseudo-code
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