Rdefactored java script code