Refactor to make the method more simpler.
Added more test cases also prepared for the thrown error
Updated JSDoc and comments