Refactored from PHP to javascript