import { IDataModel } from '../Models/DataModels/Base' ; import { Utils } from './Utils' ; import keyBy from 'lodash/keyBy' ; export class CollectionUtils { /**
     * Update collection by following rules:
     *  - deleting items which are not in new collection
     *  - update item using update delegate
     *  - add new items using create delegate
     */ public static updateCollection < T , P > ( collection , newCollection , keySelector , newKeySelector , create , update , appendOnly = false ) { const oldCollectionMap = keyBy ( collection , keySelector ) ; if ( ! appendOnly ) { const newCollectionMap = keyBy ( newCollection , newKeySelector ) ; collection = collection . filter ( ( item ) => newCollectionMap [ keySelector ( item ) ] ) ; } newCollection . forEach ( ( newItem ) => { const id = newKeySelector ( newItem ) ; const oldItem = oldCollectionMap [ id ] ; if ( oldItem ) { update ( oldItem , newItem ) ; } else if ( create ) { collection . push ( create ( oldItem , newItem ) ) ; } } ) ; return [ ] . concat ( collection ) ; } /**
     * Returns true if the two collections have the same set of keys.
     * Otherwise false.
     */ public static compareCollectionsByKeys < T , P > ( collection , newCollection , keySelector , newKeySelector ) { if ( collection . length !== newCollection . length ) { return false ; } const oldCollectionMap = keyBy ( collection , keySelector ) ; return newCollection . every ( item => { const id = newKeySelector ( item ) ; return ! ! oldCollectionMap [ id ] ; } ) ; } /**
     * Update DataModelCollection
     */ public static updateDataModelCollection < T > ( collection , newCollection , appendOnly = false ) { return CollectionUtils . updateCollection ( collection , newCollection , item => item . uniqueId , item => item . uniqueId , ( item , newItem ) => newItem , ( item , newItem ) => item . update ( newItem . raw ) , appendOnly ) ; } }