import { commit , isImmutable , modify } from '@collectable/core' ; import { HashMap } from '@collectable/map' ; import { HashSetStructure , emptySet , isHashSet , isIterable } from '../internals' ; export function intersect < T > ( other , main ) { var immutable = isImmutable ( main ) ; var outputSet = immutable ? emptySet < T > ( true ) : modify ( main ) ; var outputMap = immutable ? outputSet . _map : HashMap . empty < T , null > ( outputSet ) ; if ( isHashSet < T > ( other ) ) { intersectHashSet ( main . _map , other . _map , outputMap ) ; } else if ( Array . isArray ( other ) ) { intersectArray ( main . _map , other , outputMap ) ; } else if ( other && typeof other === 'object' ) { if ( isIterable < T > ( other ) ) { intersectIterable < T > ( main . _map , other [ Symbol . iterator ] ( ) , outputMap ) ; } } if ( HashMap . size ( outputMap ) === HashMap . size ( main . _map ) ) { return main ; } outputSet . _map = outputMap ; return commit ( outputSet ) ; } function intersectHashSet < T > ( a , b , outputMap ) { var inputMap , otherMap ; if ( HashMap . size ( b ) <= HashMap . size ( a ) ) { inputMap = b ; otherMap = a ; } else { inputMap = a ; otherMap = b ; } return intersectIterable ( inputMap , HashMap . keys ( otherMap ) , outputMap ) ; } function intersectArray < T > ( inputMap , array , outputMap ) { for ( var i = 0 ; i < array . length ; i ++ ) { if ( HashMap . has ( array [ i ] , inputMap ) ) { HashMap . set ( array [ i ] , null , outputMap ) ; } } } function intersectIterable < T > ( inputMap , it , outputMap ) { var current ; while ( ! ( current = it . next ( ) ) . done ) { if ( HashMap . has ( current . value , inputMap ) ) { HashMap . set ( current . value , null , outputMap ) ; } } }