Skip to content

Commit

Permalink
feat(parsers/newline): add newline parser
Browse files Browse the repository at this point in the history
  • Loading branch information
norskeld committed Nov 28, 2021
1 parent 0aaa159 commit ae8d6ec
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/internal/parsers/newline.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Parser } from '../state'

import { choice } from '../combinators/choice'
import { error } from '../combinators/error'
import { string } from './string'

const EOL_UNIX = '\n'
const EOL_NON_UNIX = '\r\n'

export function newline(): Parser<string> {
return error(choice(string(EOL_UNIX), string(EOL_NON_UNIX)), 'newline')
}

export { newline as eol }
1 change: 1 addition & 0 deletions src/parsers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './internal/parsers/defer'
export * from './internal/parsers/eof'
export * from './internal/parsers/newline'
export * from './internal/parsers/float'
export * from './internal/parsers/integer'
export * from './internal/parsers/lazy'
Expand Down
45 changes: 45 additions & 0 deletions tests/internal/parsers/newline.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { sequence } from '@lib/internal/combinators/sequence'
import { newline } from '@lib/internal/parsers/newline'
import { letters } from '@lib/internal/parsers/letter'

import { run, result, should } from '@tests/@helpers'

const tcase = `Hello\nWorld\n`
const tcaseLit = `Hello
World
`

describe(newline, () => {
it('should succeed if given a newline (Unix)', () => {
const actual = run(newline(), '\n')
const expected = result('success', '\n')

should.matchState(actual, expected)
})

it('should succeed if given a newline sequence (non-Unix)', () => {
const actual = run(newline(), '\r\n')
const expected = result('success', '\r\n')

should.matchState(actual, expected)
})

it('should succeed if given a string with a newline at the end', () => {
const parser = sequence(letters(), newline(), letters(), newline())

const actualExplicit = run(parser, tcase)
const actualImplicit = run(parser, tcaseLit)

const expected = result('success', ['Hello', '\n', 'World', '\n'])

should.matchState(actualExplicit, expected)
should.matchState(actualImplicit, expected)
})

it('should fail if given a string without a newline', () => {
const actual = run(sequence(letters(), newline()), 'Hello')
const expected = result('failure', 'newline')

should.matchState(actual, expected)
})
})
2 changes: 2 additions & 0 deletions tests/parsers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ it('should expose parsers', () => {
'letters',
'nothing',
'nil',
'newline',
'eol',
'regexp',
're',
'rest',
Expand Down

0 comments on commit ae8d6ec

Please sign in to comment.