Improve JS code and add unit test