Calculate score for the given binary string | Function to return the score for the given binary string ; Traverse through string character ; Initialize current chunk 's size ; Get current character ; Calculate total chunk size of same characters ; Add / subtract pow ( chunkSize , 2 ) depending upon character ; Return the score ; Driver code
function calcScore ( str ) { var score = 0 ; var len = str . length ; for ( var i = 0 ; i < len ; ) { var chunkSize = 1 ; var currentChar = str [ i ++ ] ; while ( i < len && str [ i ] == currentChar ) { chunkSize ++ ; i ++ ; } if ( currentChar == ' ' ) score += Math . pow ( chunkSize , 2 ) ; else score -= Math . pow ( chunkSize , 2 ) ; } return score ; } var str = " " ; document . write ( calcScore ( str ) ) ;