Handle minimum and maximum keywords on number types

This commit is contained in:
Ben Ogle
2014-09-24 09:47:54 -07:00
parent ac67430926
commit f7f28e7995
2 changed files with 47 additions and 1 deletions

View File

@@ -508,6 +508,22 @@ describe "Config", ->
atom.config.set('foo.bar.anInt', 'nope')
expect(atom.config.get('foo.bar.anInt')).toBe 12
describe 'when the minimum and maximum keys are used', ->
beforeEach ->
schema =
type: 'integer'
minimum: 10
maximum: 20
default: 12
atom.config.setSchema('foo.bar.anInt', schema)
it 'keeps the specified value within the specified range', ->
atom.config.set('foo.bar.anInt', '123')
expect(atom.config.get('foo.bar.anInt')).toBe 20
atom.config.set('foo.bar.anInt', '1')
expect(atom.config.get('foo.bar.anInt')).toBe 10
describe 'when the value has an "integer" and "string" type', ->
beforeEach ->
schema =
@@ -540,6 +556,22 @@ describe "Config", ->
atom.config.set('foo.bar.aFloat', 'nope')
expect(atom.config.get('foo.bar.aFloat')).toBe 12.1
describe 'when the minimum and maximum keys are used', ->
beforeEach ->
schema =
type: 'number'
minimum: 11.2
maximum: 25.4
default: 12.1
atom.config.setSchema('foo.bar.aFloat', schema)
it 'keeps the specified value within the specified range', ->
atom.config.set('foo.bar.aFloat', '123.2')
expect(atom.config.get('foo.bar.aFloat')).toBe 25.4
atom.config.set('foo.bar.aFloat', '1.0')
expect(atom.config.get('foo.bar.aFloat')).toBe 11.2
describe 'when the value has a "boolean" type', ->
beforeEach ->
schema =

View File

@@ -404,12 +404,26 @@ Config.addTypeFilters
throw new Error() if isNaN(value)
value
minMaxCoercion: (value, schema) ->
if schema.minimum? and typeof schema.minimum is 'number'
value = Math.max(value, schema.minimum)
if schema.maximum? and typeof schema.maximum is 'number'
value = Math.min(value, schema.maximum)
value
'number':
coercion: (value, schema) ->
value = parseFloat(value)
throw new Error() if isNaN(value)
value
minMaxCoercion: (value, schema) ->
if schema.minimum? and typeof schema.minimum is 'number'
value = Math.max(value, schema.minimum)
if schema.maximum? and typeof schema.maximum is 'number'
value = Math.min(value, schema.maximum)
value
'boolean':
coercion: (value, schema) ->
switch typeof value
@@ -419,7 +433,7 @@ Config.addTypeFilters
!!value
'string':
typeCheck: (value, schema) ->
coercion: (value, schema) ->
throw new Error() if typeof value isnt 'string'
value