Skip to content

Commit

Permalink
[Refactor] GetIntrinsic: further simplification
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Dec 16, 2019
1 parent 0c7f99a commit 9be0385
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
16 changes: 7 additions & 9 deletions GetIntrinsic.js
Expand Up @@ -171,31 +171,29 @@ var stringToPath = function stringToPath(string) {
/* end adaptation */

var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var key = $replace(name, /^%?([^%]*)%?$/, '%$1%');
if (!(key in INTRINSICS)) {
if (!(name in INTRINSICS)) {
throw new SyntaxError('intrinsic ' + name + ' does not exist!');
}

// istanbul ignore if // hopefully this is impossible to test :-)
if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) {
if (typeof INTRINSICS[name] === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}

return INTRINSICS[key];
return INTRINSICS[name];
};

module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new TypeError('"allowMissing" argument must be a boolean');
}

var parts = stringToPath(name);

if (parts.length === 0) {
return getBaseIntrinsic(name, allowMissing);
}

var value = getBaseIntrinsic('%' + parts[0] + '%', allowMissing);
var value = getBaseIntrinsic('%' + (parts.length > 0 ? parts[0] : '') + '%', allowMissing);
for (var i = 1; i < parts.length; i += 1) {
if (value != null) {
if ($gOPD && (i + 1) >= parts.length) {
Expand Down
20 changes: 20 additions & 0 deletions test/GetIntrinsic.js
Expand Up @@ -22,6 +22,26 @@ test('throws', function (t) {
'nonexistent intrinsic throws a syntax error'
);

t['throws'](
function () { GetIntrinsic(''); },
TypeError,
'empty string intrinsic throws a type error'
);

t['throws'](
function () { GetIntrinsic('.'); },
SyntaxError,
'"just a dot" intrinsic throws a syntax error'
);

This comment has been minimized.

Copy link
@lencioni

lencioni Dec 16, 2019

I don't follow where this happens. Is this because getBaseIntrinsic will look for '%%' which doesn't exist?

This comment has been minimized.

Copy link
@ljharb

ljharb Dec 16, 2019

Author Owner

yes, exactly


forEach(v.nonStrings, function (nonString) {
t['throws'](
function () { GetIntrinsic(nonString); },
TypeError,
debug(nonString) + ' is not a String'
);
});

forEach(v.nonBooleans, function (nonBoolean) {
t['throws'](
function () { GetIntrinsic('%', nonBoolean); },
Expand Down

0 comments on commit 9be0385

Please sign in to comment.