[Pas2js] Built-in helper methods for Double type

Mattias Gaertner nc-gaertnma at netcologne.de
Wed Sep 4 23:25:11 CEST 2019


On Wed, 4 Sep 2019 11:26:42 -0700 (MST)
warleyalex via Pas2js <pas2js at lists.freepascal.org> wrote:

> solution using type helpers:
> ==================
> type
>   Float = Double;
> 
> type
> { TDoubleHelper }
> TDoubleHelper = type helper for Float
>    function toFixed(aNumber: Double; fractionDigits: integer): string;
> assembler;
> end;
> 
> { TDoubleHelper }
> function TDoubleHelper.toFixed(aNumber: Double; fractionDigits:
> integer): string; assembler;
> asm
>   return Number(aNumber).toFixed(fractionDigits);
> end;
> 
> 
> var
>   ReturnValue: float;
>   x: String;
> begin
>   x := ReturnValue.toFixed(sin(10.1) * 2.5, 2); 
> 
>   rtl.createHelper($mod,"TDoubleHelper",null,function () {
>     this.toFixed = function (aNumber, fractionDigits) {
>       return Number(aNumber).toFixed(fractionDigits);
>     };
>   });
> 
>    $mod.x = $mod.TDoubleHelper.toFixed.call({p: $mod, get: function
> () { return this.p.ReturnValue;
>      }, set: function (v) {
>        this.p.ReturnValue = v;
>      }},Math.sin(10.1) * 2.5,2);
> 
> 
> Personaly, I don't like being able to specify a type helper, jsut
> because Class helpers are not attractive. It's a kind of weird
> thing :)
> 
> I just want to determine X and cut to 2 decimals, using type helper,
> this weird syntax:
> 
>   x := ReturnValue.toFixed(sin(rad) * r, 2); // type helpers it's
> weird and generates extra code

Delphi defines type helpers as pass value by reference - a type helper
can modify the value. That's why pas2js must for compatibility
reasons create this weird awkward code.
Iff there would be a modifier or attribute to define a read only type
helper method, the compiler could create shorter code. 

Another possibility would be a whole program analysis to spot if a
type helper method is read-only and never referenced via address. But
that would only work for Pascal methods, not external ones.

Mattias


More information about the Pas2js mailing list