Replaced the ad-hoc implementation with a spec compliant one. This change fixes 36 WPT tests. (cherry picked from commit 50f642613de54c73473c216fdc4d7e607e712679)