Skip to content

toPrimitive #792

Open
Open
@char0n

Description

@char0n

Is your feature request related to a problem? Please describe.
toPrimitive function should return a primitive representation of value provided as a single argument. Coercion hint is bonded to default. Before the Symbol.toPrimitive existed, there were Object.prototype.valueOf and Object.prototype.toString methods that were responsible for returning the primitive value. The function can throw TypeError if Symbo.toPrimitive method returns non primitive value.

Describe the solution you'd like
Possible implementation of toPrimitive:

const toPrimitive = toPrimitiveHint('default');

Possible implementation of toPrimitiveHint:

// pseudocode
const toPrimitiveHint = curry((hint, obj) => {
  // if obj is already primitive value, we do nothing 
  is (isPrimitive(obj)) { return obj; }
 
  // The order here is very important, it is the order how implicit ToPrimitive coercion works
  // 1.) find out if obj have Symbo.toPrimitive and call it and return
  // 2.) find out if obj have valueOf method and call it and return
  // 3.) find out if obj have toString method and call it and return
  // 4.) return original object if it cannot be coerced
});

Describe alternatives you've considered

toPrimitiveHint should be implemented too as part of this issue. This function consumes the hint of the coercion.

var obj = {
  [Symbol.toPrimitive](hint) {
    if (hint == 'number') {
      return 10;
    }
    if (hint == 'string') {
      return 'hello';
    }
    return true;
  }
};

toPrimitiveHint('number', obj); //=> 10
toPrimitiveHint('string', obj); /=> 'hello'
toPrimitiveHint('default', obj); => true

Additional context

This issue is currently blocked by isPrimitive, which is implementation requirement for this function.

valueOf: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
Primitive values: https://developer.mozilla.org/en-US/docs/Glossary/Primitive
Symbol.toPrimitive: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive
Ecmascript abstract ToPrimitive operation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive
You don't know Javascript: https://github.com/getify/You-Dont-Know-JS/blob/9959fc904d584bbf0b02cf41c192f74ff4238581/types-grammar/ch4.md

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions