如何使这些javascript语句看起来更具可读性.函数库ramda.js可以用来使这段代码看起来更好吗?
var getTextSpace = function(len) { var tlength; if (len >= 1 && len <= 4) { tlength = 10; } else if (len === 5) { tlength = 14; } else if (len === 6) { tlength = 16; } else if (len === 7) { tlength = 18; } else if (len >= 8 && len <= 10) { tlength = 20; } else if (len === 11) { tlength = 22; } else if (len === 12) { tlength = 24; } else if (len >= 13 && len <= 15) { tlength = 26; } else if (len === 16) { tlength = 28; } else if (len >= 17 && len <= 20) { tlength = 32; } else if (len >= 21 && len <= 34) { tlength = tlength * 2; } else if (len >= 35 && len <= 80) { tlength = Math.round((len + len / 100 * 50)); } else { tlength = Math.round((len + len / 100 * 30)); } return tlength; };
先感谢您.
也许有可能做一些允许这样做的事情?
value .between(2,20).then(20) .between(21,22).then(0) .greater(25).then(25)) .less(30).then(function(value) {return value * 20 )})
Scott Sauyet.. 6
拉姆达可能会有所帮助.但主要的是以可读的方式构建范围.下面的代码假定输入值是整数,您不需要测试其他数字类型.那些可以做到,但是你需要比between
这里简单更复杂的东西.您需要多个功能或一种方法来配置一个功能,以确定每个开头和结尾是包含还是排他.
var getTextSpace = (function() { // :: (Int, Int) -> (Int -> Bool) var between = (begin, end) => R.both(R.gte(R.__, begin), R.lt(R.__, end)); return R.cond([ [between(1, 5), R.always(10)], [between(5, 6), R.always(14)], [between(6, 7), R.always(16)], [between(7, 8), R.always(18)], [between(8, 11), R.always(20)], [between(11, 12), R.always(22)], [between(12, 13), R.always(24)], [between(13, 16), R.always(26)], [between(16, 17), R.always(28)], [between(17, 21), R.always(32)], [between(21, 35), R.multiply(2)], // assuming original was typo [between(35, 80), len => Math.round(len + len / 100 * 50)], [R.T, len => Math.round(len + len / 100 * 30)] ]); }());
(原始案例中似乎存在错误:
} else if (len >= 21 && len <= 34) { tlength = tlength * 2;
我认为这意味着什么
} else if (len >= 21 && len <= 34) { tlength = len * 2;
我在这里编写了相应的代码.)
您可以在Ramda REPL上看到这一点.
拉姆达可能会有所帮助.但主要的是以可读的方式构建范围.下面的代码假定输入值是整数,您不需要测试其他数字类型.那些可以做到,但是你需要比between
这里简单更复杂的东西.您需要多个功能或一种方法来配置一个功能,以确定每个开头和结尾是包含还是排他.
var getTextSpace = (function() { // :: (Int, Int) -> (Int -> Bool) var between = (begin, end) => R.both(R.gte(R.__, begin), R.lt(R.__, end)); return R.cond([ [between(1, 5), R.always(10)], [between(5, 6), R.always(14)], [between(6, 7), R.always(16)], [between(7, 8), R.always(18)], [between(8, 11), R.always(20)], [between(11, 12), R.always(22)], [between(12, 13), R.always(24)], [between(13, 16), R.always(26)], [between(16, 17), R.always(28)], [between(17, 21), R.always(32)], [between(21, 35), R.multiply(2)], // assuming original was typo [between(35, 80), len => Math.round(len + len / 100 * 50)], [R.T, len => Math.round(len + len / 100 * 30)] ]); }());
(原始案例中似乎存在错误:
} else if (len >= 21 && len <= 34) { tlength = tlength * 2;
我认为这意味着什么
} else if (len >= 21 && len <= 34) { tlength = len * 2;
我在这里编写了相应的代码.)
您可以在Ramda REPL上看到这一点.