javascript implement of basic algorithm