Skip to content

Instantly share code, notes, and snippets.

@vjeux

vjeux/index.js Secret

Created January 18, 2016 18:03
Show Gist options
  • Save vjeux/2715c9687653547037b0 to your computer and use it in GitHub Desktop.
Save vjeux/2715c9687653547037b0 to your computer and use it in GitHub Desktop.
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
'use strict';
/*eslint consistent-return: 0*/
/**
* Transforms function properties of the `Symbol` into
* the presence check, and fallback string "@@<name>".
*
* Example:
*
* Symbol.iterator;
*
* Transformed to:
*
* typeof Symbol.iterator === 'function' ? Symbol.iterator : '@@iterator';
*/
module.exports = function symbolMember(babel) {
const t = babel.types;
return {
visitor: {
MemberExpression(path) {
let node = path.node;
if (!isAppropriateMember(node)) {
return;
}
path.replaceWith(
t.conditionalExpression(
t.binaryExpression(
'===',
t.unaryExpression(
'typeof',
t.identifier('Symbol'),
true
),
t.stringLiteral('function')
),
node,
t.stringLiteral(`@@${node.property.name}`)
)
);
// We should stop to avoid infinite recursion, since Babel
// traverses replaced path, and again would hit our transform.
path.stop();
},
},
};
};
function isAppropriateMember(node) {
return node.object.type === 'Identifier' &&
node.object.name === 'Symbol' &&
node.property.type === 'Identifier';
}
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @emails oncall+jsinfra
*/
jest.autoMockOff();
const testUtil = require('../../util/test-util');
const plugins = [
require('../index'),
];
testUtil.testCase('symbol-member', plugins, {
'transform Symbol.iterator to @@iterator': {
input: `foo[Symbol.iterator]();`,
output: `
foo[typeof Symbol === "function" ? Symbol.iterator : '@@iterator']();
`,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment