COMMUNITY

How to convert this js code to haxe?

code from

m = {0: 1, 1: 1}

var fib = function(n) {
  if (n in m) return m[n];
  return m[n] = fib(n - 1) + fib(n - 2);
};

console.log(fib(46));

I try to conver to this use Map<Int64,but failed

 import haxe.Int64;

    class TestUV {
        static var map:Map<Int64, Int64> = [];

        public static function fib(n:Int64):Int64 {
            if (map.exists(n)) {
                return map[n];
            }
            return map[n] = fib(n - 1) + fib(n - 2);
        }

        static function main() {
            map[0] = 1;
            map[1] = 1;

            var t1 = Date.now().getTime();
            trace(fib(46));

            var t2 = Date.now().getTime();

            trace(t2 - t1);
        }
    }

You should replace everywhere Int64 with Int.

@alex_dja … but you will get an overflow (i.e. instead of having 2971215073 for fib(46), you will get -1323752223).

Not optimal: you can try to use a string map to store the Int64 values.

using haxe.Int64;

class TestUV {
	static final map: Map<String, String> = [
		"0" => "1",
		"1" => "1"
 	];

	public static function fib(n: Int64): Int64 {
		final value = n.toStr();
		if (!map.exists(value)) map[value] = (fib(n - 1) + fib(n - 2)).toStr();
		return map[value].parseString();
	}

	static function main() {
		trace(fib(46));
	}
}

In js target case you would’t https://try.haxe.org/#9594c.

Of course :smile: !
Haxe’s Int maps to Number when targeting JS… and the Number type is a double-precision 64-bit binary format IEEE 754 value.

@Zhan What is your target? If you encountered an error, I guess it’s not JS…

I want to test js target and hl target .and I found there is a bug about Map<Int64,Int64>

As a workaround you can try this:

typedef MyInt64 = 
#if js 
  Int;
#elseif hl
  hl.I64;
// and so on
#end
...
static var map:Map<MyInt64, MyInt64> = [];
2 Likes

I don’t think it’s best way to use that .because orgin code is target to js

fib(46)

how about this https://try.haxe.org/#178c9 ?

1 Like

wow!,it’s work!