Skip to content

Commit

Permalink
feat(utils): slice
Browse files Browse the repository at this point in the history
Signed-off-by: Lexus Drumgold <[email protected]>
  • Loading branch information
unicornware committed Mar 4, 2024
1 parent aa3c242 commit 0e71947
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 0 deletions.
61 changes: 61 additions & 0 deletions src/utils/__tests__/slice.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* @file Unit Tests - slice
* @module esast-util-attach-comments/utils/tests/unit/slice
*/

import type { State } from '#src/types'
import type { NewExpression } from 'estree'
import testSubject from '../slice'

describe('unit:utils/slice', () => {
let node: NewExpression
let state: State

beforeAll(() => {
state = {
comments: [
{
position: {
end: { column: 33, line: 11, offset: 411 },
start: { column: 18, line: 11, offset: 396 }
},
type: 'Block',
value: ' @__PURE__ '
},
{
position: {
end: { column: 27, line: 14, offset: 535 },
start: { column: 12, line: 14, offset: 520 }
},
type: 'Block',
value: ' @__PURE__ '
}
],
index: 0
}

node = {
arguments: [],
callee: {
name: 'Set',
position: {
end: { column: 41, line: 11, offset: 419 },
start: { column: 38, line: 11, offset: 416 }
},
type: 'Identifier'
},
position: {
end: { column: 43, line: 11, offset: 421 },
start: { column: 34, line: 11, offset: 412 }
},
type: 'NewExpression'
}
})

it('should return slice from state.comments', () => {
expect(testSubject(state, node))
.to.be.an('array')
.of.length(1)
.with.deep.ordered.members([state.comments[0]])
})
})
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@

export { default as compare } from './compare'
export { default as keycheck } from './keycheck'
export { default as slice } from './slice'
48 changes: 48 additions & 0 deletions src/utils/slice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* @file Utilities - slice
* @module esast-util-attach-comments/utils/slice
*/

import type { State } from '#src/types'
import type { Comment, Node } from 'estree'
import compare from './compare'

/**
* Get a comments slice.
*
* @see {@linkcode Comment}
* @see {@linkcode Node}
* @see {@linkcode State}
*
* @internal
*
* @this {void}
*
* @param {State} state - Visitor state
* @param {Node} node - Node being visited
* @param {boolean?} [trailing] - Trailing comments slice?
* @return {Comment[]} Slice from `state.comments`
*/
function slice(
this: void,
state: State,
node: Node,
trailing?: boolean
): Comment[] {
/**
* Slice result.
*
* @const {Comment[]} result
*/
const result: Comment[] = []

// get slice
while (
state.comments[state.index] &&
compare(state.comments[state.index]!, node, trailing) < 1
) result.push(state.comments[state.index++]!)

return result
}

export default slice

0 comments on commit 0e71947

Please sign in to comment.