Added another JavaScript solution, but this one keeps no mutable internal state