Problem in saving the value of an object key - javascript

Modify insert and remove to only work if the safe is opened, if the safe is closed then return Please open the safe first.
So all of my test cases are working properly, however I want to be able to do the following:
after removing an element via the remove method I want to access the element size value first
save it, then remove that element so that I can give the removed size back to the safe.
I tried doing it myself but I dunno how to code it, any suggestions?
class Safe {
constructor(safeSize, passcode) {
this.storage = [];
this.safeSize = safeSize;
this.oldSafeSize = this.safeSize;
this.passcode = passcode; // <---- Modify Safe to have a passcode attribute
this.isOpen = this.isOpen; // <---- Add isOpen attribute to the Safe Class
}
insert(name, size) {
//add restriction for insert to only work if this.isopen == true
if (this.isOpen == true) {
if (this.safeSize - size >= 0) {
this.safeSize -= size;
this.storage.push({
name,
size
}); // push it as an object
return true + " still accepting";
}
return false + " size limit reached";
} //end of isOpen tesecase
return "Please open the safe first"
}
remove(test) {
if (this.isOpen == true) {
let shouldSkip = false;
let message = "";
this.storage = this.storage.filter(element => {
if (element.name == test && !shouldSkip) {
// let temporarySize= this.safeSize;
shouldSkip = true;
this.storage.pop(element);
//adding the size back to the main safe only after
//deleting an element
// this.safeSize = this.oldSafeSize - temporarySize;
message = "The item " + element.name + " Has been removed"
return false;
}
return true;
});
if (!shouldSkip) message = test + " Item not found";
return message;
}
return "Please open the safe first"
}
setPassCode(passWord) {
if (this.passcode == undefined) {
this.passcode = passWord;
return "Passcode has been set"
}
return "please reset passcode first" // todo make a reset password function
}
resetPassCode(providedPasscode) {
if (this.passcode == undefined) {
return "Set a passcode first"
}
if (providedPasscode == this.passcode) {
this.passcode = undefined
return "Passcode has been reset"
}
return "Wrong passcode" // or this.passcode != providedPasscode
}
openSafe(testCode) {
if (this.passcode == testCode) {
this.isOpen = true
return "The safe is open and ready to use"
}
return "Wrong safe passcode"
}
closeSafe() {
this.Open = false;
return "The safe is closed"
}
} // end of class
const safe = new Safe(10);
testcases:
safe.setPassCode("8642"); // => "Passcode has been set"
safe.insert("laptop", 8); // => "Please open the safe first"
safe.remove("laptop"); // => "Please open the safe first"
safe.openSafe("7531"); // => "Wrong passcode"
safe.openSafe("8642"); // => "The safe is open and ready to use"
safe.insert("watermelon", 7); // => true
safe.remove("watermelon"); // => {name: "watermelon", "size: 7"}
safe.closeSafe(); // => "The safe is closed"
safe.insert("watermelon", 7); // => "Please open the safe first"

I've just found one typo.
closeSafe() {
// this.Open = false;
this.isOpen = false;
return "The safe is closed";
}

remove(test) {
if (this.isOpen == true) {
let shouldSkip = false;
let message = "";
this.storage = this.storage.filter(element => {
if (element.name == test && !shouldSkip) {
this.safeSize += element.size; // you've done similar job in insert method
shouldSkip = true;
this.storage.pop(element);
//adding the size back to the main safe only after
//deleting an element
// this.safeSize = this.oldSafeSize - temporarySize;
message = "The item " + element.name + " Has been removed"
return false;
}
return true;
});
if (!shouldSkip) message = test + " Item not found";
return message;
}
return "Please open the safe first"
}
Get the element size and subtract it from the safeSize.

Related

My code is throwing an error, I need to find out the reason

I am getting expected error in my code and I have no idea why.
',' expected. The ide is pointing at the closing curly bracket of function remove, the curly bracket before the last curly bracket
The console says, uncaught syntax error: missing ) after argument list
Write a method remove that removes the specified item from the storage and returns the removed item and if not found
return a string Not Found, incase there are multiple items with the same name return the first one found.
class Safe {
constructor(safeSize) {
this.storage = [];
this.safeSize = safeSize;
}
insert(name, size) {
if (this.safeSize - size >= 0) {
this.safeSize -= size;
this.storage.push({
name: size
}); // push it as an object
return true;
}
return false;
}
remove(test) {
let shouldSkip = false;
this.storage.forEach(function(element, index) {
if (shouldSkip) {
return;
}
if (element === test) {
shouldSkip = true;
const removedItem = element;
this.storage.pop(element);
return ("The item" + removedItem + " Has been removed");
}
return (test + " Item not found");
}
}
}
> test cases:
>
> safe.insert("watermelon", 7); => true
> safe.insert("plate", 2); => true
>
> safe.remove("money"); => "Not Found"
> safe.remove("watermelon"); => {name: "watermelon", "size: 7"}
> safe.remove("watermelon"); => "Not Found"
There are some wrong codes in your code.
Please use this code.
class Safe {
constructor(safeSize) {
this.storage = [];
this.safeSize = safeSize;
}
insert(name, size) {
if (this.safeSize - size >= 0) {
this.safeSize -= size;
this.storage.push({
name, size
}); // push it as an object
return true;
}
return false;
}
remove(test) {
let shouldSkip = false;
let message = "";
this.storage = this.storage.filter( element => {
if(element.name == test && !shouldSkip) {
shouldSkip = true;
message = "The item " + element.name + " Has been removed"
return false;
}
return true;
});
if(!shouldSkip) message = test + " Item not found";
return message;
}
}
You're missing the closing parenthesis for your forEach function:
remove(test) {
let shouldSkip = false;
this.storage.forEach(function(element, index) {
if (shouldSkip) {
return;
}
if (element === test) {
shouldSkip = true;
const removedItem = element;
this.storage.pop(element);
return ("The item" + removedItem + " Has been removed");
}
return (test + " Item not found");
}) //<------
}

How do I set a javascript variable inside a for loop to be used afterwards

So, I'm creating a login form, and when certain criteria aren't met to continue after the form, I am setting a variable to be tested after I've tested all the criteria. IF that variable ($cantcontinue) is set to 'true' I want to send a console message with the criteria that isn't met. Here is my code:
function testfields() {
// Ask if logging in or Creating Account
//Logging In:
if (document.getElementById("tEmail").style.display != "unset") {
var loginelements = ["Username", "Password"];
var text = "";
var i;
for (i = 0; i < loginelements.length; i++) {
//Check all fields are full:
if (document.getElementById(loginelements[i]).value == "") {
document.getElementById(loginelements[i]).style.background = '#ff6060'
var cantcontinue = true;
console.log(loginelements[i] + " is not set,")
} else {
document.getElementById(loginelements[i]).style.background = '#f7f7f7'
}
}
if ($cantcontinue != true) {
console.log("Create Account")
} else {
console.log("Could Not Create Account")
}
//Create a new Account:
} else {
var createelements = ["Username", "Password", "tEmaili", "tConfirmi"];
var text = "";
var i;
for (i = 0; i < createelements.length; i++) {
//Check all fields are full:
if (document.getElementById(createelements[i]).value == "") {
document.getElementById(createelements[i]).style.background = '#ff6060'
var cantcontinue = true;
console.log(createelements[i] + " is not set,")
} else {
document.getElementById(createelements[i]).style.background = '#f7f7f7'
}
}
//If passwords Match
if (document.getElementById("Password").value != document.getElementById("tConfirmi").value) {
var cantcontinue = true;
document.getElementById("tConfirmi").style.background = '#ff6060'
document.getElementById("tConfirmi").value = ''
console.log(" Passwords didn't Match,");
}
if ($cantcontinue != true) {
console.log("Create Account")
} else {
console.log("Could Not Create Account")
}
}
}
$cantcontinue !== cantcontinue;//....
Also
if (cantcontinue != true) {
equals:
if (!cantcontinue) {
Sidenote: Please don't use "$" unless you're using jQuery. It reminds me of PHP ( brrrrr...)

Form validation JavaScript not working

My form validation function is not working properly. The error msg displayed in the innerHTML element goes away as soon as it appears, like the page is being refreshed.I am new in javascript. I don't know whet seems to be the problem.
<script type="text/javascript">
function validate(form) {
var user = form.txtUsername;
var institute = form.txtinstitute;
var email = form.txtemail;
var pass1 = form.pwdpassword1;
var pass2 = form.pwdpassword2;
var check = "";
check = validateFilled(pass2);
check = validateFilled(pass1);
check = validateFilled(email);
if (check == true) {
check = validateEmail(email);
}
check = validateFilled(institute);
check = validateFilled(user);
if (checked == false) {
return false;
}
//return true;
}
function validateFilled(control) {
if (control.value.length == 0) {
document.getElementById(control.id).nextSibling.innerHTML = "* required";
document.getElementById(control.id).focus();
return false;
}
return true;
}
function validateEmail(control) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!(re.test(email.value))) {
document.getElementById(email.id).nextSibling.innerHTML = " *invalid email";
document.getElementById(email.id).focus();
return false;
}
return true;
}
</script>
check = validateFilled(pass2);
check = validateFilled(pass1); //overrides check above
check = validateFilled(email); //overrides check above
if (check == true) {
check = validateEmail(email);//overrides check above
}
if (check == true) {
check = validateEmail(email);//overrides check above
}
check = validateFilled(institute);//overrides check above
check = validateFilled(user);//overrides check above
So if any of those are false, the other checks under it will make it true. Bad design....
You need to only set check to false if the validation fails....

Limit select2 to only accept email addresses

I have a select2 box, an I was to limit this to accept only email addresses.
I am trying to do this by writing a custom formatSelection function, as
formatSelection: function(object, container){
if(validateEmail(object.text)){
return object.text;
}
else{
return "";
}
}
I am expecting that returning an empty string would be enough to not show this input in select2, but I am getting an empty result.
As of select2 4.0 +, just use the createTag function:
createTag: function(term, data) {
var value = term.term;
if(validateEmail(value)) {
return {
id: value,
text: value
};
}
return null;
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
I have solved this. Just copy paste the code below and it will work smooth.
validate: function(value) {
if(value && value.length != 0){
var emailText = "";
var isValidEmail = true;
var isEmailLengthValid = true;
for (var i in value) {
var email = value[i];
isValidEmail = validateEmail(email);
if(isValidEmail == false){
break;
}else{
emailText = (i == 0) ? emailText : ", " + emailText;
if(emailText.length > 250){
isEmailLengthNotValid = false;
break;
}
}
}
if(isValidEmail == false){
return 'Enter a valid email address';
}else if(isEmailLengthValid == false){
return 'Maximum 250 characters allowed';
}
}
}
Also add below function validateEmail() which uses regex to validate email string.
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
it isn't clear from your question where your data source is. if the data source is from an ajax call then you can do server side validation and only return the email addresses.
but i suspect that you want to accept user input and only of valid email addresses. The Select2 docs explain the createSearchChoice function in the initialization $opts. you could insert your validateEmail function here and decide if you want to accept the new answer or not.
you might even want to write to an external DOM element any errors you find so the user knows they have to go back and correct the invalid email address.
//Allow manually entered text in drop down.
createSearchChoice: function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {id:term, text:term};
}
},
i use select2 4.01
regex validator email
function isEmail(myVar){
var regEmail = new RegExp('^[0-9a-z._-]+#{1}[0-9a-z.-]{2,}[.]{1}[a-z]{2,5}$','i');
return regEmail.test(myVar);
}
i return only a text without id in the return json if it's no valid. in this cas, you can add alert no selectable.
createTag: function (params)
{
if(!isEmail(params.term)){
return {
text: params.term,
};
}
return {
id: params.term,
text: params.term,
};
}
In your templateResult
function formatRepoReceiver (repo) {
if (repo.loading) return repo.text;
var markup = "";
if(typeof(repo.email) == 'undefined'){
// >>>your Alert<<<<
if(!isEmail(repo.text)){
if(repo.text == ''){
return null;
}
return 'Address email no valid';
}
//----------------------------
markup = "<div class='select2-result-repository clearfix'>"+
"<div class='select2-result-repository__meta'>" +
"<span>"+ repo.text +"</span> "+
"(<span>" + repo.text + "</span>)"+
"</div>"+
"</div";
}
else{
markup = "<div class='select2-result-repository clearfix'>"+
"<div class='select2-result-repository__meta'>" +
"<span>"+ repo.name +"</span> "+
"(<span>" + repo.email + "</span>)"+
"</div>"+
"</div";
}
return markup;
}
$('.select2-tokenizer').on('change', function() {
var num= this.value
if(!$.isNumeric(num)){
$('option:selected',this).remove();
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Please enter an integer!'
})
}
});

Filtering collections in backbone

Hello I am running a search of a backbone collection, the current string I am searching is
Project Number
This should return 2 results however it only ever shows 1 result, I cannot understand why, below is the code that I using,
The code the runs when adding search parameters,
updateSearchFilter: function(e) {
var self = this;
this.collection.each(this.filterHide, this);
if($(e.currentTarget).val() === "")
{
this.collection.each(this.filterShow, this);
}
var activeLabels = $(".labels").find(".inactive");
$.each(activeLabels, function(key, index){
switch($(index).attr("id"))
{
case "pending":
status = "7";
self.filterDetails.states["pending"] = false;
break;
case "completed":
status = "5";
self.filterDetails.states["complete"] = false;
break;
case "archived":
status = "3";
self.filterDetails.states["archived"] = false;
break;
case "active":
status = "1";
self.filterDetails.states["active"] = false;
break;
}
});
var visible = this.collection.search($(e.currentTarget).val(), this.filterDetails.states);
if (visible !== undefined) {
visible.each(this.filterShow, this);
}
},
So the above code, hides the idividual results on the first key press, is then loops through an array of jquery objects and re-assigns some values in an object - this is done so we can work out what filters we need to search through.
We then run our search code,
ProjectCollection.prototype.search = function(searchTerm, filters) {
var pattern;
console.log(filters);
pattern = new RegExp(searchTerm, "gi");
if (filters.active && filters.archived) {
if (searchTerm === "") {
return this;
}
return _(this.filter(function(data) {
return pattern.test(data.get("project_name") + data.get("client_name"));
}));
} else if (filters.active) {
if (searchTerm === "") {
return this.active();
}
return _(this.active().filter(function(data) {
return pattern.test(data.get("project_name") + data.get("client_name"));
}));
} else if (filters.pending) {
console.log("hello");
if (searchTerm === "") {
return this.pending();
}
return _(this.pending().filter(function(data) {
return pattern.test(data.get("project_name") + data.get("client_name"));
}));
} else if (filters.archived) {
if (searchTerm === "") {
return this.archived();
}
return _(this.archived().filter(function(data) {
return pattern.test(data.get("project_name") + data.get("client_name"));
}));
} else if (filters.complete) {
if (searchTerm === "") {
return this.complete();
}
return _(this.complete().filter(function(data) {
return pattern.test(data.get("project_name") + data.get("client_name"));
}));
}
};
ProjectCollection.prototype.archived = function() {
return new ProjectCollection(this.where({
status: '3'
}));
};
ProjectCollection.prototype.active = function() {
return new ProjectCollection(this.where({
status: '1'
}));
};
ProjectCollection.prototype.pending = function() {
return new ProjectCollection(this.where({
status: '7'
}))
};
ProjectCollection.prototype.complete = function() {
return new ProjectCollection(this.where({
status: '5'
}));
}
Now what I should be getting back is 2 results,
Project Number 1 & Project Number 2
However I only every get one result on this search term, Project Number 1 has the status of "Archived" and Project Number 2 has the status of "Pending". However I never seem to get go into the pending portion of the logic (above) even though filters.pending = true;
How can I make sure that I get all the matches for each status returned?
Instead of setting state of your filter individually, you could keep all filter status keys in an array. For example, your user want to filter for active, complete and pending so you would have an array of ['1','5','7']
So when you filter for relevant statuses you could do by
// filterModes is ['1', '5', '7'];
collection.filter(function(model){
return filterModes.indexOf(model.status) !== -1;
}
The rest should be simpler for you now
Note that collection.filter() and collection.where() return array and array may or may not have filter() and definitely don't have where() so be wary about chaining your function call

Categories

Resources