puntable
puntable

Reputation: 337

Calculate price from width and height

The question is divided into 2 parts.

1. How to structure the data in the json array

2. How to calculate the price from the json array

I need to store the price data inline in HTML as JSON, as AJAX requests to the server are too slow/heavy.

The data are stored as serialized strings in a database. This is added to the database from CSV file uploads. The CSV files looks like below.

      50    100    150    200    250
20    70     90    110    130    150
30    90    110    130    150    170
40    110   130    150    170    190
50    130   150    170    190    210
60    150   170    190    210    230

If you enter 100 in width and 40 in height, the price should be 130.

If you enter 170 in width and 52 in height the price should be 210.

If column or row is not found, it should round up to next column or row.

  1. What is the best way to store this as JSON inline, if you need to calculate the price based on width and heigth?

  2. How would you calculate the price, based on user input width and height?

I am not looking for specific code, just suggestions on the JSON structure and how to calculate from this.

Upvotes: 1

Views: 417

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28226

When there is a regular pattern for the width and height steps you could also do the following:

const h0=20,dh=10,w0=50,dw=50, prices=
 [[  70,   90,  110,  130,  150],
  [  90,  110,  130,  150,  170],
  [ 110,  130,  150,  170,  190],
  [ 130,  150,  170,  190,  210],
  [ 150,  170,  190,  210,  230]];

// w,h
[[100,30],[90,25]].forEach(([w,h])=>
 console.log(prices[Math.ceil((h-h0)/dh)][Math.ceil((w-w0)/dw)]));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386746

You could take two arrays for widths and heights and a 2D array for the prices.

For getting a right price get the indices first and then the price.

Maybe you need to add some guard for the values to prevent getting wrong indices.

const
    getPrice = (width, height) => {
       const
           w = widths.findIndex(w => width <= w),
           h = heights.findIndex(h => height <= h);
       return prices[w][h];       
    },
    widths = [50, 100, 150, 200, 250],
    heights = [20, 30, 40, 50, 60],
    prices = [[70, 90, 110, 130, 150], [90, 110, 130, 150, 170], [110, 130, 150, 170, 190], [130, 150, 170, 190, 210], [150, 170, 190, 210, 230]];
    

console.log(getPrice(100, 30));
console.log(getPrice(90, 25));

Upvotes: 2

Related Questions