Saikat Chakrabortty
Saikat Chakrabortty

Reputation: 2680

convert python function to Javascript/node.js

trying to simulate similar behavior of a python function with node.js.

Here is the python function:

Input (for both of the function):

(9x11)JHASGJHAYGGSDFLRAAAA(16x7)ABCDEFG
def evaluate_expression(sub_string):
    var re = require('re')
    regex = r'^([(](\d+)[xX](\d+)[)])?'
    prog = re.compile(regex)
    op = prog.match(sub_string)
    print('in evaluate exp', sub_string)
    expression_list = list(op.groups())
    # print(expression_list)
    str_len = int(expression_list[1])
    itr = int(expression_list[2])
    endindex = op.end()
    return str_len, itr, endindex-1

Output:

5 9 11

in JS i have tried so far:

evaluate_expression = (sub_string)=>{
    const a =/^([(](\d+)[xX](\d+)[)])?/g;
    const b = sub_string.match(a);
    // console.log(sub_string)
    let extratkted = b[0].split("x");
    return {
      str_len:extratkted[0].split("(")[1],
      itr:extratkted[1].split(")")[0],
    endpoint:extratkted.length+extratkted.length+extratkted.length-2
  }

 }

Output:

{str_len:9,itr:11,endpoint:4}

where Expected output: {str_len:5,itr:9,endpoint:11}

Upvotes: 0

Views: 226

Answers (1)

furas
furas

Reputation: 142631

It seem you have good values but they are assigned in wrong order.

In Python you use [1] and [2] but in Javascript you use different order [1], and [0]. If you assign values in different order then you should get correct result.


In Python you have endindex-1 but in JavaScript you do something similar to endindex-2 so you get 4 instead of 5.

Upvotes: 1

Related Questions