Home > Back-end >  Map numbers to other numbers with interpolation in Javascript
Map numbers to other numbers with interpolation in Javascript

Time:03-10

I have a dataset with a volume for a given surface elevation of an irregular basin. For example:

cm      kL
11870 : 6043453
11871 : 6053522
11872 : 6063591
11873 : 6073674
11874 : 6083767
(...1550 rows)

cm is a series that always increments by one; The associated kL values are irregular but always increase and are never duplicated. The mapping never changes and it can be loaded/stored in any convenient format.

Does Javascript have a simple way to convert between cm and kL? Ideally with linear interpolation in both directions. Ultimately I am looking for this functionality:

cm_to_kL(11872.2); //Expect 6065607.6
kL_to_cm(6065600); //Expect 11872.199

CodePudding user response:

I wrote an example of how to start solving this problem. Like already mentioned, there are no internal functionality for interpolating or handling such structures, but you need to write your own logic.

I have to admit I'm not an expert what comes to math ( it's 2am here, but this question got me interested in :D).

I hope this helps you at least to get started:

const data = {
  11870 : 6043453,
  11871 : 6053522,
  11872 : 6063591,
  11873 : 6073674,
  11874 : 6083767,
};

const cm_to_kL = (val) => {
    const cm_ref = Math.floor(val);
    const factor = parseFloat((val % cm_ref).toFixed(5));
    const lower = data[cm_ref];
    const higher = data[cm_ref   1];

    if (isNaN(lower) || isNaN(higher)) {
        throw Error('Data entry point not found');
    }
    
    const result = lower   ((higher - lower) * factor);

    if (isNaN(result)) {
        throw Error('Incorrect data provided');
    }

    return result;
};

const kL_to_cm = (val) => {
    const [cm, kL] = Object.entries(data).find(([k, v]) => val < v);

    if (isNaN(cm) || isNaN(kL)) {
        throw Error('Data entry point not found');
    }
    
    const lower_cm = cm - 1;
    const lower_kL = data[lower_cm];
    const diff = (val - lower_kL) / (kL - lower_kL);

    const result = parseFloat((lower_cm   diff).toFixed(5))

    if (isNaN(result)) {
        throw Error('Incorrect data provided');
    }

    return result; 
};

console.log('11872.2',
    cm_to_kL(11872.2),
);

console.log('6065600',
    kL_to_cm(6065600),
);

CodePudding user response:

Yes of course JS have to do what you need! You can create 2 Maps from your given array, one for cm to kL and another for kL to cm. Create two functions for them cm_to_kL and kL_to_cm to gat value from Maps after this you can easily get elements with O(1) complexity

  • Related