Skip to content

Commit

Permalink
fix: iterator uniqueness
Browse files Browse the repository at this point in the history
  • Loading branch information
tpluscode committed Jul 8, 2021
1 parent 079bed7 commit a15434d
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/silent-peas-fold.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"alcaeus": patch
---

Iterating response would return same resource multiple times
13 changes: 11 additions & 2 deletions src/ResourceRepresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import type { ResourceFactory } from '@tpluscode/rdfine/lib/ResourceFactory'
import type { RdfResourceCore } from '@tpluscode/rdfine/RdfResource'
import type { AnyContext, AnyPointer, GraphPointer } from 'clownface'
import type { DatasetCore, NamedNode } from 'rdf-js'
import TermMap from '@rdf-esm/term-map'
import { Term } from '@rdfjs/types'

export interface ResourceRepresentation<D extends DatasetCore = DatasetCore, T extends RdfResourceCore<D> = Hydra.Resource<D>> extends Iterable<Hydra.Resource<D>> {
/**
Expand Down Expand Up @@ -72,8 +74,15 @@ export default class <D extends DatasetCore, T extends RdfResourceCore<D>> imple
}

public [Symbol.iterator]() {
return this.__graph.in()
.map(this._createEntity.bind(this))[Symbol.iterator]()
return this.__graph.in().toArray()
.reduce((uniq, pointer) => {
if (!uniq.has(pointer.term)) {
return uniq.set(pointer.term, this._createEntity(pointer))
}

return uniq
}, new TermMap<Term, Hydra.Resource<D>>())
.values()
}

private _createEntity<T>(node: GraphPointer<ResourceIdentifier>) {
Expand Down
21 changes: 21 additions & 0 deletions tests/ResourceRepresentation-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,27 @@ describe('ResourceRepresentation', () => {
expect(array.map(r => r.id.value).join()).toBe('http://example.com/a,http://example.com/b,http://example.com/c,http://example.com/d')
})

it('should iterate unique resources', () => {
// given
const dataset = $rdf.dataset()
cf({ dataset, graph: ex.a })
.namedNode(ex.a).addOut(rdf.type, ex.Res).addOut(schema.knows, [ex.b, ex.c, ex.d])
.namedNode(ex.c).addOut(schema.knows, [ex.a, ex.d])
.namedNode(ex.d).addIn(schema.knows, ex.a)
const r12n = new ResourceRepresentation(cf({ dataset, graph: ex.a }), factory, ex.a)

// when
const array = Array.from(r12n).map(r => r.id)

// then
expect(array).toHaveLength(2)
expect(array).toStrictEqual(
expect.arrayContaining([
ex.a, ex.c,
]),
)
})

describe('root', () => {
it('should use selection root resource as specified by parameter', () => {
// given
Expand Down

0 comments on commit a15434d

Please sign in to comment.