I'm writing an ATM console program which validate user with pin.Now when ever users tries to use it,it asks for their pin and brings any name associated to that particular pin but i have not been unable to achieve that.It's the only thing left for me in this little project as i hav coded the rest and they are working okay.The below is the code for pin validation.
function Authentication(){
let LoginAcess = [
{"name" : "bradly cooper", "pass" : 1990},
{"name" : 'james berry', "pass" : 1989},
{"name" : "sarah lance", "pass" : 1980},
]
for (let records in LoginAcess){
eachRecord = LoginAcess[records];
console.log(eachRecord)
let pin = prompt("enter your 4 valid digit pin : ");
if (pin === eachRecord.pass){
console.log(eachRecord.name)
}
}
};
Authentication();
the value in the variable pin is a string.
if (pin === eachRecord.pass){
console.log(eachRecord.name)
}
you are comparing string and number.
You can convert string to number by using parseInt(pin) or Number(pin)
if (parseInt(pin) === eachRecord.pass){
console.log(eachRecord.name)
}
you can do it without looping for better performance by using the below piece of code.
let LoginAcess = [
{"name" : "bradly cooper", "pass" : 1990},
{"name" : 'james berry', "pass" : 1989},
{"name" : "sarah lance", "pass" : 1980},
];
var pin ; // pin is input taken from user
var userName = (LoginAcess.find(({ pass }) => pass == pin)["name"]);
You will get the name as output. if you want to get the entire object as output remove "["name"]".
for...in is to iterate on properties object :
for ( propertie in objet ) { ... }
instead use find() :
let userIn = LoginAcess.find( element => element.pass == pin );
you have to put let pin = prompt("enter your 4 valid digit pin : "); out of the bucle.
In python is very easy:
def Authentication():
LoginAcess = [{"name" : "bradly cooper", "pass" : 1990},{"name" : 'james berry', "pass" : 1989},{"name" : "sarah lance", "pass" : 1980}]
pin = input('enter your 4 valid digit pin: ')
for record in LoginAcess:
print('checking record' + str(record))
if(pin == record['pass']):
print("USER WITH PIN SELECTED FOUND")
print(record['name'])
return
else:
print("user: " + str(record['name']) + " does not match input pin")
Authentication()
you can analyze this python code and change yours
Related
I have a profile field where the data comes in the below format for each user profile.
User1 could have his profile field populated as below while user2 could have just one role/id/company listed in their profile.
RoleA : 123456 - company1 \n
RoleB : 234567 - company2 \n
RoleC : 891011
I am supposed to split the roles for each user into 1 field separated by commas and the id/company into another field separated by comma.
For the above data, the output should look like-
Role field - RoleA, RoleB, RoleC
ID/Company field - 123456-company1, 234567-company2.
This has to be done in JavaScript. Any suggestion is appreciated.
Thanks!
What you should do is something similar to below:
function splitProfile(profile, roleList, idCompanyList) {
var splitProfileString = profile.split(" : ");
roleList.push(splitProfileString[0]);
var splitIdCompanyString = splitProfileString[1].split(" - ");
// check if there is a company for `id`
if(splitIdCompanyString[1]) {
idCompanyList.push(splitIdCompanyString[0] + "-" + splitIdCompanyString[1].replace(" \n", ""));
}
}
var roleIdCompanyList = [
"RoleA : 123456 - company1 \n",
"RoleB : 234567 - company2 \n",
"RoleC : 891011"
];
var roleList = [];
var idCompanyList = [];
roleIdCompanyList.forEach(function(roleIdCompany) {
splitProfile(roleIdCompany, roleList, idCompanyList);
});
console.log(roleList.join(", ")); // RoleA, RoleB, RoleC
console.log(idCompanyList.join(", ")); // 123456-company1, 234567-company2
I tried to think that the input and the output are exactly similar to the ones you provided in the question. In any case, I hope you get the idea of what I am trying to do here.
I did this code :
var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');
str.split(/\s+/).forEach(function (s) {
return console.log(
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
});
But in my input file there are some space, and I don't want my code to take it into account. My input file is :
cat
bob
alicia
shirley
cookie
thomas
rat`
So how can I code, to ignore the space in my input file please ?
First of all if you'd console.log(str.split(/\s+/)) you'll get
[ 'cat', 'bob', 'alicia', 'shirley', 'cookie', 'thomas', 'rat`' ]
so as everyone has already said /\s+/ will in fact remove the spaces
#JuanCaicedo your solution doesn't work well sorry, I tried and between cookie and thomas there are space, and the code write unknown. The result is unknown boy girl unknown dog unknown unknown unknown so after rat the code take care about the space
the output you're seeing is correct, according to your logic
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
If the string doesn't equal bob or alicia or cookie it will output unknown therefore
cat = unknown
bob = boy
alicia = girl
shirley = unknown
cookie = dog
thomas = unknown
rat` = unknown
Please look at the code below
function removeEmptyLines(str) {
const arrayOfLines = str.split("\n"); // Remove empty lines from the string which leaves "" in the returned array
const filtered = arrayOfLines.filter(line => line !== ""); // filter the array and remove all the empty strings
const joined = filtered.join(" "); // form a single string
return joined; // return filtered array
}
I'm scanning data from a vcard QR-code. The string I receive always looks something like this:
BEGIN:VCARD
VERSION:2.1
N:Lastname;Firstname
FN:Firstname Lastname
ORG:Lol Group
TITLE:Project Engineer
TEL;WORK:+32 (0)11 12 13 14
ADR;WORK:Industrielaan 1;2250 Olen;Belgium
EMAIL:link.com
URL:http://www.link.com
END:VCARD
I need some data to automatically fill in the form (I'm doing this in jQuery). I need the firstname, lastname, organisation and telephone number.
So I need the data after N, ORG and TEL. But I'm really stuck on how I could do this the best way. Any experience with this and maybe some tips for me?
UPDATE:
The data varies at times. These are the possibilities:
OPTION 1
BEGIN:VCARD
VERSION:3.0
N:lname;fname;;;
FN:fname lname
TITLE:Project manager
EMAIL;type=INTERNET;type=WORK:s.demesqdqs.be
TEL;type=WORK:+3812788105
END:VCARD
OPTION 2
BEGIN:VCARDFN:Barend VercauterenTEL:+32(0)9 329 93 06EMAIL:Barend.Vercauterenëesc.beURL:http://www.esc.beN:Vercauteren;BarendADR:Grote Steenweg 39;9840;De PinteORG:ESC bvbaROLE:sales consultantVERSION:3.0END:VCARD
OPTION 3
BEGIN:VCARDVERSION:2.1N:Deblieck;Tommy;;DhrFN:Tommy DeblieckTITLE:ZaakvoerderORG:QBMT bvbaADR:;;Kleine Pathoekweg 44;Brugge;West-Vlaanderen;8000;Belgi≠A0171TEL;WORK;PREF:+32 479302972TEL;CELL:+32 479302972EMAIL:tdëqbmt.beURL:www.qbis.beEND:VCARD
As you can see it can happen that all the text is attached to each other .. .
My code for receiving the correct data with option 1:
var fname = /FN:(.*)/g;
var org = /ORG:(.*)/g;
var tel = /TEL;[^:]*:(.*)/g;
var fullname, firstname, morg, mtel;
fullname = fname.exec(qr_data);
fullname = fullname[1];
var array = fullname.split(' ');
firstname = array[0];
array.shift();
var lastname = '';
if(array.length > 1){
$.each(array, function(index, item) {
lastname += item ;
});
}
else
{
lastname = array[0];
}
morg = org.exec(qr_data);
mtel = tel.exec(qr_data);
if(firstname)
{
$("#firstname").val(firstname);
}
if(lastname)
{
$("#name").val(lastname);
}
if(morg)
{
$("#company").val(morg[1]);
}
if(mtel)
{
$("#number").val(mtel[1]);
}
But how can I get these data with the other 2 options?
Use regex to extract the data.
For name = /FN:(.*)/g
For organization = /ORG:(.*)/g
For telephone = /TEL;[^:]*(.*)/g
Check out this fiddle.
var fname = /FN:(.*)/g;
var org = /ORG:(.*)/g;
var tel = /TEL;[^:]*:(.*)/g;
var str = 'BEGIN:VCARD\nVERSION:2.1\nN:Lastname;Firstname\nFN:Firstname Lastname\nORG:Lol Group\nTITLE:Project Engineer\nTEL;WORK:+32 (0)11 12 13 14\nADR;WORK:Industrielaan 1;2250 Olen;Belgium\nEMAIL:link.com\nURL:http://www.link.com\nEND:VCARD';
var mname, morg, mtel;
mname = fname.exec(str);
morg = org.exec(str);
mtel = tel.exec(str);
alert(mname[1]);
alert(morg[1]);
alert(mtel[1]);
In order to parse a vCard correctly, you cannot rely on a single regex expression. There are some vCard parsers that you can leverage.
Here is an example of using Nilclass vCardJS:
VCF.parse(input, function(vcard) {
// this function is called with a VCard instance.
// If the input contains more than one vCard, it is called multiple times.
console.log("Names: ", JSON.stringify(vcard.n)); // Names
console.log("Org: ", JSON.stringify(vcard.org)); // Org
console.log("Tel: ", JSON.stringify(vcard.tel)); // Tel
});
Here are all defined fields:
VCard.allKeys = [
'fn', 'n', 'nickname', 'photo', 'bday', 'anniversary', 'gender',
'tel', 'email', 'impp', 'lang', 'tz', 'geo', 'title', 'role', 'logo',
'org', 'member', 'related', 'categories', 'note', 'prodid', 'rev',
'sound', 'uid'
];
UPDATE:
Here is a regex that you might try. However, it might not be complete, and you will have to adjust it as you get more different field names in the vCard:
(begin|end|version|cell|adr|nickname|photo|bday|anniversary|gender|tel|email|impp|lang|tz|geo|title|role|logo|org|member|related|categories|note|prodid|rev|sound|uid|fn|n):(.*?)(?=(?:begin|end|version|cell|adr|nickname|photo|bday|anniversary|gender|tel|email|impp|lang|tz|geo|title|role|logo|org|member|related|categories|note|prodid|rev|sound|uid|fn|n):|\n|$)
See demo
The first capturing group will contain a field name and the second will contain the field value. Again, you'd be safer with a dedicated parser.
var re = /(begin|end|version|cell|adr|nickname|photo|bday|anniversary|gender|tel|email|impp|lang|tz|geo|title|role|logo|org|member|related|categories|note|prodid|rev|sound|uid|fn|n):(.*?)(?=(?:begin|end|version|cell|adr|nickname|photo|bday|anniversary|gender|tel|email|impp|lang|tz|geo|title|role|logo|org|member|related|categories|note|prodid|rev|sound|uid|fn|n):|\n|$)/gi;
var str = 'BEGIN:VCARDVERSION:2.1N:Deblieck;Tommy;;DhrFN:Tommy DeblieckTITLE:ZaakvoerderORG:QBMT bvbaADR:;;Kleine Pathoekweg 44;Brugge;West-Vlaanderen;8000;Belgi≠A0171TEL;WORK;PREF:+32 479302972TEL;CELL:+32 479302972EMAIL:tdëqbmt.beURL:www.qbis.beEND:VCARD';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
if (m[1].toLowerCase() === "n") {
document.write("Names: " + m[2] + "<br/>");
}
else if (m[1].toLowerCase() === "org") {
document.write("Org: " + m[2] + "<br/>");
}
else if (m[1].toLowerCase().indexOf("tel") === 0 ||
m[1].toLowerCase().indexOf("cell") === 0) {
document.write("Tel.: : " + m[2]);
}
}
I have this string that I get from an outside data source. It looks like this:
var myString = "Worker Management System :
Your request has been submitted
________________________________________
Your Account User Info:
Name : Doe, John, A
ID : JDOE123
Email :
Title : Worker
BusinessUnit : BARN
Department : PIGS
EmployeeID :
SupervisorName : Doe, Jane, B
HireDate : 02/22/2002
Role : Feed Pigs;
ManagerEmail : JaneDoe#mail.com
City : New York
State : NY
ZipCode : 12345
Phone : --
"
I'd like to parse this into a JSON (or something that i can work with) so that I can call maybe myString.Name and have it return Doe, John, A.
Is this possible? It's not an option for my to modify the way I get this string, I'm just trying to format it so I can easily extract the data from it.
I've looked into Douglas Crockford's JSON.parse, but that doesn't do me any good if my string isn't already properly formatted.
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
function my_string_to_object(myString)
{
var tmp = myString.split('Your Account User Info: ',2);
var tmp = tmp[1].split("\n");
var obj = {};
for(var k=0;k<tmp.length;k++) {
var line = tmp[k].split(' : ');
if(typeof(line[1]) != 'undefined') {
obj[ line[0].trim() ] = line[1].trim();
}
}
return obj;
}
I get back a json object from Facebook which contains some friends information.
Some users have included their birthday some have not, while others have included only the the month and day.
I want to sort the array putting users with a birthday that is closes to the current date first.
How can I do this?
The json object looks like this:
json = { "data" : [{name : "Joe Sam", id : "5555555", birthday: "02/02/1989" }, {name : "Joe Sam", id : 5555555, birthday: }, {name : "Joe Sam", id : 5555555, birthday: "01/01" }
Your JSON is invalid - if that is the actual JSON string keynames need to be quoted. You have left off the closing ] and }, and the middle record's birthday has to have some kind of value, e.g., empty string or null - or just don't provide that key at all. I'll assume you can fix that and will have already parsed the JSON into a variable called json.
Also you don't say if the dates are in DD/MM(/YYYY) format or MM/DD(/YYYY) format so I'll code for DD/MM but you can comment that out to use MM/DD instead.
"Closest to the current date" is ambiguous: is yesterday closer than next week? I shall assume that yesterday is as far from the current date as you can get.
So here's your object tidied up along with a sort routine. I haven't tested it, but even assuming it is broken it should give you the general idea:
var json = { "data" : [
{name : "Joe Sam", id : "5555555", birthday: "02/02/1989" },
{name : "Joe Sam", id : 5555555, birthday: null },
{name : "Joe Sam", id : 5555555, birthday: "01/01" }
]
};
// First sort into ascending birthday order, with people who didn't provide
// a birthday at the beginning of the list
function dayMonthComparer(a,b)
// note double-equals null also allows for undefined "birthday" property
if (aBD == null)
return bBD == null ? 0 : -1;
if (bBD == null)
return 1;
// next two lines allow for DD/MM format; comment them out for MM/DD format
aBD = aBD.substr(3,2) + aBD.substr(0,2);
bBD = bBD.substr(3,2) + bBD.substr(0,2);
// note: simple string compare works once in MM/DD format
return aBD === bBD ? 0 : (aBD > bBD ? 1 : -1);
}
json["data"].sort(function(a,b) {
return dayMonthComparer(a["birthday"],b["birthday"]);
});
// Next, find the first item in the array after the current date and
// move everything before that item to the end of the array.
var today = new Date(),
d = today.getDate(),
m = today.getMonth() + 1,
current,
firstNonBlank = null,
firstFromCurrent = 0;
if (d < 10) d = "0" + d;
if (m < 10) d = "0" + d;
current = d + "/" m;
// or use current = m + "/" + d if using American format
// get index of first item with birthday on or after current date
while(firstFromCurrent < json["data"].length &&
dayMonthComparer(current,json["data"][firstFromCurrent]["birthday"]) > 1) {
if (firstNonBlank===null &&
json["data"][firstFromCurrent]["birthday"] != null)
firstNonBlank = firstFromCurrent;
firstFromCurrent++;
}
if (firstFromCurrent < json["data"].length) {
json["data"] = json["data"].slice(firstFromCurrent)
.concat(json["data"].slice(firstNonBlank,firstFromCurrent),
json["data"].slice(0,firstNonBlank) );
}
// array is now sorted by birthday starting from current date, where
// those who didn't provide a birthday are at the end
For details about how .sort() works refer to the MDN doco.