🚀 DAY 5 OF LAUNCH WEEK: Introducing Socket Firewall Enterprise.Learn more
Socket
Book a DemoInstallSign in
Socket

@lihautan/babel-plugin-transform-roman-numbers

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@lihautan/babel-plugin-transform-roman-numbers

## Inspiration

latest
npmnpm
Version
0.0.3
Version published
Maintainers
1
Created
Source

transform-roman-numbers

Inspiration

Roman numerals. Mandatory for floating point numbers.

— Bogdan Marinescu (@bogdanm78) July 22, 2020

💡 The Idea

OK, I'm a bit lazy over here. I just going to support only integer roman numerals.

The following is a valid JavaScript syntax:

let a = II;
b(VI);

as II is just a normal variable.

If the variable name is a roman numeric, we are going to transpile them into a number.

let a = 2;
b(6);

So it would work like JavaScript supports roman numeric.

Of course not all variable name are free to modify:

II(a);
const III = { IV: b };
class XI {
  XC() {}
}

The above is a valid JS, but it does not make sense to turn them into number, as function call expression, variable declaration, class name and method does not allow number as the sole variable name.

2(a);
const 3 = { 4: b };
class 11 {
  90() {}
}

Although { 4: b } looks valid. 🤔

I realised that the places of a variable can be interpreted as roman numeric is limited, so it's easier to whitelist those places rather than blacklist places it shouldn't be appear.

📘 The Code

import { isValidRoman, romanToArab } from 'roman-numbers';

export default function ({ types: t }) {
  return {
    name: 'roman-numbers',
    visitor: {
      Identifier(path) {
        const { parent, node } = path;
        if (
          // const a = II
          (t.isVariableDeclarator(parent) && parent.init === node) ||
          // { a: II }
          (t.isObjectProperty(parent) && !parent.method) ||
          // [II]
          t.isArrayExpression(parent) ||
          // const { a: b = II } = c
          (t.isAssignmentExpression(parent) && parent.right === node) ||
          // function a({ a: b = II }) {}
          (t.isAssignmentPattern(parent) && parent.right === node) ||
          // II + III
          (t.isBinaryExpression(parent)) ||
          // II++
          (t.isUpdateExpression(parent))
        ) {
          const name = node.name;
          if (isValidRoman(name) && !path.scope.hasBinding(name)) {
            path.replaceWith(t.numericLiteral(romanToArab(name)));
          }
        }
      },
    },
  };
}

🧪 Try it out

📦 Babel Plugin

npm version

FAQs

Package last updated on 25 Jul 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts