0

I tried to find some tool that would do this, but prepack is not quite doing what I want and other tools are failing at this particular example.

I think it's quite common in programming to use functions in which some of the arguments are constants and the remainder are variables. A good example in JS is parseInt(someNumberToParse, 10).

If I were to write a similar function like this in JS and only ever use it with 10 as a second argument, we could optimise our function to remove logic for other bases, however all tools that I know of fail at this to some degree.

This makes me wonder, would it be possible to write a program that could take any code (module or script) that would track values and types as the code is parsed?

TypeScript is doing it in a way - I can use type guards to narrow down possible types.

I know that for modules, values are most often not known, but a silly example like this:

const add = (a, b = undefined) => {
    if (b > 10) {
        return a + b
    }

    return a + a
}

export const mul2 = a => add(a)

In this case we know that b will never be larger than 10 and we can safely remove the condition.

In effect, we could just optimise to

export const mul2 = a => a + a

Sometimes we can't know the value, but we know it has a certain type(s) or the value matches some conditions.

Is it possible to do that in JS? Would it be possible to do it in a real program (possibly megabytes of code)?

Artur
  • 3
  • 2

0 Answers0