Results 1 to 14 of 14

Thread: [RESOLVED] VB6 to Javascript

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Resolved [RESOLVED] VB6 to Javascript

    I've created some code in VB6 and was wondering if anyone could help me with converting it to Javascript.

    My main concern is with arrays, i'm not too sure how to use them in javascript, as you will see.

    Here's what i've converted so far (Bolded lines i have not converted, or are unsure about):

    Code:
    var primefactors[0]
    
    function prime_calculation(num_)
    {
    
    var F_;
    var N_;
    var C_;
    
    F_ = 2;
    N_ = num_;
    
    Do 
    {
      If (divide_evenly(N_, F_)==False);
      {
        F_ = F_ + 1;
      }
      else
      {
        If (C_ >= 1) 
        {
          ReDim Preserve PrimeFactors(UBound(PrimeFactors) + 1);
        }
        PrimeFactors(UBound(PrimeFactors)) = F_ ;
        N_ = parseInt(N_ / F_) ;
      }
    
    C_ = C_ + 1;
    }
    while (N_>1)
    
    check_array();
    
    return construct_number_string()
    }
    
    
    function divide_evenly(num1,num2)
    {
    
    If (Num1 / Num2 == parse.Int(Num1 / Num2))
    {
    return 1
    }
    Else
    {
    return 0
    }
    
    }
    
    function check_array()
    {
    
    var TmpArr[];
    var I_;
    
    For I_ = 0 To UBound(PrimeFactors)
    If (PrimeFactors(I_) == 0)
    {
    removeitem (primefactors(), I_);
    }
    Next I_
    
    }
    
    function removeitem(sArray[],index)
    {
    var K;
    
    If (Index < UBound(sArray))
    {
        For K = Index To UBound[sArray] - 1
            sArray[K] = sArray[K + 1];
        Next K
    }
    
    ReDim Preserve sArray(UBound[sArray] - 1)
    
    }
    
    
    function construct_number_string()
    {
    var I_;
    var tmpstr;
    
    For I_ = 0 To UBound[PrimeFactors]
    
    tmpstr = tmpstr + primefactors[I_] + ", ";
    
    Next I_ 
    
    return tmpstr 
    }
    
    }

    Here is the orginal VB6 Code (Please note that i have taken some stuff out, such as the 'on error resume next' and that):


    Code:
    Option Explicit 'Makes sure there's nothing undefined
    
    'Declare program class private variables
    Dim PrimeFactors() As Integer 'Main array for storing prime integers
    
    Private Function Prime_Calculation(Num_ As Integer) As String
    
    On Error GoTo Errors 'If there's an error go to the error handler label
    'There shouldn't be any errors! But meh.
    
    'Declare private variables
    ReDim PrimeFactors(0)
    Dim F_ As Integer
    Dim N_ As Integer
    Dim C_ As Integer 'Used for counting how many times the loop has occured
    
    'Set standard variable integers
    F_ = 2
    N_ = Num_
    
    Do Until N_ <= 1 'Start the loop for discovering the prime numbers
        If Divide_Evenly(N_, F_) = False Then 'If they don't divide evenly then incease F_
            F_ = F_ + 1
        Else 'Or if they do divide evenly
            'Check to see if it's not the first time the loop has happened (Logic errors will happen
                'when the array is checked, and strange prime numbers will occur, some prime numbers
                'will also be missing), Then increase the array's dimensions by 1.
            If C_ >= 1 Then ReDim Preserve PrimeFactors(UBound(PrimeFactors) + 1)
            PrimeFactors(UBound(PrimeFactors)) = F_ 'Place the data (F_) into the last array index
            N_ = Int(N_ / F_) 'Divide N_ by F_ and make the answer N_
        End If
    
    C_ = C_ + 1 'Increase the loop count by 1
    
    Loop 'Loop back to the top
    
    Check_Array 'Check the array for any anomalies
    
    Prime_Calculation = Construct_Number_String 'Construct the string and pass it to the calling sub
    
    Exit Function 'Exit the function (Will go to the error handler otherwise)
    
    Errors: 'Error handler label
        MsgBox "You are experiencing a mysterious error that shouldn't exist." 'Have a laugh.
    Exit Function 'Exit the function so the program won't crash
    
    End Function
    
    Private Function Divide_Evenly(Num1 As Integer, Num2 As Integer) As Boolean
    
    'Checks to see if the rounded number is the same as the non-rounded number
    If Num1 / Num2 = Int(Num1 / Num2) Then
        Divide_Evenly = True
    Else
        Divide_Evenly = False
    End If
    
    End Function
    
    Private Sub Check_Array()
    On Error Resume Next 'If there's an error continue to the next line ignoring the error line
    
    'Declare private variables
    Dim TmpArr() As Integer
    Dim I_ As Integer
    
    'If 0 is present in the array, remove that array index
    For I_ = 0 To UBound(PrimeFactors)
        If PrimeFactors(I_) = 0 Then RemoveItem PrimeFactors(), I_
    Next I_
    
    End Sub
    
    Private Sub RemoveItem(sArray() As Integer, ByVal Index As Integer)
    'Thanks to Static on VBforums for this sub's code
    '(http://www.vbforums.com/showthread.php?t=451353&highlight=remove+array+index)
    
    Dim K As Integer
    
    If Index < UBound(sArray) Then
        For K = Index To UBound(sArray) - 1
            sArray(K) = sArray(K + 1)
        Next K
    End If
    
    ReDim Preserve sArray(UBound(sArray) - 1)
    
    End Sub
    Private Function Construct_Number_String(Optional Before_ = "", Optional After_ = ", ", Optional Include_ = False) As String
    
    'Before_ is any formatting that goes before the number
    'After_ is any formatting that goes after the number (Default is ", ", Comma and a space)
    'Include_ is whether the user wants the last number to have the formatting on the end (True), or not (False)
    
    'Declare private variables
    Dim I_ As Integer
    Dim TmpStr As String
    
    For I_ = 0 To UBound(PrimeFactors) 'Go through every index
    
        If I_ = UBound(PrimeFactors) Then 'If at the end of the array then
            If Include_ = True Then 'Check to see if Include has been enabled
                TmpStr = TmpStr & Before_ & PrimeFactors(I_) & After_ 'Place the formatting on the end
            Else 'Or if Include is not enabled
                TmpStr = TmpStr & Before_ & PrimeFactors(I_) 'Ommit the formatting
            End If
        Else
            TmpStr = TmpStr & Before_ & PrimeFactors(I_) & After_ 'Continue constructing the string
        End If
    
    Next I_ 'Do the next index in the array
    
    Construct_Number_String = TmpStr 'Place the temporary string into the sub to be transfered into the calling sub
    
    End Function
    
    Private Sub CmdCalculate_Click()
    
    On Error GoTo Errors 'If there's an error go to the error handler label
    
    'Check if the number is 4 or larger (There is no use for it to be smaller)
    If PrimeTxt.Text <= 3 Then
        MsgBox "Please enter a number larger then 4."
        Exit Sub
    End If
    
    'Integers can only take numbers up to 32767 before an overflow happens. Stop the user from causing this error
    If PrimeTxt.Text >= 32768 Then
        MsgBox "Please enter a number less then 32768."
        Exit Sub
    End If
    
    AnswerTxt.Text = Prime_Calculation(PrimeTxt.Text) 'Display the data
    
    Exit Sub 'Exit the sub (Will go to the error handler otherwise)
    
    Errors: 'Error handler label
        MsgBox "The number that you have inputted is invalid." 'Inform the user of the error
    Exit Sub 'Exit the sub so the program won't crash
    
    End Sub

    Any help will be appreciated (I don't expect you to solve it all for me, but rather point out errors, and me in the right direction).

    I will fix up the little errors (Such as cases not matching and that) once i have properly translated it into javascript.

  2. #2
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: VB6 to Javascript

    In javascript (someone correct me if I'm wrong) if you assign a value to an element corresponding to position x+1, the size of the array automatically increases. This means that you don't need to find an equivalent of redim preserve.

  3. #3
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: VB6 to Javascript

    What naming convention is that called? Highly unusual.

  4. #4

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: VB6 to Javascript

    So when another element is added to an array's dimension (even though it's outside the arrays bounds) the array automatically resizes?

    What about removing an element from an array & having all the later elements move down so there's no gap?

    This code is from an assignment i did last year (Passed 100% mind you). We're learning javascript now & if i could figure out arrays in javascript, then i'm home free (I'd know enough to pass it 100% too) so i want to learn before we need to.

    That's why i wish to know how arrays work, and any other things that i might have missed, so i can do them in class when i need to =).

  5. #5
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: VB6 to Javascript

    Use the push method to append an item to an array.

  6. #6

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: VB6 to Javascript

    What about removing an element from an array & having all the later elements move down so there's no gap?

  7. #7
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: VB6 to Javascript

    Code:
    // example usage:
    gen_primes(1, 42).forEach(document.write)
    
    // generate and return an array of prime numbers
    function gen_primes(min, max)
    {
      var primes = [];
      
      min = Math.floor(min);
      max = Math.floor(max);
      
      for (x = min; x <= max; ++x)
        if (is_prime(x)) primes.push(x);
      
      return primes;
    }
    
    // assumes x is an integer
    function is_prime(x)
    {
      var n = x - 1;
      while (n > 1) if (x / n-- % 1 == 0) return false;
      return true;
    }

  8. #8
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: VB6 to Javascript

    Quote Originally Posted by Slyke
    What about removing an element from an array & having all the later elements move down so there's no gap?
    You try not to.


    JavaScript arrays are hashtables. They are not stored in a linear fashion. This makes addressing very quick, but moving things around rather slow.

    Treat them like collections; use for(x in y) rather than for( ; ; ) to enumerate items. Set offsets to null to effectively remove items.

  9. #9
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: VB6 to Javascript

    Very nice, thanks Pena. You learn something new every day. I had always wondered why I was using for(x in y) but never bothered to find out.

  10. #10

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: VB6 to Javascript

    Thanks dude =), will test this out when i get time. It's gonna take a bit to get my head around this code;

    Especially this line: while (n > 1) if (x / n-- % 1 == 0) return false;

    While n is more then 1
    If (x divided by n minus 1?) mod 1 equals 0 then
    return false
    end if
    loop

    You're a legend =).

  11. #11
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: VB6 to Javascript

    If you are testing primality, you need to repeat the test 6-10 times. This rule determines the likelihood the number is a prime by finding the GCD of that and any number less than that number is one.

    It is impossible for a prime number not to conform to that rule but it is possible (but unlikely) that a non prime does. Repeating the test with several numbers will decrease the degree of uncertainty exponentially.
    Last edited by visualAd; Mar 3rd, 2008 at 02:57 PM.
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  12. #12
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: VB6 to Javascript

    Quote Originally Posted by Slyke
    If (x divided by n minus 1?) mod 1 equals 0 then
    Almost.

    "If x divided by n mod 1 equals 0 then return false
    end if
    Subtract 1 from x"

    --n, on the other hand, subtracts 1 before returning the value:
    "Subtract 1 from x
    If x divided by n... etc."

  13. #13

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: VB6 to Javascript

    Quote Originally Posted by visualAd
    If you are testing primality, you need to repeat the test 6-10 times. This rule determines the likelihood the number is a prime by finding the GCD of that and any number less than that number is one.

    It is impossible for a prime number not to conform to that rule but it is possible (but unlikely) that a non prime does. Repeating the test with several numbers will decrease the degree of uncertainty exponentially.
    Wow, that explanation is totally awesome.


    Thanks penagate, that helped me understand what you did =). I'll close the thread.

  14. #14

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: [RESOLVED] VB6 to Javascript

    Okay, i know this is old, but i successfully converted everything.

    So if anyone in the future comes past this thread and has a similar problem, then they can get help here.

    Code:
    <script>
    
    var primefactors = new Array();
    
    function prime_calculation(num_)
    {
    
    var F_;
    var N_;
    var C_;
    var varrl;
    
    F_ = 2;
    N_ = num_;
    C_ = 0;
    
    do
    {
    
      if (divide_evenly(N_, F_)==0)
      {
        F_ = F_ + 1;
      }
      else
      {
        if (C_ >= 1) 
        {
          primefactors.push("");
        }
    		varrl=primefactors.length;
        primefactors[varrl] = F_ ;
        N_ = parseInt(N_ / F_);
      }
    
    C_ = C_ + 1;
    }
    while (N_>1)
    
    check_array();
    
    return construct_number_string()
    }
    
    
    function divide_evenly(num1,num2)
    {
    var tmpdta;
    
    tmpdta=parseInt(num1 / num2);
    if (num1 / num2 == tmpdta)
    {
    return 1
    }
    else
    {
    return 0
    }
    
    }
    
    function check_array()
    {
    var I_;
    var varrl;
    
    I_=0;
    varrl=primefactors.length;
    
    for (I_ = 0; I_ <= varrl; I_++)
    {
      if (primefactors[I_] == 0)
      {
        primefactors.splice(I_, 1); 
      }
    }
    return 0
    }
    
    
    function construct_number_string()
    {
    var Q_;
    var tmpstr="";
    var varrl;
    
    varrl=primefactors.length-1;
    
    Q_=0;
    
    for (Q_ = 0; Q_ <= varrl; Q_++)
    {
    if (Q_ == varrl)
    {
    tmpstr = tmpstr + primefactors[Q_];
    }
    else
    {
    tmpstr = tmpstr + primefactors[Q_] + ", ";
    }
    }
    funcleanarr()
    return tmpstr 
    }
    
    function funcleanarr()
    {
    var Q_;
    var tmpstr="";
    var varrl;
    
    varrl=primefactors.length;
    
    Q_=0;
    
    for (Q_ = 0; Q_ <= varrl; Q_++)
    {
    
    primefactors.splice(0,varrl);
    }
    }
    
    
    function funwritetopage(vvalue)
    { //Function to write the result to the webpage.
    var element = document.getElementById('answer');
    var text = document.createTextNode(vvalue);
    
    // Check if the page has an answer already, and if not then create one, if it does then rewrite over it.
    if (element.hasChildNodes()) 
    {
    element.replaceChild(text, element.childNodes[0]);
    }
    else
    {
    element.appendChild(text);
    }
    }
    
    function funcalculate (form) 
    { //The event triggered by the button.
    
    
    rsult = prime_calculation(form.numbertxt.value)
    
    funwritetopage(rsult);
    }
    
    </script>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width