Move sampling logic into javascript