changed pseudocode into functional js