refactored cache function