Skip to content

Commit

Permalink
[New] add getSymbolDescription and getInferredName helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Oct 18, 2019
1 parent f1d05e0 commit f721f34
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 0 deletions.
10 changes: 10 additions & 0 deletions helpers/getInferredName.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

var getInferredName;
try {
// eslint-disable-next-line no-new-func
getInferredName = Function('s', 'return { [s]() {} }[s].name;');
} catch (e) {}

var inferred = function () {};
module.exports = getInferredName && inferred.name === 'inferred' ? getInferredName : null;
30 changes: 30 additions & 0 deletions helpers/getSymbolDescription.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';

var GetIntrinsic = require('../GetIntrinsic');

var callBound = require('./callBound');

var $SyntaxError = GetIntrinsic('%SyntaxError%');
var symToStr = callBound('Symbol.prototype.toString', true);

var getInferredName = require('./getInferredName');

module.exports = function getSymbolDescription(symbol) {
if (!symToStr) {
throw new $SyntaxError('Symbols are not supported in this environment');
}
var str = symToStr(symbol); // will throw if not a symbol

if (getInferredName) {
var name = getInferredName(symbol);
if (name === '') { return; }
// eslint-disable-next-line consistent-return
return name.slice(1, -1); // name.slice('['.length, -']'.length);
}

var desc = str.slice(7, -1); // str.slice('Symbol('.length, -')'.length);
if (desc) {
// eslint-disable-next-line consistent-return
return desc;
}
};
50 changes: 50 additions & 0 deletions test/helpers/getSymbolDescription.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict';

var test = require('tape');
var debug = require('object-inspect');
var forEach = require('foreach');

var v = require('./values');
var getSymbolDescription = require('../../helpers/getSymbolDescription');

test('getSymbolDescription', function (t) {
t.test('no symbols', { skip: v.hasSymbols }, function (st) {
st['throws'](
getSymbolDescription,
SyntaxError,
'requires Symbol support'
);

st.end();
});

forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) {
t['throws'](
function () { getSymbolDescription(nonSymbol); },
TypeError,
debug(nonSymbol) + ' is not a Symbol'
);
});

t.test('with symbols', { skip: !v.hasSymbols }, function (st) {
forEach(
[
[Symbol(), undefined],
[Symbol(undefined), undefined],
[Symbol(null), 'null'],
[Symbol(''), ''],
[Symbol.iterator, 'Symbol.iterator'],
[Symbol('foo'), 'foo']
],
function (pair) {
var sym = pair[0];
var desc = pair[1];
st.equal(getSymbolDescription(sym), desc, debug(sym) + ' yields ' + debug(desc));
}
);

st.end();
});

t.end();
});

0 comments on commit f721f34

Please sign in to comment.