Skip to content

Commit

Permalink
feature: add dagEdgesParent
Browse files Browse the repository at this point in the history
slight optimization of dagEdgesResolve
  • Loading branch information
0b5vr committed Feb 19, 2022
1 parent 9a160f2 commit 26d8cda
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/dag/dagEdgesParent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { RawDagEdge } from './RawDagEdge';

/**
* Return first parent source the specified destination has.
* If it can't find a parent, it will return `null` instead.
*
* @param edges An array of dag edge
* @param destination The target destination
*
* See also: {@link dagEdgesParents}
*/
export function dagEdgesParent<T>( edges: RawDagEdge<T>[], destination: T ): T | null {
return edges.find( ( edge ) => edge[ 1 ] === destination )?.[ 0 ] ?? null;
}
4 changes: 2 additions & 2 deletions src/dag/dagEdgesResolve.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RawDagEdge } from './RawDagEdge';
import { dagEdgesParents } from './dagEdgesParents';
import { dagEdgesParent } from './dagEdgesParent';

/**
* Resolve dag dependency relationship and give you a correct order.
Expand All @@ -16,7 +16,7 @@ export function dagEdgesResolve<T>( edges: RawDagEdge<T>[], nodes: T[] ): T[] {
while ( tempEdges.length > 0 ) {
nodeSet.forEach( ( node ) => {
// is this an entrypoint?
const hasParents = dagEdgesParents( tempEdges, node ).length > 0;
const hasParents = dagEdgesParent( tempEdges, node ) != null;

if ( !hasParents ) {
if ( nodeSet.has( node ) ) {
Expand Down
1 change: 1 addition & 0 deletions src/dag/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './dagEdgesAncestors';
export * from './dagEdgesChildren';
export * from './dagEdgesDescendants';
export * from './dagEdgesParent';
export * from './dagEdgesParents';
export * from './dagEdgesResolve';
export * from './RawDagEdge';
21 changes: 21 additions & 0 deletions src/dag/tests/dagEdgesParent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { dagEdgesParent } from '../dagEdgesParent';
import type { RawDagEdge } from '../RawDagEdge';

describe( 'dagEdgesParent', () => {
it( 'returns a parent of the specified destination from the given edges', () => {
const edges: RawDagEdge<string>[] = [
[ 'a', 'b' ],
[ 'b', 'c' ],
[ 'a', 'd' ],
[ 'a', 'e' ],
[ 'b', 'e' ],
[ 'c', 'e' ],
[ 'b', 'f' ],
[ 'e', 'f' ],
];

const subject = dagEdgesParent( edges, 'f' );

expect( subject ).toBe( 'b' );
} );
} );

0 comments on commit 26d8cda

Please sign in to comment.