Skip to content

Instantly share code, notes, and snippets.

@twlca
Created April 28, 2017 05:14
Show Gist options
  • Save twlca/a9725ccb42cf7e92d9ad84a07396cf12 to your computer and use it in GitHub Desktop.
Save twlca/a9725ccb42cf7e92d9ad84a07396cf12 to your computer and use it in GitHub Desktop.
Patch an array so it can be used as range separator. First we validate the argument is an array then check if each array element is integer. Then we add 0 and infinity to the array.
// patch an array so it add 0 as 1st element and Infinite as last element
function checkArr( arr ) {
try {
Array.isArray( arr );
} catch(e) {
console.log( 'Input arguments is not an array' );
return false;
};
// validate element types
try {
arr.every( function( item ) {
return Number.isInteger( item );
});
} catch(e) {
console.log( 'Elements in array should be all positive integers' );
}
// patch the array
arr.unshift( 0 );
arr.push( Infinity );
return arr;
}
@twlca
Copy link
Author

twlca commented Apr 28, 2017

使用整數陣列作為區段臨界值

在各類報告中,常需要以以數值區段作為統計資料依據。各類統計資料設定的區段不一,很難事先設定。

採用由使用者以 CSV 輸入臨界值,將其轉换成區段陣列後,再由函式呼叫以區別出各臨界值的統計值。

最小值為 0, 最大值為正無限大 (JS 中以 Infinity 代表,是一個 global constant)。

程序為

  1. 驗證輸入參數是陣列
  2. 驗證陣列中的元素皆為整數值
  3. 插入 0 到陣列第一元素,插入 Infinity 到陣列最後元素

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment