Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
There're a lot of examples of masking names with RegExp but I couldn't find my case.
I want to mask companies names according to the following examples:
ST --> S*
STE --> S*E
STEP --> S**P
Apple --> A***e
Mozilla --> Mo****la
Mozilla Firefox --> Moz**** ****fox
LTD Best Company --> LTD **** ****any
Telecommunications --> Tel************ons
No Matter How Long --> No ****** *** *ong
GRAS Company Name --> GRA* ******* *ame
Any ideas? Please, help.
You can use a loop
function mask(string) {
const show = string.length > 7 ? 3 : string.length > 5 ? 2 : 1
const result = []
for (let i = 0; i < string.length; i += 1) {
const char = string[i]
if (i < show || i > string.length - show - 1 || char === ' ') {
result.push(char)
} else {
result.push('*')
}
}
return result.join('')
}
const strings = [
'ST', // --> S*
'STE', // --> S*E
'STEP', // --> S**P
'Apple', // --> A***e
'Mozilla', // --> Mo****la
'Mozilla Firefox', // --> Moz**** ****fox
'LTD Best Company', // --> LTD **** ****any
'Telecommunications', // --> Tel************ons
'No Matter How Long', // --> No ****** *** *ong
'GRAS Company Name', // --> GRA* ******* *ame
]
for (const string of strings) {
console.log(string, '-->', mask(string))
}
function mask(string) {
const show = string.length > 7 ? 3 : string.length > 5 ? 2 : 1
const result = []
for (let i = 0; i < string.length; i += 1) {
const char = string[i]
if (i < show || i > string.length - show - 1 || char === ' ') {
result.push(char)
} else {
result.push('*')
}
}
return result.join('')
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
if I have the following values
0 - a
1 - b
2 - c
4 - d
8 - e
16 - f
if i get the value 17, how would i know that values b and f are in that values, some for the others as these can be mixed together by adding, so bd value would be 6
Convert your value to binary format. For example 17 => 10001. Then select only 1's. You can make for loop starts from 'a' to 'z'. Increase characters +1 then convert to character.
This is sample code:
function foo(num) {
if (num == 0)
return 'a';
const binaryNum = (num >>> 0).toString(2);
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
var converted = '';
var asci = 'b';
for(var i=binaryNum.length-1; i>=0; --i) {
if (binaryNum.charAt(i) == '1')
converted+=asci;
asci = nextChar(asci);
}
return converted;
}
console.log(foo(17));
console.log(foo(0));
console.log(foo(6));
console.log(foo(28));
Output is:
bf
a
bd
def
Note that 'bd' is 5.
Much like the bank note problem, reduce down the value in denominations, then pick out the index for the map to the letter.
const v1 = [0, 1, 2, 4, 8, 16];
const v2 = ['a', 'b', 'c', 'd', 'e', 'f'];
let value = 7
const vMap = new Map();
for (let i = v1.length - 1; i >= 0 && value; i--) {
const qty = Math.floor(value / v1[i]);
qty && vMap.set(v1[i], qty);
value = value % v1[i];
}
const entries = Array.from(vMap.entries());
console.log(entries.map(([curr, qty]) => `${curr} * ${qty} = ${curr * qty} is ${v2[v1.indexOf(curr)]}`))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a list of different units:
const unitList = [1, 10, 36, 50, 20]; // all different numbers and all numbers are above 0
const unit = 13; // this is not included in unitList and not more that max number in unitList
And I want to get the index of unit in which unit should be placed before. for instance:
const unit = 13; returns index 4 because it should be placed before 20
const unit = 35; returns index 2 because it should be placed before 36
function getUnitPosition() {
if(!unitList.length) return 'before add new unit';
const max = Math.max(...unitList);
if(unit > max) return 'before add new unit';
const min = Math.min(...unitList);
if(unit < min) return columns[0].id;
for(let a = 0; a < unitList.length; a++) {
console.log(unit , unitList[a], unit < unitList[a])
if(unit < unitList[a]) return columns[a].id;
}
}
You could take the first found index with a smaller value than unit. For any other smaller value check the value to get the smallest one.
const
getIndex = (data, unit) => {
let index;
for (let i = 0; i < data.length; i++) {
if (
unit < data[i] &&
(index === undefined || data[i] < data[index])
) index = i;
}
return index;
},
unitList = [1, 10, 36, 50, 20];
// 13 ^^
// 35 ^^
console.log(getIndex(unitList, 13)); // 4 placed before 20
console.log(getIndex(unitList, 35)); // 2 placed before 36
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
I'm creating a function that generate a random Uniq Serial id by replacing a string with this format ; xxxx-xxxx-xxxx-xxxx , the goal is to get a serial like that : ABCD-1234-EFGH-5678 ,the first and third parts are a letters and the second and last parts are numbers, this is my code :
public generateUniqSerial() {
return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, function (c) {
let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
return v.toString(16)
})
}
it give a result like that : "7f8f-0d9a-fd5-450f"
, how to edit this function to get a result with this format : ABCD-1234-EFGH-6789 ?
You can do something like this to generate a random Uniq Serial id with a format like ABCD-1234-EFGH-5678:
function rnd(t) {
let str = '';
const min = t === 'a' ? 10 : 0;
const max = t === 'n' ? 10 : 62;
for (let i = 0; i++ < 4;) {
let r = Math.random() * (max - min) + min << 0;
str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48);
}
return str;
}
function generateUniqSerial() {
return `${rnd('a')}-${rnd('n')}-${rnd('a')}-${rnd('n')}`
}
console.log(generateUniqSerial())
console.log(generateUniqSerial())
When I'm asked to do things like this I like to start with a "string of letters" and a "string of digits." My logic then simply consists of choosing a random index into the appropriate source string to get each character that I need. I like to do it this way because to me it's "extremely obvious" what I am doing and equally easy to desk-check that it will work.
Missing link to credit card validation using only JavaScript. Needs to have atleast two different digits and all digits should not be the same. I am unable to return values in the text please help thank you. Here is a link to the exercise.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Credit Card Validation</title>
<meta name="description" content="CHANGE THIS CONTENT DESCRIPTION">
</head>
<body>
<span>Credit Card Number* :</span>
<input class="inputForm" type="number" id="ccn" name="inputStealMoney"
placeholder="Enter Credit Card Number"><span class="restriction" id="CCNSpan"></span>
<button type="button" onclick="CCNSpan">Submit</button>
<br>
<p id="CCNSpan">Text</p>
<script>
function funcCall() {
validFormCCN();
}
function validFormCCN() {
var x, textC;
x = document.getElementById('ccn').value;
//If statement below is blank in the last () paranthesis. It needs to be filled with 'different numbers' to work
if (isNaN(x) && (x%2) ==0 && x.length==16 && ()) {
/*The if statement above is NaN() and x%2==0 is even and x.length is 16 digits and the blank () paranthesis where all the digits cannot be the same with atleast two different digits*/
return true;
}
else {
return false;
}
}
document.getElementById("CCNSpan").innerHTML = textC;
</script>
</body>
</html>
Consider using the following regex pattern:
(\d)(?!\1{15})\d{15}
This asserts that the credit number contains 16 digits, and that the first number does not repeat for the next 15 digits. This implies that there are at least 2 numbers which are not the same.
var str = "1111111111111111";
var patt = new RegExp("(\\d)(?!\\1{15})\\d{15}");
var res = patt.test(str);
console.log(res);
str = "1111111115111111";
res = patt.test(str);
console.log(res);
Of course, in practice, in a production e-commerce site, you would be using much more complex regular expressions. Visa, MasterCard, etc. have rules for how their credit card numbers are formed. You may visit this link for more information.
Your code looks somewhat like an attempt to implement the Luhn algorithm. Implementations for many languages including JavaScript can be easily found.
var luhn10 = function(a,b,c,d,e) {
for(d = +a[b = a.length-1], e=0; b--;)
c = +a[b], d += ++e % 2 ? 2 * c % 10 + (c > 4) : c;
return !(d%10)
};
However, not all credit card companies use the Luhn algorithm. This it is recommended to use a library function to validate credit card numbers, e.g. the jQuery Validation Plugin. Another common implementation is provided by Braemoor and a regex-based JS version can be found here.
function validateCcn(value) {
// Accept only spaces, digits and dashes
if ( /[^0-9 \-]+/.test( value ) ) {
return false;
}
var nCheck = 0,
nDigit = 0,
bEven = false,
n, cDigit;
value = value.replace( /\D/g, "" );
if ( value.length < 13 || value.length > 19 ) {
return false;
}
for ( n = value.length - 1; n >= 0; n-- ) {
cDigit = value.charAt( n );
nDigit = parseInt( cDigit, 10 );
if ( bEven ) {
if ( ( nDigit *= 2 ) > 9 ) {
nDigit -= 9;
}
}
nCheck += nDigit;
bEven = !bEven;
}
return ( nCheck % 10 ) === 0;
}
console.log(validateCcn('1234-1234-1234-1234'));
console.log(validateCcn('378282246310005'));
So I understand that my question is about masking. I saw the documentation of masking for javascript here.
so I tried:
var PEN = 1;
var CHAIR = 2;
var TABLE = 4;
> PEN | CHAIR
3
But what if what I have is 3 how do I get what I have from that number alone?
Original Question
Say, I have the following constant numbers:
1 | 2 | 4
These numbers corresponds to a something.
Let us say: 1 is a pen, 2 is a chair and 4 is a table.
Possibilities:
If I have the #1 it means I have a pen but NO chair and table.
If I have the #2 it means I have a chair but NO pen and table.
If I have the #4 it means I have a table but NO pen and chair.
If I have the #3 it means I have a pen and a chair but NO table.
If I have the #6 it means I have a chair, a table but NO pen.
If I have the #7 it means I have a pen, a chair and a table.
Question: Now say all I know about is the number 6. How do I programatically decipher that 6 means 2 and 4 or I have a chair and a table?
Sorry, this is also confusing me. I'm trying to reimplement a skills list algorithm for a game to javascript. Where if I have 6 it means I have the 2nd and 3rd skill but not the 1st skill.
Also what is this approach called?
Lets say you have 5 skills... A, B, C, D and E. You can encode these skills as first, second, third, fourth and fifth bit of an integer.
So, if a players skill is 0b00001000... that means he has 4th skill.
Now,
// No skill
var skill = 0;
// add skill B... which means set second bit to 1.
skill = skill | ( 1 << 1 );
// add skill A
skill = skill | ( 1 << 0 );
//check for skill B,
var hasSkillB = ( ( skill & ( 1 << 1 ) ) > 0 );
// Remove skill B
skill = skill & ( ~( 1 << 1 ) );
This looks more like a problem of finding elements summing up to the target value:
var elementsUsedInSum = function (arr, sum) {
var curr_sum = arr[0], start = 0, i;
for (i = 1; i <= arr.length; i++)
{
while (curr_sum > sum && start < i-1)
{
curr_sum = curr_sum - arr[start];
start += 1;
}
if (curr_sum === sum)
{
console.log ("Elements from " + start + " to " + i-1 + " found.");
}
// Add this element to curr_sum
if (i < n)
curr_sum = curr_sum + arr[i];
}
console.log ("Combination not possible");
}
If you want an easy way to do it just mask the bits and compare it with the number:
var FLAG_A = 1; // 0001 - PEN
var FLAG_B = 2; // 0010 - CHAIR
var FLAG_C = 4; // 0100 - TABLE
var PEN;
var CHAIR;
var TABLE;
n = 3; //Input number
if (n & FLAG_A) {
PEN = true;
} else {
PEN = false;
}
if (n & FLAG_B) {
CHAIR = true;
} else {
CHAIR = false;
}
if (n & FLAG_C) {
TABLE = true;
} else {
TABLE = false;
}