Javascript - Online Coding assessment to mask credit cards numbers with # [duplicate] - javascript

This question already has answers here:
Masking credit card number
(5 answers)
Closed 12 months ago.
I got the below coding assessment question in Javascript. I tried my best to solve but there are few edge cases I missed. I need help to identify those missing cases
Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct.
However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it.
This is what I tried so far
function maskify (cc) {
if (cc.length < 6) {
let reversed = reverse(cc);
let newString = '';
for (let i = 0; i < reversed.length; i++) {
if (i < 4) {
newString += reversed[i];
} else {
newString += '#';
}
}
return reverse(newString);
Output

This is my solution:
function maskify (cc) {
// If less than 6 characters return full number
if (cc.length < 6)
return cc;
// Take out first character
let firstChar = cc.charAt(0);
cc = cc.slice(1);
// Replace characters except last 4
cc = cc.replace(/\d(?=.{4,}$)/g, '#');
// Add first character back
cc = firstChar + cc;
return cc;
}
// Run every example number
const tests = ["4556364607935616", "4556-3646-0793-5616",
"64607935616", "ABCD-EFGH-IJKLM-NOPQ",
"A1234567BCDEFG89HI", "12345", "", "Skippy"];
tests.forEach((number) => console.log(`Testing: ${number} - Output: ${maskify(number)}`));
I ran it with all the numbers of your example and it gets the correct output.

Related

How to replace a specific part from strings in odd and even index in JavaScript? [duplicate]

This question already has answers here:
Matching quote wrapped strings in javascript with regex
(3 answers)
Closed 2 years ago.
How to replace a specific part from strings in odd and even index in JavaScript?
I want to replace the 1, 3, 5, etc ``` with <span class="styles"> and the 2, 4, 6, etc ``` with </span>. So that I can style the areas.
It is somewhat similar to the Stack Overflow 's Textarea/answer&question area or GitHub's editor.
For example, I have a string:
const str = "Almost ```before``` we knew it, ```we``` had left the ```ground```.";
When I will print it on the page, I want it somewhat like this.
Almost <span class="styles">before</span> we knew it, <span class="styles">we</span> had left the <span class="styles">ground</span>.
I have researched a lot but I am only able to extract this ``` from the string and I don't know how to replace in odd and even pattern.
Any help would be appreciated.
You could search for a group between the separators with non greedy search between and take the group with new tags around.
const
string = "Almost ```before``` we knew it, ```we``` had left the ```ground```.",
result = string.replace(/```(.*?)```/g, '<span class="styles">$1</span>');
console.log(result);
You could iterate through each one and do something along the lines as the following:
const str = "Almost ```before``` we knew it, ```we``` had left the ```ground```.";
const parts = str.split('```')
let final = parts[0]
for (let i = 1; i < parts.length -1; i++) {
if (i % 2 === 1) {
final += '<span class="styles">'
} else {
final += '</span>'
}
final += parts[i]
}
final += '</span>' + parts[parts.length - 1]
function repl(str, mark) {
var inside = false
var last = 0
var builder = []
for(var i in str) {
i = parseInt(i)
if (str.substring(i, i + mark.length) == mark) {
builder.push(str.substring(last, i))
last = i + mark.length
if (inside) {
builder.push(`<span class="stile">`)
} else {
builder.push(`</span>`)
}
inside = !inside
}
}
builder.push(str.substring(last))
return builder.join("")
}

How to count character followed by Special Character in string using Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My string is: Hello 1⃣2⃣3⃣ world.
The expected result is 3 (1⃣ 2⃣ and 3⃣)
Matching condition has total 12 value below:
(0⃣ 1⃣ 2⃣ 3⃣ 4⃣ 5⃣ 6⃣ 7⃣ 8⃣ 9⃣ *⃣ #⃣ )
How to use javascript to count total of result? Thank you.
// Get code of emoji
function getEmojiUnicode(emoji) {
var comp;
if (emoji.length === 1) {
comp = emoji.charCodeAt(0);
}
comp = (
(emoji.charCodeAt(0) - 0xD800) * 0x400
+ (emoji.charCodeAt(1) - 0xDC00) + 0x10000
);
if (comp < 0) {
comp = emoji.charCodeAt(0);
}
return comp.toString("16");
};
// count how many times emoji appears
function countSpecialCharacter(string) {
// what should I write here?
return result;
}
var inputString = 'Hello 1⃣2⃣3⃣ world';
var output = countSpecialCharacter(inputString); // this should be 3
Definition of Combining Enclosing Keycap is here
https://emojipedia.org/combining-enclosing-keycap/
1) Split the string by ' ' and get the words
2) Check each word if it had enclosing keyCap
3) If so, return length/2 (because each char has one enclose)
const count = line => {
const valid_chars = Array.from("0123456789*#");
const sp_chars = line.split(" ").find(x => x.includes("⃣"));
if (sp_chars && sp_chars.length % 2 === 0) {
return Array.from(sp_chars).filter(x => valid_chars.includes(x)).length;
}
return 0;
};
console.log(count("Hello 1⃣2⃣3⃣-⃣ world"));
I think what you need to do is iterate through each character you have in your string, looking at the unicode character. Once you have this you can compare this to a list of unicode characters you know are 'Keycaps' - giving you the count.
I.e (this is just checking the first character in a string as an example):
function isCharacterAKeycap(str) {
var keycapUnicodeValues = [8000, 8001, 8002];
return keycapUnicodeValues.includes(str.charCodeAt[0]);
}
str = "1⃣";
isCharacterAKeycap(str);

Average calculator finding strange and incorrect numbers [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 3 years ago.
I am trying to make an average calculator. This is my code for it:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
}
var average = total / data.length;
document.write(average);
It seems to take input well, however something goes wrong when it comes to calculation. It says that the average of 6 and 6 is 33, 2 and 2 is 11, and 12 and 6 is 306. These are obviously wrong. Thank you in advance for your help.
You need to take a number, not a string value from the prompt.
The easiest was is to take an unary plus + for converting a number as string to a number
data.push(+newdata);
// ^
Your first example shows, with '6' plus '6', you get '66', instead of 12. The later divsion converts the value to a number, but you get a wrong result with it.
It is taking the input as string. Convert the input to floats before putting them in the array. I think its performing string additions like 6+6=66 and then 66/2 = 33. Similar is the case of 2 and 2.

Convert Google Contact ID to Hex to use in URL

Google Contacts now (Jan 2019) issues a long (19 digit) decimal number id for each contact that you create.
Unfortunately, as discussed in this question the ID cannot be put into a URL to view the contact easily, however if you convert this decimal number to Hex it can be put into the URL.
So the question is, how to convert
c2913347583522826972
to
286E4A310F1EEADC
When I use the Decimal to Hex converter here it gives me
286E4A310F1EEADC if I drop the c (2nd function below is a version of the sites code, but it does use PHP too maybe)
However trying the following functions in Javascript give me mixed results
The first one is from this stack question which is the closest, just 2 digits off
function decimalToHexString(number)
{
number = parseFloat(number);
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}
return number.toString(16);
}
console.log(decimalToHexString('2913347583522826972'));
//output 286e4a310f1eea00
function convertDec(inp,outp) {
var pd = '';
var output ;
var input = inp;
for (i=0; i < input.length; i++) {
var e=input[i].charCodeAt(0);var s = "";
output+= e + pd;
}
return output;
}
//return 50574951515255535651535050565054575550
Love to know your thoughts on improving this process
It seems like the limit of digit size. You have to use arrays if you need to convert bigger digits.
You can use hex2dec npm package to convert between hex and dec.
>> converter.decToHex("2913347583522826972", { prefix: false }
//286e4a310f1eeadc
Js example
On python side, you can simply do
dec = 2913347583522826972
// Python implicitly handles prefix
hexa = hex(dec)
print dec == int(hexa, 16)
// True
Python example
For more take a look at the following gist
https://gist.github.com/agirorn/0e740d012b620968225de58859ccef5c

Reverse The Words In A Sentence But Not The Letters [duplicate]

This question already has answers here:
Reversing a string
(4 answers)
Closed 5 years ago.
I want to make a program to reverse the words only, not the letters.
For example...
i love india
... should become...
india love i
Another example...
google is the best website
... should become...
website best the is google
With spaces I have thoroughly researched on it but found just nothing.
My logic is that I should just give you my program that is not working. If you find a small error in my code please give the solution for it and a corrected copy of my program. Also, if you are not too busy, can you please give me the logic in a flow chart.
my logic is here
Thank you for your time.
class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
// split to words by space
String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = arr.length - 1; i >= 0; --i) {
if (!arr[i].equals("")) {
sb.append(arr[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}
1.
Store the words of each line in a string array.
2.
Print the elements of the array from the last item to the first.

Categories

Resources