• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3var toStr = Object.prototype.toString;
4
5var isPrimitive = require('./helpers/isPrimitive');
6
7var isCallable = require('is-callable');
8
9// http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
10var ES5internalSlots = {
11	'[[DefaultValue]]': function (O) {
12		var actualHint;
13		if (arguments.length > 1) {
14			actualHint = arguments[1];
15		} else {
16			actualHint = toStr.call(O) === '[object Date]' ? String : Number;
17		}
18
19		if (actualHint === String || actualHint === Number) {
20			var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
21			var value, i;
22			for (i = 0; i < methods.length; ++i) {
23				if (isCallable(O[methods[i]])) {
24					value = O[methods[i]]();
25					if (isPrimitive(value)) {
26						return value;
27					}
28				}
29			}
30			throw new TypeError('No default value');
31		}
32		throw new TypeError('invalid [[DefaultValue]] hint supplied');
33	}
34};
35
36// http://ecma-international.org/ecma-262/5.1/#sec-9.1
37module.exports = function ToPrimitive(input) {
38	if (isPrimitive(input)) {
39		return input;
40	}
41	if (arguments.length > 1) {
42		return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
43	}
44	return ES5internalSlots['[[DefaultValue]]'](input);
45};
46