Permutation Check - 1

With map

by dpnminh

HTML

<div id="test">
</div>

JavaScript

function isPermutation(strA, strB){
	var isValid = true;
	
	//First validity check
	if (!strA || !strB || strA.length !== strB.length){
		return !isValid;
	}
  
	//Get the map of characters and their occurences in strA
	var charsMap = getMap(strA);
	
	//Check strB characters and occurences on the computed map.
	for (var i = 0; i < strB.length; i++){
		var charB = strB[i];
		
		if (charsMap[charB] !== undefined && charsMap[charB] >= 1){
			charsMap[charB]--; // If current character does appear in A and B, decrement the occurence counter.
		}
		else{
			return !isValid;
		}
	}
	
	return isValid;
}

function getMap(str){
	var map = {};
	
	for (var i = 0; i < str.length; i++){
		var currChar = str[i];
		
		//If current character hasn't been mapped, map it
		if (map[currChar] === undefined){
			map[currChar] = 1;
		}
		else{
			map[currChar]++; //Else increment the occurrence counter.
		}
	}
	
	return map;
}

function test(){
	var tests = {
  	1: "DOOG vs DOGO - Result: " + isPermutation('DOOG', "DOGO"),
    2: "DO G VS DOOG - Result: " + isPermutation('DO G', 'DOOG'),
    3: "DOGY vs DOGE - Result: " + isPermutation('DOGY', 'DOGE'),
    4: "gdoo and dGoo - Result: "+ isPermutation('gdoo', 'dGoo'),
    5: "DOOG and GOOO - Result: "+ isPermutation('DOOG', 'GOOO'),
    6: "DOOO and GOOD - Result: "+ isPermutation('DOOO', 'GOOD')
  }
  var strs = "";
  
  for (var key in tests){
  	strs += "<div>" + tests[key] + "</div>";
  }
  
  document.getElementById('test').innerHTML = strs;
}

test();