Skip to content

Commit

Permalink
avoid dividing by zero & handle single value
Browse files Browse the repository at this point in the history
  • Loading branch information
pokutuna committed Jun 17, 2019
1 parent 9f54e60 commit 19a3e63
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
7 changes: 3 additions & 4 deletions asciichart.js
Expand Up @@ -17,7 +17,7 @@
let offset = (typeof cfg.offset !== 'undefined') ? cfg.offset : 3
let padding = (typeof cfg.padding !== 'undefined') ? cfg.padding : ' '
let height = (typeof cfg.height !== 'undefined') ? cfg.height : range
let ratio = height / range
let ratio = range !== 0 ? height / range : 1;
let min2 = Math.round (min * ratio)
let max2 = Math.round (max * ratio)
let rows = Math.abs (max2 - min2)
Expand All @@ -33,9 +33,8 @@
result[i][j] = ' '
}
}

for (let y = min2; y <= max2; ++y) { // axis + labels
let label = format (max - (y - min2) * range / rows, y - min2)
let label = format (rows > 0 ? max - (y - min2) * range / rows : y, y - min2)
result[y - min2][Math.max (offset - label.length, 0)] = label
result[y - min2][offset - 1] = (y == 0) ? '┼' : '┤'
}
Expand All @@ -62,4 +61,4 @@
return result.map (function (x) { return x.join ('') }).join ('\n')
}

}) (typeof exports === 'undefined' ? /* istanbul ignore next */ this['asciichart'] = {} : exports);
}) (typeof exports === 'undefined' ? /* istanbul ignore next */ this['asciichart'] = {} : exports);
10 changes: 9 additions & 1 deletion test.js
Expand Up @@ -36,4 +36,12 @@ var s2 = new Array (width)
s2[0] = Math.round (Math.random () * 15)
for (i = 1; i < s2.length; i++)
s2[i] = s2[i - 1] + Math.round (Math.random () * (Math.random () > 0.5 ? 2 : -2))
console.log (asciichart.plot (s2) + "\n")
console.log (asciichart.plot (s2) + "\n")

console.log (line)
console.log ("single value\n")

var s3 = new Array (width)
for (i = 0; i < width; i++)
s3[i] = 1.0
console.log (asciichart.plot (s3) + "\n")

0 comments on commit 19a3e63

Please sign in to comment.