The code is getting too complex here, hence the test failure regarding jshint code cyclomatic complexity check, possibly. You need to split these logical blocks into individual functions.