Questions example phoneNumber [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am a student studying JavaScript.
It hasn't been long since I studied.
Example, createPhoneNumber
The length is up to 11 digits.
I wrote the code in question like this.
function createPhoneNumber(arr) {
let first = '(010)';
if(arr.length === 11){
return `(${arr.slice(0,3).join('')})${arr.slice(3,7).join('')}-${arr.slice(7,11).join('')}`;
}
return `${first}${arr.slice(0,4).join('')}-${arr.slice(4,8).join('')}`;
}
I think it's very messy code.
Is it better to add a new variable to make it shorter and simpler?

This can be done by Regex:
function createPhoneNumber(arr) {
let first = '(010)';
// the submatch (\D)? is intended to get an empty match when the length of arr is not 11
let reg = arr.length == 11 ? /(\d{3})(\d{4})(\d{4})/ : /(\D)?(\d{4})(\d{0,4})(\d{0,})/;
return arr.join('').replace(reg, (match, $1, $2, $3) => ($1 ? "(" + $1 + ")" : first) + $2 + "-" + $3);
}
console.log(createPhoneNumber([0,1,0,1,2,3,4,5,6,7,8]));
console.log(createPhoneNumber([1,2,3,4,5,6]));
console.log(createPhoneNumber([1,2,3,4,5,6,7,8,9,0,0,0,0,0]));

You want it shorter and simpler? This is subjective but I believe the following applies. Also, I wasn't sure if you misused your 11th digit in your function so... I made it work with 10.
function createPhoneNumber(arr) {
const arrL = arr.length;
let arrI = arrL - 4;
arr.splice(arrI, 0, "-");
arr.splice(arrI -= 3, 0, ")");
arr.splice(0, 0, arrL === 10 ? "(" : "(010");
return arr.join("");
}

If it's just a matter of readability, I suggest a few changes:
Export hard coded values to const.
Don't duplicate your code! like the complicated return you had.
It did look messy - do I decided to separate the number to 3 parts - 3 variables, and use 1 return
const PRE_FIRST = '(010)';
const FULL_NUMBER_LENGTH = 11;
function createPhoneNumber(arr) {
let isFullPhone = FULL_NUMBER_LENGTH === arr.length;
let first = isFullPhone ? arr.slice(0, 3).join('') : PRE_FIRST;
let second = (isFullPhone ? arr.slice(3, 7) : arr.slice(0, 4)).join('');
let third = (isFullPhone ? arr.slice(7, 11) : arr.slice(4, 8)).join('');
return `${first}-${second}-${third}`;
}

Related

JavaScript: How to create a function that receives an array of numbers and returns an array containing only the positive numbers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
What is Wrong with this Code? I should create a function that receives an array of numbers and returns an array containing only the positive numbers. How can it be modified? Especially Modified. Not another code!
all = prompt("Give me an array of numbers seperated by ','");
var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
var positive = [];
for(var i = 0; i < splitted.length; i++);{
var el = splitted[i];
if (el >= 0){
positive.push(el);
}
}
return positive;
}
var positive = returner(splitted);
print(positive);
First I noticed that you are using print to check your output - that should be console.log().
But your real mistake is the semicolon after the for bracket in line 7.
Here is a working code-snippet:
let all = prompt("Give me an array of numbers seperated by ','");
let splitted = all.split`,`.map(x => +x);
function returner(splitted) {
let positive = [];
for (let i = 0; i < splitted.length; i++) {
const el = splitted[i];
if (el >= 0) {
positive.push(el);
}
}
return positive;
}
var positive = returner(splitted);
console.log(positive);
Just remove the semicolon after the for statement as:
all = prompt("Give me an array of numbers seperated by ','");
var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
var positive = [];
for(var i = 0; i < splitted.length; i++){
var el = splitted[i];
if (el >= 0){
positive.push(el);
}
}
return positive;
}
var positive = returner(splitted);
console.log(positive);
practically with that semicolon you were doing "nothing" n times and then executing the block on it's own which didn't help filling your array since the i variable is already passed the last index of the array and so splitted[i] results to undefined which is not >=0 thus nothing gets pushed to the positive array.
(also I'd imagine you want a console.log at the end instead of print? )
Why don't you use filter?
var array = [3, -1, 0, 7, -71, 9, 10, -19];
const getpositiveNumbers = (array) => array.filter(value => value > 0);
var positives = getpositiveNumbers(array);
console.log(positives);
Anyway, as #trincot noticed, your code is wrong.

I’m trying to write a function in javascript that Returns the number of times a number occurs as a digit in another number [closed]

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 years ago.
Improve this question
The second input number will always be between 0 and 9, and I must use the filter method. This is what I have so far:
const countOccurrencesFilter = (number, target) => {
let numStrArr = number.toString().split('');
let targetStr = target.toString();
let count = numStrArr.filter = (numStrArr => numStrArr[0] === targetStr).length;
return count;
};
You're almost there, you're assigning a key to numStrArr named filter whereas in actual you need to call the method. you need use
numStrArr.filter(numStrArr ...
not
numStrArr.filter = (numStrArr
const countOccurrencesFilter = (number, target) => {
let numStrArr = number.toString().split('');
let targetStr = target.toString();
let count = numStrArr.filter(numStrArr => numStrArr === targetStr).length;
return count;
};
console.log(countOccurrencesFilter(121, 1))
console.log(countOccurrencesFilter(000, 1))
P.S:- Also no sense of using numStrArr[0] as you splited values will always be one character long only as you're spliting with ''
I think this will solve your purpose.
const countOccurrencesFilter = (number, target) => {
let numStrArr = number.toString().split('');
let targetStr = target.toString();
let count = numStrArr.filter(digit => digit === targetStr).length;
return count;
};
console.log(countOccurrencesFilter(11211, 1));
Try changing
let count = numStrArr.filter = (numStrArr => numStrArr[0] === targetStr).length;
To
let count = numStrArr.filter(numStrArr => numStrArr === targetStr).length;

looping over certain elements on an array in javascript [closed]

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 3 years ago.
Improve this question
i have a very long array of points like so:
latlngs: [
[3.063895, 50.636767],
[3.06339, 50.637233],
[3.063309, 50.637278],
[3.063254, 50.637288],
[3.063103, 50.637267],
[3.061939, 50.636762],
[3.059679, 50.635821],
[3.056687, 50.634532],
[3.067972, 50.628265],
[3.068189, 50.628169],
[3.068389, 50.628159],
[3.06959, 50.628201],
[3.075613, 50.629068],
[3.077604, 50.629383],...
// 4500 array more
]
And i would like to loop on one on n element on it to make the computation less intensive. For example i would like to loop on 1 on 6 elements. What would be the best way to do that ?
A for loop seems like the simplest solution:
for (let n = startIndex; n < endIndex; ++n) {
const entry = theArray[n];
// ...
}
You can also create an array from a slice of an array, but it...creates an array (and, in this example, an iterator object, though that may get optimized away):
for (const entry of theArray.slice(startIndex, endIndex)) {
// ...
}
In a comment, user753642 said they think you mean "...elem 0, elem 6, elem 12". If so, you'd use n += 6 rather than ++n:
for (let n = startIndex; n < endIndex; n += 6) {
const entry = theArray[n];
// ...
}
That assumes you know endIndex is <= theArray.length. If you're accepting it from outside you may not know that, in which case:
for (let n = startIndex, end = Math.min(theArray.length, endIndex); n < end; n += 6) {
const entry = theArray[n];
// ...
}
A simple for loop is enough
for (let index = 0; index < latlngs.length; index+= 6) {
// do whatever computation you need with latlngs[index]
}
an alternative to the for loop with 6 increment can be the usage of modulo
latlngs.forEach((x, i) => {
// cbk + return in case of modulo !== 0 is negligible
// in regards to doyourstuff
if (i % 6 !== 0) { return }
doyourstuff
})

JAVASCRIPT Can someone fix my code? [closed]

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 5 years ago.
Improve this question
Can someone help me fix my code?
The function is like the Eval function but has a √ added but it doesn't work
function Eval(n) {
var a = n.split("√").length - 1;
var b = n.split("√").length;
var c = a.replace("√" + d, e);
var d = parseFloat(b[1]);
var e = Math.sqrt(d);
while (a != 0) {
b();
d();
e();
c();
return;
}
}
document.write(Eval("64+√68+32"));
There are some issues with your code and going by your approach, I have updated the code to following. Please see, whether it helps!
Please note, I am assuming as per the name of the function, that you want to evaluate the expression. Also, there are other assumptions as well, like there will be only one square root expression and all operations will be additive.
function Eval(n) {
var b = n.split("√"); // you were expecting b to be an array
var a = b.length - 1; // you can use b here
var d = parseFloat(b[1]); // d should have been assigned before using in c
var e = Math.sqrt(d);
var c = n.replace("√" + d, e);
return c.split("+").reduce(function(a, b) {
return a + parseFloat(b); // sum up all the values
}, 0);
}
console.log(Eval("64+√68+32"));
You can try tweaking here
function eval(n){
var numbers = n.split('+'); // split the exepression with the + operator
var result = 0; // initaliaze the result to 0
for(number of numbers){ // for each number of numbers
if(number.indexOf('√') !== -1){ // if the number contains sqrt
number = +number.substring(1, number.length); // cast to int
result += Math.sqrt(number);
}else{
number = +number; // cast string to int, NaN if not possible
result += number;
}
}
return result;
}
This function will work for you additions.
Not that this is just a point to start, and not the best way of doing it, I tried to be the more comprehensive seeing that you are a beginner in javascript

How to convert a string into a series of digits in Javascript? [closed]

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 8 years ago.
Improve this question
What would be a good way to turn a string into a series of digits in Javascript (I'm not talking about converting "0.5" into 0.5, but more "Hello" into 47392048)?
Any idea appreciated.
Thanks!
You can use the ASCII value of each letter:
"a letter".charCodeAt(0);
Ok, so given your comments, here is a (not widely tested) solution.
var str = "κόσμε 这是一条狗 é €";
$('#orig').after('<dd>' + str + '</dd>');
var result = "";
for (var i = 0, len = str.length, code, paddedCode; i < len; ++i) {
code = str[i].charCodeAt(0).toString();
paddedCode = code.length >= 8
? code
: new Array(8 - code.length + 1).join(0) + code; result += paddedCode;
result += paddedCode;
}
$('#nums').after('<dd>' + result + '</dd>');
var segments = result.match(/.{8}/g);
$.each(segments, function(k, v) {
$('#nums-segmented').after('<dd>' + v + '</dd>');
});
revertedString = '';
for (var i = 0, len = segments.length; i < len; i=i+2) {
revertedString += String.fromCharCode((segments[i] | 0));
}
$('#string').after('<dd>' + revertedString + '</dd>');
Run it at JSFiddle
The trick is to pad number and work with them as string when needed.

Categories

Resources