I am trying to create a function to convert metres per second (m/s) to Beaufort scale in Javascript. I can do this using a series of if statements, but it I would much prefer to replace this with the formula to dynamically calculate this for me.
This is what my research has enabled me to achieve so far:
function beaufort(ms) {
ms = Math.abs(ms);
if (ms <= 0.2) {
return 0;
}
if (ms <= 1.5) {
return 1;
}
if (ms <= 3.3) {
return 2;
}
if (ms <= 5.4) {
return 3;
}
if (ms <= 7.9) {
return 4;
}
if (ms <= 10.7) {
return 5;
}
if (ms <= 13.8) {
return 6;
}
if (ms <= 17.1) {
return 7;
}
if (ms <= 20.7) {
return 8;
}
if (ms <= 24.4) {
return 9;
}
if (ms <= 28.4) {
return 10;
}
if (ms <= 32.6) {
return 11;
}
return 12;
}
I would like to replace this with a function that automatically calculates using the correct formula. Doe anyone know how this can be achieved without multiple if statements or switch case?
Ok, so after reading several articles there seems to be a formula to calculate Beaufort to and from m/s. I will answer my own post with a couple of functions that I have made.
Calculate m/s to beaufort:
function msToBeaufort(ms) {
return Math.ceil(Math.cbrt(Math.pow(ms/0.836, 2)));
}
msToBeaufort(24.5);
output: 10
Calculate beaufort to m/s:
function beaufortToMs(bf){
return Math.round(0.836 * Math.sqrt(Math.pow(bf, 3)) * 100)/ 100;
}
beaufortToMs(3)
output: 4.34
I know its a rare topic, but hopefully this helps someone.