Reusing simple Javascript Function - javascript

I'm new to JS and would like to know how to refactor this simple code so that I can pass in strings to count the number of "e" in a string.
function countE() {
var count = 0;
var str = "eee";
var charLength = str.length;
for (i =0; i <= charLength; i++){
if(str.charAt(i) == "e"){
count++;
}
}
console.log(count);
}
I would like to execute this function where I can do something like this:
countE('excellent elephants');
which would log 5.

function countE(str) {
if(typeof(str)==='undefined') str = 'eee';
var count = 0;
var charLength = str.length;
for (i =0; i <= charLength; i++){
if(str.charAt(i) == "e"){
count++;
}
}
console.log(count);
}

If you want to make your function body shorter, you can do the following:
function countE(str) {
return str.match(/e/g).length;
}
And even more sophisticated:
function count(what) {
return function(str) {
return str.match(new RegExp(what, 'g')).length;
};
}
// now you can do the this
var countE = count('e');
var resultE = countE('excellent elephants');
var countL = count('l');
var resultL = countL('excellent elephants');

If I understand your comment correctly, you want to do something like this:
function countE(inString) {
var count = 0;
var str = inString ? inString : "eee";
var charLength = str.length;
for (i =0; i <= charLength; i++){
if(str.charAt(i) == "e"){
count++;
}
}
console.log(count);
}

You can also use a regular expression
function countE(str) {
var count = str.match(/e/g).length;
console.log(count);
}
or
function countE(str) {
console.log(str.match(/e/g).length);
}

Related

how to decode string in javascript?

I am trying to decode my string using JavaScript. Here is my code on JSBin.
decordMessage('oppeeennnn','1234');
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str ='';
var j =0
for (var i=0;i<msg.length;){
str += msg[i];
if(j < keysplit.length -2 &&i < keysplit.length && keysplit[j]){
i = i + parseInt(keysplit[j]);
j++;
}
console.log(i +"i")
console.log(str);
}
console.log("after");
console.log(str);
}
I make a function in which message and key is passed.
Expected output :: open
Actually string charters are repeated in input message (encrypted message) using key. So I need to decode the message.
You forgot to put a break in the else condition, that's why it was looping infinitely till it ran out of memory. Run it in a browser and the tab will crash:
decordMessage('oppeeennnn','1234');
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str ='';
var j =0
for (var i=0;i<msg.length;){
str += msg[i];
if(j < keysplit.length &&i < keysplit.length && keysplit[j]){
i = i + parseInt(keysplit[j]);
j++;
}
else
break;
}
console.log("after");
console.log(str); // prints open
}
By the way, a better way to write the loop would be:
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str = '';
var j = 0, i = 0;
while (j < keysplit.length
&& i < msg.length) {
str += msg[i];
i += parseInt(keysplit[j]);
j++;
}
console.log(str)
}
This may helps you.
decordMessage('oppeeennnn', '1234');
function decordMessage(m, k) {
var arr = m.split("");
uniqueArray = arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
});
console.log(uniqueArray.join(""));
}
Assuming encryption logic goes as 123456....
Sample here

less than or equal to condition is not working in my script

<script type="text/javascript">
function ValidateAddOnModule(source, args) {
var gdv = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules');
var j = 0;
var k = 0;
for (var i = 1; i <= gdv.rows.length - 1; i++) {
var img = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_ImgLanUserError_' + j);
var LANUser = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_txtAdditionalLANUser_' + j).value;
var MinLANUser = gdv.rows(i).cells(2).innerText;
// alert(MinLANUser);
// alert(LANUser);
if (MinLANUser != " ")
{
if (MinLANUser <= LANUser) {
alert("true");
img.style.visibility = "hidden";
}
else {
alert("false");
img.style.visibility = "visible";
k = 1;
}
j++;
}
}
if (k = 1) {
return false;
} else
{
return true;
}
}
</script>
frist try to change the numbers you grab from thext fields with parseInt() function
element.innerText will give you the output in string format. You have to first convert that value to integer using parseInt. Then only you can operate arithmetic operators on them.
var LANUser = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_txtAdditionalLANUser_' + j).value;
var MinLANUser = gdv.rows(i).cells(2).innerText;
convert these to integer type.
var LANUser = parseInt(document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_txtAdditionalLANUser_' + j).value);
var MinLANUser = parseInt(gdv.rows(i).cells(2).innerText);

Javascript For Loop: Assignment to character not working

I was writing a test function to capitalize each word in a sentence. I ended up solving it; however, one of my first attempts to solve the problem didn't work when I thought it would.
function capSentence(str) {
var strArray = str.split(" ");
var answer = '';
var temp = '';
for(var i = 0; i < strArray.length; i++){
strArray[i][0] = strArray[i][0].toUpperCase();
answer += strArray[i];
if(i !== strArray.length-1){
answer += ' ';
}
}
return answer;
}
capSentence("this is a test");
I thought the above code would output "This Is A Test", but instead it outputs "this is a test".
strArray[i][0] = strArray[i][0].toUpperCase();
doesn't seem to have any affect. Why is that?
#thefourtheye's comment is correct. You need to build a new string.
function capSentence(str) {
var strArray = str.split(" ");
var answer = '';
var temp = '';
for(var i = 0; i < strArray.length; i++){
answer += strArray[i][0].toUpperCase();
answer += strArray[i].slice(1,strArray[i].length);
if(i !== strArray.length-1){
answer += ' ';
}
}
return answer;
}
Strings are immutable in Javascript. That's why you are not able to change the value of the strArray.
But you can do in this way:
function capSentence(str) {
strArray = str.split(" ");
console.log(strArray);
var answer = '';
var temp = '';
for(var i = 0; i < strArray.length; i++){
for (var j = 0; j< strArray[i].length; j++) {
if(j==0) {
temp = strArray[i][j].toUpperCase();
} else {
temp+=strArray[i][j];
}
}
answer += temp;
if(i !== strArray.length-1){
answer += ' ';
}
}
return answer;
}
This will retrun "This Is A Test"
Try this simple snippet,
function capSentence(str) {
var strArray = str.split(" ");
var answer = '';
var temp = '';
for(var i = 0; i < strArray.length; i++){
answer += (strArray[i].substring(0,1)).toUpperCase()+strArray[i].substring(1);
if(i !== strArray.length-1){
answer += ' ';
}
}
return answer;
}

JavaScript - how to change elements of a string?

JS newbie here. I want to write a basic program that changes each element in a string based on a condition. If the letter is uppercase we swap it to lowercase, if the letter is already lowercase we swap it to uppercase. Why is this not working? Thanks!
function SwapCase(str){
for (var i = 0; i < str.length; i++) {
if (str.charAt(i)===str.charAt(i).toUpperCase()) {
str.charAt(i).toLowerCase();
} else{}
str.charAt(i).toUpperCase();
}
return str;
}
SwapCase("gEORGE");
Currently you do not write back your changes. You could, for example, do something like this:
function SwapCase(str){
var result = '';
for (var i = 0; i < str.length; i++) {
if (str.charAt(i)===str.charAt(i).toUpperCase()) {
result += str.charAt(i).toLowerCase();
} else{
result += str.charAt(i).toUpperCase();
}
}
return result;
}
function SwapCase(str){
var sReturn = "";
for (var i = 0; i < str.length; i++) {
if (str.charAt(i)===str.charAt(i).toUpperCase()) {
sReturn += str.charAt(i).toLowerCase();
} else{
sReturn += str.charAt(i).toUpperCase();
}
}
return sReturn;
}
Doing the same thing with String Prototyping and some shorthand notation.
String.prototype.swapCase = function(){
var returnString = '';
for (var i = 0; i < this.length; i++) {
returnString += (this[i]===this[i].toUpperCase())
? this[i].toLowerCase()
: this[i].toUpperCase();
}
return returnString;
};
console.log("Hallo".swapCase());

Mccluskey algorithm, javascript

<html>
<body>
<script type="text/javascript">
start();
function start() {
var val = "0,1";
var n = 5;
var chars = ['a', 'b', 'c', 'd', 'e'];
gVars = chars.slice(0, n);
for (var i = 0; i < gVars.length; i++)
document.write(gVars[i] + "<br />");
var termsStr = val.split(',');
for (var i = 0; i < termsStr.length; i++)
document.write(termsStr[i] + "<br />");
var gOrigTerms = [];
var maxterm = Math.pow(2, termsStr.length) - 1;
document.write("maxterm: " + maxterm + "<br />");
for (var i = 0; i < termsStr.length; i++) {
gOrigTerms[i] = parseInt(termsStr[i]);
document.write(gOrigTerms[i] + "<br />");
if (gOrigTerms[i] > maxterm) document.write("Invalid term in term list." + "<br />");
}
gFormula = new Formula(gVars, gOrigTerms);
document.write(gFormula);
gFormula.toString();
gFormula.reduceToPrimeImplicants(); //here the breakpoint is inserted
}
function Formula(vars, terms)
{
this.vars = vars;
this.termList = [];
for (var i = 0; i < terms.length; i++) {
this.termList[i] = new Term(Dec2Bin(terms[i], vars.length));
document.write("this.termList" + this.termList[i] + "<br />");
}
this.orginalTermList = [];
document.write("this.orginalTermList" + this.orginalTermList + "<br />");
}
function Dec2Bin(dec, size) {
var bits = [];
for (var bit = 0; bit < size; bit++)
{
bits[bit] = 0;
}
var i = 0;
while (dec > 0)
{
if (dec % 2 == 0)
{
bits[i] = 0;
} else
{
bits[i] = 1;
}
i++;
dec = (dec / 2) | 0;
// Or with zero casts result to int (who knows why...)
}
bits.reverse();
return bits;
}
function Term(varVals)
{
this.varVals = varVals;
document.write("this.varVals: " + this.varVals);
}
function reduceToPrimeImplicants() //there is some problem with this function
{
this.originalTermList = this.termList.slice(0);
var numVars = this.termList[0].getNumVars();
var table = [];
for (var dontKnows = 0; dontKnows <= numVars; dontKnows++) {
table[dontKnows] = [];
for (var ones = 0; ones <= numVars; ones++) {
table[dontKnows][ones] = [];
}
table[dontKnows][numVars + 1] = [];
}
table[numVars + 1] = [];
table[numVars + 1][numVars + 1] = [];
for (var i = 0; i < this.termList.length; i++) {
var dontCares = this.termList[i].countValues(DontCare);
var ones = this.termList[i].countValues(1);
var len = table[dontCares][ones].length;
table[dontCares][ones][len] = this.termList[i];
}
for (var dontKnows = 0; dontKnows <= numVars - 1; dontKnows++) {
for (var ones = 0; ones <= numVars - 1; ones++) {
var left = table[dontKnows][ones];
var right = table[dontKnows][ones + 1];
var out = table[dontKnows + 1][ones];
for (var leftIdx = 0; leftIdx < left.length; leftIdx++) {
for (var rightIdx = 0; rightIdx < right.length; rightIdx++) {
var combined = left[leftIdx].combine(right[rightIdx]);
if (combined != null) {
if (out.indexOf(combined) < 0) {
var len = out.length;
out[len] = combined;
}
if (this.termList.indexOf(left[leftIdx]) >= 0) {
this.termList.splice(this.termList.indexOf(left[leftIdx]), 1);
}
if (this.termList.indexOf(right[rightIdx]) >= 0) {
this.termList.splice(this.termList.indexOf(right[rightIdx]), 1);
}
if (this.termList.indexOf(combined) < 0) {
var len = this.termList.length;
this.termList[len] = combined;
}
}
}
}
}
}
}
function getNumVars()
{
return this.varVals.length;
}
function countValues(value)
{
result = 0;
for (var i = 0; i < this.varVals.length; i++) {
if (this.varVals[i] == value) {
result++;
}
}
return result;
}
function combine(term)
{
var diffVarNum = -1; // The position where they differ
for (var i = 0; i < this.varVals.length; i++) {
{
if (this.varVals[i] != term.varVals[i])
if (diffVarNum == -1) {
diffVarNum = i;
} else { // They're different in at least two places return null; }
}
}
if (diffVarNum == -1)
{
// They're identical return null;
}
resultVars = this.varVals.slice(0);
resultVars[diffVarNum] = DontCare;
return new Term(resultVars);
}
</script>
</body>
</html>
In the above code, that is not complete, but which implements quine Mccluskey algorithm. There is a problem while it is debugged.
If a breakpoint is inserted at gFormula.reducetoPrimeImplicants(); the debugger does not go into that function. This is the last function called in the code until now. But, it does go to start(), which is the first function.
There is some problem in reducetoPrimeImplicants(); function because it also gives ERROR in internet explorer.
I am not able to figure out the error. If I remove reducetoPrimeImplicants(); function from the code the works fine.
Please, can somebody tell me why the debugger does not enter reducetoPrimeImplicants();.
I am using the Firebug debugger.
Thanks in advance.
The last function in your page combine() is missing a closing brace.
If you don't mind, a suggestion: Please use http://jsbeautifier.org/ or some similar tool to indent your code better.
Your For loop has two starting braces.
for (var i = 0; i < this.varVals.length; i++) {
{
So remove one. This should solve your problem.

Categories