npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@lihautan/babel-plugin-transform-destructure-number

v0.0.7

Published

## Inspiration

Downloads

10

Readme

transform-destructure-number

Inspiration

💡 The Idea

Destructuring decimal number via .?

Cool! 😎

Too bad it's not a valid syntax:

let a.b = 3.142;
a === 3; // true
b === 142; // true

Which means, this require us to fork the babel parser.

We can create a parser plugin to extend the existing parsing method. This allow us to turn on / off the parser plugin from the transform plugin. This is just like how babel typescript plugin or flow plugin works.

// filename: https://github.com/babel/babel/tree/master/packages/babel-parser/src/plugin-utils.js

import estree from "./plugins/estree";
+import jsWeDoNotDeserve from "./plugins/jsWeDoNotDeserve";
import flow from "./plugins/flow";
import jsx from "./plugins/jsx";
import typescript from "./plugins/typescript";

// ...

export const mixinPlugins: { [name: string]: MixinPlugin } = {
   estree,
+  jsWeDoNotDeserve,
   jsx,
   // ...

We can first copy the original implementation of parseVarId, the method to parse variable name in a VariableDeclarator.

If we encounter a . token after the variable name, we create a different AST node, DestructureNumberPattern instead.

const a.b = 1.3;

// ...
{
  type: "VariableDeclarator",
  id: {
    type: "DestructureNumberPattern",
    left: {
      type: "Identifier",
      name: "a",
    },
    right: {
      type: "Identifier",
      name: "b",
    },
  },
  init: {
    type: "NumericLiteral",
    value: 1.3,
  },
}
// @flow
import { types as tt, type TokenType } from '../tokenizer/types';
import type Parser from '../parser';
import * as N from '../types';
import {
  type BindingTypes,
  BIND_NONE,
  BIND_LEXICAL,
  BIND_VAR,
} from '../util/scopeflags';

export default (superClass: Class<Parser>): Class<Parser> =>
  class extends superClass {
    parseVarId(
      decl: N.VariableDeclarator,
      kind: 'var' | 'let' | 'const'
    ): void {
      const startPos = this.state.start;
      const startLoc = this.state.startLoc;

+      decl.id = this.parseBindingAtom();
+      if (this.eat(tt.dot) && decl.id.type === 'Identifier') {
+        const node = this.startNodeAt(startPos, startLoc);
+        node.left = decl.id;
+        node.right = this.parseIdentifier();
+        decl.id = this.finishNode(node, 'DestructureNumberPattern');
+      }
      this.checkLVal(
        decl.id,
        kind === 'var' ? BIND_VAR : BIND_LEXICAL,
        undefined,
        'variable declaration',
        kind !== 'var'
      );
    }

    checkLVal(
      expr: N.Expression,
      bindingType: BindingTypes = BIND_NONE,
      checkClashes: ?{ [key: string]: boolean },
      contextDescription: string,
      disallowLetBinding?: boolean
    ): void {
      switch (expr.type) {
        case 'DestructureNumberPattern':
          break;
        default:
          super.checkLVal(
            expr,
            bindingType,
            checkClashes,
            contextDescription,
            disallowLetBinding
          );
      }
    }
  };

📘 The Code

export default function ({ types: t, template }) {
  return {
    name: 'transform-destructure-number',
    visitor: {
      VariableDeclarator(path) {
        if (path.node.id.type === 'DestructureNumberPattern') {
          if (t.isNumericLiteral(path.node.init)) {
            const [a, b] = path.node.init.extra.raw.split('.');

            path.replaceWith(
              template.statement`let [${path.node.id.left}, ${
                path.node.id.right
              }] = [${a}, ${b || '0'}]`().declarations[0]
            );
          } else {
            throw new Error('Destructure number with number!');
          }
        }
      },
    },
  };
}

🧪 Try it out

<a href="https://twitter.com/share?ref_src=twsrc%5Etfw" class="twitter-share-button" data-show-count="false"

Tweet

📦 Babel Plugin

npm version