0

I would like to convert the following code from php to JavaScript:

$price = '270';

$allowed_sms_prices = array(
 5,7,10,15,20,25,30,35,39,40,
 45,49,50,55,59,60,69,75,79,85,
 89,95,100,125,150,175,200,225,250,275,
 300,310,315,320,325,330,335,340,345,350,
 355,360,365,370,375,380,385,390,395,400,
 405,410,415,420,425,430,435,440,445,450,
 455,460,465,470,475,480,485,490,495,500
);

while( ! in_array( $price, $allowed_sms_prices ) )
{
     $price = $price + 1;
}
echo $price;
1
  • 4
    If you'd have $price = 501; that would be an endless loop :) Commented Nov 16, 2012 at 20:31

1 Answer 1

3

Here is a javascript equivalent:

$price = 270;

$allowed_sms_prices = Array(
 5,7,10,15,20,25,30,35,39,40,
 45,49,50,55,59,60,69,75,79,85,
 89,95,100,125,150,175,200,225,250,275,
 300,310,315,320,325,330,335,340,345,350,
 355,360,365,370,375,380,385,390,395,400,
 405,410,415,420,425,430,435,440,445,450,
 455,460,465,470,475,480,485,490,495,500
);

while( $allowed_sms_prices.indexOf($price) == -1 )
{
     $price = $price + 1;
}
alert($price);

See how easy that was?

There is still a problem with your logic, namely that there is no reliable exit condition for the loop. For example, if the $price value was greater than 500, the loop would run indefinitely. There are several approaches you could take that could correct this, one of which is to check if the value is not larger than the greatest value in the array.

Sign up to request clarification or add additional context in comments.

10 Comments

@phpisuber01: $ can be part of a variable name, if you want.
@phpisuber01 I just wanted to make the point that the changes that were required were minimal.
@azizpunjani That would be a correction of his logic. I am simply duplicating his logic in a different language.
@azizpunjani I have edited my answer to mention this concern, however.
@Asad: I can't be bothered :P, it's just as a side-note, that might be of interest to the OP. The only thing I can't stand, though, is the (ab)use of the array constructor. I know you wanted the code to resemble the PHP code as much as possible, but PHP 5.4 now supports the [] array-notation, too. It also supports lambda functions and json_decode decodes to objects by default. It looks as if they're cherry-picking JS for the good parts :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.