How to turn ternary if statement back into standard javascript? - javascript

I'm working with this ternary if statement:
a[textProp] = _newText + ' (' + (_newText === a[textProp] ? 'no change' : 'changed') + ')';
And I'd like to turn it back into standard javascript (for the sake of readability). I additionally want to make it into an if, else if, else statement to test if the variable is empty/null.
This is what I have, which doesn't work:
if (_newText = null) {
'Invalid Record';
}
else if (_newText === a[textProp]) {
'no change';
}
else(_newText != a[textProp]) {
'changed';
}
+ ')';

if (_newText = null) {
^
needs to be
if (_newText == null) {
^^
or
if (_newText === null) {
^^^
And you need to build up your string
a[textProp] = 'Invalid Record';

For the sake of readability, I'd start with something like this, where each state is checked explicitly (valid and changed):
var isValid = true;
if (_newText == null || _newText.trim().length === 0) {
isValid = false;
}
var hasChanged = false;
if (isValid && _newText !== a[textProp]) {
hasChanged = true;
}
if (!isValid) {
a[textProp] = 'Invalid Record';
}
else if (hasChanged) {
a[textProp] = _newText + ' (changed)';
}
else {
a[textProp] += ' (no change)';
}
But, I also think it's not right to store the result of the tests as a string inside a[textProp], it could invalidate future tests. I'd probably have separate keys for the test results (as a flag), e.g.: a.valid[textProp] and a.changed[textProp] (in this case, textProp can never be "valid" or "changed"). Even better would be to store the text in a[textProp].text, and the flags in a[textProp].valid and a[textProp].changed.

Related

exporting function return value

I have a code below
function createRoom(){
$(document).keyup(function(event) {
if ($("#room_name").is(":focus") && event.key == "Enter") {
var plainText = document.querySelector(".create-room-class").value;
var createRoomName = plainText.replace(/(<([^>]+)>)/gi, "");
createRoomName = createRoomName.replace(/ +/g, "");
createRoomName = createRoomName.trim();
if(createRoomName.length == 0){
alert("empty");
} else if(createRoomName.length < 5){
alert("Room name must be equal or longer than 5 characters");
} else if(!createRoomName.length == 0)
{
getCreatedRoomName(createRoomName);
window.location = createRoomName;
}
}
});
}
createRoom();
function getCreatedRoomName(x){
return x;
}
What it does is first checks if input field is not empty and if not smaller than 5 characters. If everything is fine then we pass that value to a function and then redirect to that created name url. Look below.
getCreatedRoomName(createRoomName);
window.location = createRoomName;
And we return value (return x)
function getCreatedRoomName(x){
return x;
}
How can I retrieve that returned value in nodejs? I tried modules it doesn't work for some reason.

How to write a state machine to solve the Count the smiley faces?

I have solved the problem Count the smiley faces:
Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
Rules for a smiling face:
Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
Every smiling face must have a smiling mouth that should be marked with either ) or D
No additional characters are allowed except for those mentioned.
Valid smiley face examples: :) :D ;-D :~)
Invalid smiley faces: ;( :> :} :]
Example
countSmileys([':)', ';(', ';}', ':-D']); // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
Note
In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same.
Then when I look through the solutions I find that many people use regexp. Then I want write a state machine to implement regexp and solve this problem. But I failed. This is my code:
function countSmileys(smileys) {
let state = smileyHasValidEye;
return smileys.filter(smiley => {
for (let s of [...smiley]) {
state = state(s);
}
return state === true;
}).length;
}
function smileyHasValidEye(s) {
if (s === ':' || s === ';') {
return smileyHasValidNose;
}
return smileyHasValidEye;
}
function smileyHasValidNose(s) {
if (s === '-' || s === '~') {
return smileyHasValidMouth;
}
return smileyHasValidMouth(s);
}
function smileyHasValidMouth(s) {
if (s === ')' || s === 'D') {
return true;
}
return;
}
console.log(countSmileys([':)', ';(', ';}', ':-D']));
And the error I get is:
state = state(s);
^
TypeError: state is not a function
Then I debugged my code I found the procedure doesn't enter the smileyHasValidNose function. Then I don't know the reason.
The problem is you don't really reset state in between smileys. So the next smiley state will be true which you can't call (it's not a function).
You could use a local variable for state that resets it to the first function (the first step).
function countSmileys(smileys) {
let firstStep = smileyHasValidEye;
return smileys.filter(smiley => {
let state = firstStep;
for (let s of [...smiley]) {
state = state(s);
}
return state === true;
}).length;
}
function smileyHasValidEye(s) {
if (s === ':' || s === ';') {
return smileyHasValidNose;
}
return smileyHasValidEye;
}
function smileyHasValidNose(s) {
if (s === '-' || s === '~') {
return smileyHasValidMouth;
}
return smileyHasValidMouth(s);
}
function smileyHasValidMouth(s) {
if (s === ')' || s === 'D') {
return true;
}
return;
}
console.log(countSmileys([':)', ';(', ';}', ':-D']));
This code however, will error if there's more on the string besides the smiley (or a partial of the smiley).
I would change smileyHasValidMouth to return false if it doesn't detect a smiley. Just to be more consistent here...
function smileyHasValidMouth(s) {
if (s === ')' || s === 'D') {
return true;
}
return false;
}
And adjust your loop to exit early if it finds a value that is not a function.
for (let s of [...smiley]) {
state = state(s);
if(typeof state !== 'function') return state;
}
function countSmileys(smileys) {
let firstStep = smileyHasValidEye;
return smileys.filter(smiley => {
let state = firstStep;
for (let s of [...smiley]) {
state = state(s);
if (typeof state !== 'function') return state;
}
}).length;
}
function smileyHasValidEye(s) {
if (s === ':' || s === ';') {
return smileyHasValidNose;
}
return smileyHasValidEye;
}
function smileyHasValidNose(s) {
if (s === '-' || s === '~') {
return smileyHasValidMouth;
}
return smileyHasValidMouth(s);
}
function smileyHasValidMouth(s) {
if (s === ')' || s === 'D') {
return true;
}
return false;
}
console.log(countSmileys([':~(', ':>', ':D', ':(', ':o>', ';)', ':)']));

Bool value returns false when the function set it to true in Javascript

I am facing this problem, created a Audio Player in the document ready and a var for playing as false but every time function seems to be called correctly but not setting that variable to true:
the code is this the function is called from a click listener.
var cartSongPlayer = new Audio();
var playingStatus = false;
var playingTrack;
function switchTrack(trackID, trackSource) {
//logging basic information:
console.log('Current Track ID ' + trackID)
console.log('Current Track Source ' + trackSource)
console.log('Previous Track ID ' + playingTrack)
console.log('Playing Status ' + playingStatus)
if (playingStatus) {
console.log('song is playing')
if (trackID == playingTrack) {
playingStatus == false;
console.log('pausing current song')
cartSongPlayer.pause();
} else {
console.log('moved to new song')
playingStatus == true;
playingTrack = trackID
cartSongPlayer.src = trackSource;
cartSongPlayer.play();
}
//no song is playing
} else {
console.log('song is not playing')
if (trackID == playingTrack) {
playingStatus == true;
console.log('resumed song')
cartSongPlayer.play();
} else {
console.log('started new song')
playingStatus == true;
playingTrack = trackID
cartSongPlayer.src = trackSource;
cartSongPlayer.play();
}
}
}
You seem to be mistakingly using the == comparison operator, instead of the = assignment operator.
Change
playingStatus == true;
to
playingStatus = true;
You never change the value of playingStatus.
== is the equality operator, not the assignment operator (which is =).

i am getting error in console can not read property tostring() in javascript

i am getting error cannot read tostring() . below is my code please help on this
function convertRounding(nValue) {
var sArr = nValue.toString("0.00000").split('.');
**var sVal = sArr[1].toString();**
if (sVal == "00000" || sVal.substring(1) == "0000" || sVal.substring(2) == "000")
return parseFloat(nValue).toFixed(2);
else if (sVal.substring(3) == "00")
return parseFloat(nValue).toFixed(3);
else if (sVal.substring(4) == "0")
return parseFloat(nValue).toFixed(4);
else
return parseFloat(nValue).toFixed(5);
}
The value you are passing in (nValue) doesn't contain a dot, and therefore will fail when you try to split.
Make sure your input can indeed be split first.
function convertRounding(nValue) {
var sArr = nValue.toString().split('.');
var sVal = sArr[1].toString();
if (sVal == "00000" || sVal.substring(1) == "0000" || sVal.substring(2) == "000")
return parseFloat(nValue).toFixed(2);
else if (sVal.substring(3) == "00")
return parseFloat(nValue).toFixed(3);
else if (sVal.substring(4) == "0")
return parseFloat(nValue).toFixed(4);
else
return parseFloat(nValue).toFixed(5);
}
console.log(convertRounding(100.20));
//console.log(convertRounding(100)); // fails
https://jsfiddle.net/qgafbvot/2/
Updated to work with number input.
I think there is problem with radix nValue.toString("0.00000")
just try nValue.toString() this

Javascript test() method syntax error?

I'm attempting to convert (what I've found to be) the best email validation function (located here: http://www.linuxjournal.com/article/9585?page=0,3) from php to javascript. Regardless of the fact that "you shouldn't validate with javascript because javascript can be disabled". Obviously I can't leave in the checkdnsrr() portion of the function, but everything else should be doable with javascript.
So far the function works as expected up until this line:else if(/\.\./.test(domain)) {
I know it's pretty useless without context, so the full function is below. What's also weird is that it gives a "pass" to a line with the exact same regex pattern:else if(/\.\./.test(local)) { which is used a few lines before it. Strange.
function validEmail(email) {
var isValid = true;
var atIndex = email.indexOf("#");
var ending = email.length - 1;
if(typeof(atIndex) == "boolean" && !atIndex) {
isValid = false;
}
else {
var domain = email.substr(atIndex+1);
var local = email.substr(0, atIndex);
var localLen = local.length;
var domainLen = domain.length;
if(localLen < 1 || localLen > 64) {
// local part length exceeded
isValid = false;
}
else if(domainLen < 1 || domainLen > 255) {
// domain part length exceeded
isValid = false;
}
else if(local[0] == '.' || local[localLen-1] == '.') {
// local part starts or ends with '.'
isValid = false;
}
else if(/\.\./.test(local)) {
// local part has two consecutive dots
isValid = false;
}
else if(/^[A-Za-z0-9\\-\\.]+$/.test(domain) == false)
// character not valid in domain part
isValid = false;
}
else if(/\.\./.test(domain)) {
// domain part has two consecutive dots
isValid = false;
}
else if(/^(\\\\.|[A-Za-z0-9!#%&`_=\/$'*+?^{}|~.-])+$/.test(local.replace("\\\\",""))) {
// character not valid in local part unless
// local part is quoted
if(/^"(\\\\"|[^"])+"$/.test(local.replace("\\\\",""))) {
isValid = false;
}
}
}
return isValid;
}
You missed a { in the previous if.
Therefore, that else has no if connected to it.

Categories

Resources