algorithm implementation with javascript