Skip to content

Commit

Permalink
feat(sparkline): option support for range coercion
Browse files Browse the repository at this point in the history
The default behavior is still to adjust thee range to be zero based. This allows for better relative display of the numbers.
If you need absolute numbers dislayed you can use the option `coerceData:false`
  • Loading branch information
beauraines committed Oct 6, 2024
1 parent 379330c commit 053b14d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,25 +117,40 @@ function getEpochMillis() {
*
* unlabled is just that ▁▂▄▆█
*
* Options supported are
*
* {
* coerceData: true, // coerces the minimum value to zero
* }
*
* @param {array} data Array of values to plot in the sparkline
* @param {string} label Text to display before sparkline, if empty or null, will not display any labels
* @param {object} options Optional options for display, e.g display min,max,last, range coercion
*
* @returns
*/
// eslint-disable-next-line no-unused-vars
function sparkline(data,label,options) {
// TODO add handling if data is object

options = {
coerceData: true,
...options
}

// TODO add handling if data is object
// Assuming data is array
const minValue = Math.min(...data)
const maxValue = Math.max(...data)
const lastValue = data.slice(-1)[0]

// coerces the minimum value to zero because the mimimum option is only used for range validation,
// not display https://github.com/sindresorhus/sparkly/blob/9e33eaff891c41e8fb8c8883f62e9821729a9882/index.js#L15
// sparkly(open,{minimum:27,maximum:50})
// This is the default behavior
if ( options.coerceData ) {
// coerces the minimum value to zero because the mimimum option is only used for range validation,
// not display https://github.com/sindresorhus/sparkly/blob/9e33eaff891c41e8fb8c8883f62e9821729a9882/index.js#L15
// sparkly(open,{minimum:27,maximum:50})
data = data.map( x=> x- minValue)
}

data = data.map( x=> x- minValue)

let sparkline
if (label) {
Expand Down
8 changes: 8 additions & 0 deletions src/helpers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,13 @@ describe('helpers',()=> {
expect(helper.sparkline(input,label)).toBe(expectedOutput)
})

it('should return a sparkline with no range coercion',()=>{
const expectedOutput = '▂▄▅▇█'
const input = [1,2,3,4,5]
const label = ''
const options = { coerceData: false }
expect(helper.sparkline(input,label, options)).toBe(expectedOutput)
})

})

0 comments on commit 053b14d

Please sign in to comment.