var values = ["50.00024+40.04005+0.1", "0050.00024+040.04005+0.1"];
for (var i=0; i<values.length; i++) {
if(values[i].indexOf('+')>0 || values[i].indexOf('-')>0 || values[i].indexOf('*')>0 || values[i].indexOf('/')>0){
try{
var evaluated = eval(values[i]);
if(typeof evaluated === 'number'){
console.log(evaluated);
}
}catch (e){
console.error(e)
}
}
}
I have some math actions, it's could be plus, minus or other actions, and I need to take result for this actions. I use eval for this. But if I have zero before number like 005,75 eval is not working. How can I calculate this?
You can split the strings and parse the numbers, and then make them into a string again to use eval
var values = ["50.00024+40.04005+0.1", "0050.00024+040.04005+0.1"];
values.forEach(function(value){
var newValue = value.split(/([\+\-\*\/])/).map(a => parseFloat(a) || a).join('');
var evaluated = eval(newValue);
console.log(value,"==", evaluated);
});
There are various libraries like math.js that can be used to evaluate expressions:
console.log(math.eval("0050.00024+040.04005+0.1"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.16.5/math.min.js"></script>
you should convert it to float (ex. parseFloat("005.75") = 5.75 instead of evaluating strings
Given code at Question you can use .match() to get number values, .map() and .reduce() to add the values
var values = ["50.00024+40.04005+0.1", "0050.00024+040.04005+0.1"];
var res = values.map(function(n) {
return n.match(/[\d.]+/g).reduce(function(a, b) {
return a + Number(b)
}, 0)
});
console.log(res);
Related
I have sorted out two string and than used json.stringify to compare it to get Anagram. please refer below code, is this a right way to code.
function same(ar, ar1) {
//sorting the string
var o = ar.split("").sort();
var o1 = ar1.split("").sort();
//comparing two string
if (JSON.stringify(o) == JSON.stringify(o1)) {
return true;
} else {
return false;
}
}
same("ria", "air"); //true
same("", ""); //true
same("aaz", zza); //false
It'll work in most cases, but it's unnecessarily computationally expensive.
It may not work when certain non-ASCII characters are used, because .split('') will result in splitting up the character code points, eg:
console.log('𝟘'.split(''));
That's not an accurate representation of each character as an element of the array. Use Array.from instead:
console.log(Array.from('𝟘'));
After that, you can also make the algorithm less expensive by counting up the number of occurrences of each character (O(n)) rather than sorting (O(n log n)). For example:
const getCount = str => Array.from(str).reduce((counts, char) => {
counts[char] = (counts[char] || 0) + 1;
return counts;
}, {});
function same(ar,ar1){
const counts1 = getCount(ar);
const counts2 = getCount(ar1);
const keys1 = Object.keys(counts1);
const keys2 = Object.keys(counts2);
if (keys1.length !== keys2.length) {
return false;
}
return keys1.every(char => counts1[char] === counts2[char]);
}
console.log(same('abc', 'cba'));
console.log(same('abc', 'aba'));
This is my assignment:
By now you should have worked with the length property of strings, e.g. "hello".length. Your task is to write a function called stringLength that accepts a string as a parameter and computes the length of that string; however, as you may have guessed, you are not allowed to use the length property of the string!
Instead, you'll need to make use of the string method called slice.
For our purposes, we can consider slice as taking one argument -- the index to begin slicing from, and returns a new string starting from that index onwards.
This is what I tried:
function stringLength(string){
var count = count++;
if(string.slice(0)){
return count}
return stringLength(string.slice(0,-1))
}
console.log(stringLength("game"))
I am trying to slice each character of the string back to start index, index 0, and then accumulate my count variable. I do not understand why my count variable is not accumulating.
An iterative proposal.
function stringLength(string) {
var count = 0;
while (string) {
string = string.slice(1);
count++;
}
return count;
}
console.log(stringLength("game"));
A recursive proposal.
function stringLength(string) {
return string ? 1 + stringLength(string.slice(1)) : 0;
}
console.log(stringLength("game"));
Hmm i tried to write code in the same format that you did.
function stringLength(str, count){
if(!str.slice(0)){
return count;
}
return stringLength(str.slice(0,-1), ++count)
}
console.log(stringLength("game", 0))
I'll point out the mistakes in your original code so that its easy to understand.
The recursion base case was incorrect. string.slice(0) will return
true if the string is non-empty, so use !string.slice(0)
The count value was not initialized and it wasn't being passed down
the recursion.
Your count variable is a separate variable for each function invocation, so it will always get the same value and not keep incrementing.
You could use this:
function stringLength(string){
return string ? 1 + stringLength(string.slice(0,-1)) : 0;
}
console.log(stringLength("game"))
A bit shorter would be to take out the first character instead of the last:
return string ? 1 + stringLength(string.slice(1)) : 0;
You really should try to figure it out yourself. Otherwise, are you really learning the subject?
function stringLength(string) {
if(!string) return 0;
var length = -1;
while(string.slice(length) !== string) --length;
return -length;
}
A variation taking into account your odd definition of slice():
function stringLength(string) {
var length = 0;
while(string.slice(length) !== "") ++length;
return length;
}
I guess you could try to use recursion like this:
function stringLength(string) {
if (string) {
return 1 + stringLength(string.slice(1))
} else return 0
}
function stringLength(string) {
var len = 0;
while (string) {
string = string.substring(1);
len++;
}
return len;
}
console.log(stringLength("boss"));
this works as well.
I have a function that returns true if a character is a form of punctuation and I'm trying to write another function that accepts a string and removes the spaces and punctuation marks while calling the first function. I got most of it I think. But now I'm stuck. Any help is appreciated.
var isPunct = function(ch) {
if (ch = ch.match(/[,.!?;:'-]/g))
return true
else
return false
}
//B
var compress = function(s) {
var result = "";
//loop to traverse s
for (var i = 0; i < s.length; i++) {
if (!(isPunct(ch));
//(isPunct(s.charAt(i) || s.charAt(i) == " "));
//do nothing
else
result = result + !compress(i)
}
return result
}
Some issues:
The inner condition should in fact be the opposite: you want to do nothing when it is a punctuation character, i.e. you don't want to add it to the result. Only in the other case you want to do that.
The call !compress(i) is wrong: first of all that function expects a string, not an index, and it returns a string, not a boolean (so to perform ! on it). It seems like you want to call your function recursively, and although that is an option, you are also iterating over the string. You should do one of the two: recursion or iteration.
You reference a variable ch in the compress function which you have not defined there.
So, if you want to write compress the iteration way, change your code as follows:
var compress = function(s) {
var result = "", ch; // define ch.
//loop to traverse s
for (var i = 0; i < s.length; i++) {
ch = s[i]; // initialise ch.
if (!isPunct(ch)) result = result + ch; // only add when not punctuation
}
return result;
}
If on the other hand you want to keep your recursive call to compress, then you should do away with your for loop:
var compress = function(s) {
var result = "", ch, rest;
if (s.length == 0) return '';
result = compress(s.substr(1)); // recursive call
ch = s[0];
if (!isPunct(ch)) result = ch + result;
return result;
}
The function isPunct also has a strange thing happening: it assigns a boolean value to ch in the if expression. This does not make your function malfunction, but that assignment serves no purpose: the match method already returns the boolean you need for your if condition.
It is also not really nice-looking to first evaluate a boolean expression in an if to then return that same value in the form of false and true. This you can do by just returning the evaluated expression itself:
var isPunct = function(ch) {
return ch.match(/[,.!?;:'-]/g);
}
On a final note, you don't really need the isPunct function if you only use it in compress. The whole logic can be performed in one function only, like this:
let compress = s => s.replace(/[,.!?;:'-]/g,'');
// Demo:
console.log(compress('a,b,c')); // abc
If you prefer to keep isPunct and don't want to repeat the regular expression elsewhere, then you can do the replace like this:
let isPunct = ch => ch.match(/[,.!?;:'-]/g);
let compress = s => Array.from(s).filter(ch => !isPunct(ch)).join('');
// Demo:
console.log(compress('a,b,c')); // abc
Note how the use of ES6 arrow functions and ES5 Array methods makes the code quite lean.
I'm a new student who's learning Javascript for the first time. This time I'm trying to better grasp the concepts of converting numbers into strings, storing them in arrays, converting them back to numbers, and adding.
In this assignment, I'm trying to write a function that takes the individual digits of a number and adds them together.
So for example, the function would take (95) and return 14. Or given (135), would return 9.
Here's what I got so far:
var addDigits = function(num) {
var newNum = num.toString();
newNum = newNum.split('');
var sum = 0;
var thirdNum = newNum.forEach(function(x) {
parseInt(x);
sum + x };
};
I'm fully aware that is not very good code, but could anyone give me any tips? Should I be using parseInt or Number?
You're pretty close. Few things though. array.forEach doesn't return anything. It's used for creating side effects (increasing sum would be considered a side effect of the function you're passing into the forEach). So setting the forEach to a variable doesn't accomplish anything. parseInt does return something, so you need to set it to a variable. And you also want to increase sum by the parsed integer plus the sum you already have. You can look into the += operator for that if you wish. Last, you need to return a value from the function itself! As it is, if you did var added = addDigits(123), added would be undefined. So finish it off with a return statement.
After you've got the grasp of that, I'd suggest looking into array.reduce to replace array.forEach since it's perfect for a problem such as this.
var addDigits = function(string) {
newNum = string.split('');
var sum = 0;
for(var i = 0 ; i < newNum.length ; i++) sum += parseInt(newNum[i]);
return sum;
};
console.log(addDigits("1234"));
Maybe this will be better:
function getDigitsSum(number) {
var charArray = (number + '').split('');
var sum = 0;
charArray.forEach(function(item) {
sum += parseInt(item)
})
return sum;
}
Number() performs type conversion, whereas parseInt() performs parsing.
What is the difference between parseInt() and Number()?
In this situation, it doesn't make a difference since the strings are proper integers.
Here's how I would do it.
var addDigits = function(num) {
var newNum = num.toString().split('');
var sum = newNum.map(Number).reduce((prev, curr) => prev + curr);
return sum;
};
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Assuming your input will always be an integer string, consider the following function:
var addDigits = function(strInt) {
var int = function(x) {
return parseInt(x,10) //10 is the radix
}
return strInt.split('').map(int).reduce(function(a,b){return a+b});
}
The function tied to var int will ensure that the provided integer string be parsed into its corresponding base 10 integer (notice the difference in type, which can be validated with Javascript's built-in typeof() function). The return will first .split the string, .map the int function against every value within the given string, and then apply whatever function you have within .reduce against an accumulated value - in this case, simply adding against each member of the array.
new to JS.
I'm using google script to create a function that will input a string will output the interger in it (if any). In order to optimize for google script, I've read suggestions on allowing also ranges as input.
I'm getting an error when using .map, but I can't figure out what it is. Any help. I've been looking for more examples of the use of map but none were helpfull.
Any idea?
thanks everyone
if (input.map) {
input.map(
if (isInt(split[i])) {
result = split[i]
});
} else {
for (i = 0; i < split.length; i++) {
if (isInt(split[i])) {
result = split[i];
}
}
}
To .map you should pass function as parameter,
input.map(function() {
// your code
});
will input a string will output the interger in it (if any)
Try using isNaN , Number() , Array.prototype.filter() , typeof to return Number values
var arr = ["1", "a", "0"];
var res = arr.map(function(n) {
return !isNaN(Number(n)) && Number(n)
}).filter(function(n) {
return typeof n === "number"
});
console.log(res)