TemplatePreprocessor.js

angular.module('homepage').
factory('TemplatePreprocessor', function() {
    function removeEmtpyFitnessSets(newtemplate, template) {
        // Removing the empty sets from the original object
        for(var index in newtemplate.data.list) {
            var workout = newtemplate.data.list[index];
            for(var jndex in workout.sets) {
                var set = workout.sets[jndex];
                if(set.distance === '' && set.repetition === '' && set.time === '' && set.weight === '') {
                    delete template.data.list[index].sets.splice(jndex, 1);
                }
            }
        }
    }

    function removeEmptyFitnessWorkout(newtemplate, template) {
        // Remvong the empty workouts from the original object
        for(var index in newtemplate.data.list) {
            var workout = newtemplate.data.list[index];
            if(workout.sets.length === 0) {
                delete template.data.list.splice(index, 1);
            }
        }
    }

    function fitnessTemplatePreprocessor(template) {
        if(template.data.list && template.data.list.length > 0) {
            var newtemplate = angular.copy(template);
            removeEmtpyFitnessSets(newtemplate, template);

            removeEmptyFitnessWorkout(newtemplate, template);
        }

        return template;
    }

    function removeEmptyWorkoutAndSet(template) {
        if(template.type === 'HLTH') {
            return fitnessTemplatePreprocessor(template);
        }
    }

    return {
        removeEmptyWorkoutAndSet: removeEmptyWorkoutAndSet
    };
});