&&& operator as codeblock glue [closed] - javascript

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 9 years ago.
Improve this question
Is there a way to make &&& behave as an operator which can concat operations into one codeblock?
This is something that came up to my mind while coding and was wondering if I could implement it somehow.
What I'm trying to achieve is make code more concise.
Example:
for (i=0;i<n;++i)
arr[i][0]+=2; &&& arr[i][1]+=3; &&& arr[i][2]=45;
I do not want to hear about how I can use additional for loop or use { } instead.
I'm wondering if such operator is possible in c++, javascript or (if not in one of those 2) in ruby
EDIT: I was aware that this is a bad thing to do but I was wondering if it is possible to be done nevertheless.
I though this was the whole point of having fun while coding.

Well, &&& is lexed as && followed by &, so you could overload the && operator taking a pointer:
struct X
{
int x;
X& operator=(int i)
{
x = i;
return *this;
}
X& operator+=(int i)
{
x += i;
return *this;
}
X& operator&&(X*)
{
return *this;
}
};
Unfortunately, operator precedence gets in the way, so you have to parenthesize the assignments:
int main()
{
const int n = 10;
X arr[n][3];
for (int i = 0; i < n; ++i)
{
(arr[i][0]+=2) &&& (arr[i][1]+=3) &&& (arr[i][2]=45);
}
}
(But of course nobody in their right mind would actually use abominations like this in production code.)

You could use the , operator instead:
arr[i][0]+=2, arr[i][1]+=3, arr[i][2]=45;
But this is a very ugly way to code (and so is your proposal). Introducing a block and having each as a separate statement would be much easier to read.

It is not part of the language definition, so no - you cannot arbitrarily define new syntax - that would be a different language. You could create a preprocessor or translator to convert your new language to valid C++, but I hardly see what purpose this would serve on its own.

Related

How to compare strings in different languages (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 1 year ago.
Improve this question
I need to make a function that compares two strings, no matter the language. Example:
let string1 = 'hola' //Spanish
let string2 = 'hi' //english
console.log (string1 === string2) //true as expected result
Is there a way to compare strings in different languages.
Regards!!
No, not really. Doesn't make much sense either considering that each word might have different meaning in each language depending on context.
Best you can do is try to translate the words and try to find matches in one of the many translations, or use an embedding model for those specific languages and see if the vectors are similar.
The only idea that I have right now is to declare 2 Maps for both languages and then get the key:
var spEn = new Map();
spEn.set('hola', 'hi');
var enSp = new Map();
spEn.set('hi', 'hola');
function spanishEnglish(spanish, en){
translation = spEn.get(spanish);
return translation === en;
}
function englishSpanish(en, spanish){
translation = enSp.get(en);
return translation === spanish;
}
console.log(spanishEnglish('hola', 'hi'))
console.log(englishSpanish('hi', 'hola'))
However this is a just a rudimentary example. There are tons of things you need to pay attention to :)

Assignment within a ternary operator, an anti-pattern? [closed]

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 5 years ago.
Improve this question
I have a colleague who uses ternary operators this way (In javascript):
var genderLabel = '';
isMale? genderLabel = 'Man' : genderLabel = 'Woman';
In C#, I'd just do that .
var genderLabel = isMale? "Man" : "Woman";
My colleague says it's a javascript coding convention... is that true? I'm no javascript expert and I dislike that language... When I review code, I focus on my left hand-side to follow a variable initialization or assignment, that kind of style forces me to read the whole line.
I'm also maintaining a Java code of an ex-employee, he uses ternary operators the same way. Is that an anti-pattern? I think it should be disallowed by the compiler the same way it's disallowed in a if statement :
if(x = 2)
{
...
}
This won't compile in C#.
My colleague says it's a javascript coding convention... is that true?
No.
Is that an anti-pattern?
Usually a line by itself is a statement, however this
isMale ? genderLabel = 'Man' : genderLabel = 'Woman';
is an expression, with a side effect of setting the value of genderLabel. Is that a good practice? I don't know, however if you think that is a good practice, then you will also have to allow this:
var a = 1, b = 2;
b = [a][a = b, 0]; # swap a and b
Your colleague might as well do:
if(isMale) genderLabel = 'Man';
else genderLabel = 'Woman';
which is much clearer.

Can someone help explain why I get this 'Value is not what was expected' error with 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 6 years ago.
Improve this question
I'm working on beefing up my Javascript skills with some katas on codewars. Here is one such kata:
At a job interview, you are challenged to write an algorithm to check if a given string, s, can be formed from two other strings, part1 and part2.
The restriction is that the characters in part1 and part2 are in the same order as in s.
The interviewer gives you the following example and tells you to figure out the rest from the given test cases.
For example:
'codewars' is a merge from 'cdw' and 'oears':
s: c o d e w a r s = codewars
part1: c d w = cdw
part2: o e a r s = oears
Here is my solution that I am working on:
function presentInString(element, index, array) {
return string.includes(element);
}
function isMerge(s, part1, part2) {
string = s;
var mergedParts = (part1 + part2).split('');
mergedParts.every(presentInString);
}
My approach is simple, I get passed in a string 'codewars' and with parts 'cdw' and 'oears' The above methods should return true because all of the characters are in the string. but I keep getting a Value is not what was expected error. I must be using the .every method wrong but I'm not sure how. I pretty much based it off of the Javascript MDN docs. Could someone pinpoint what I'm doing wrong?
It's a kata in progress by the way and I haven't tested all edge cases. Some cases will fail.
Additionally, do I have to create another function to pass into .every? I would rather just right the logic in the scope of .every instead of writing another function to pass off to.
I can't vouch for your overall algorithm, but the problem with isMerge is that it doesn't use the return value of every and doesn't return anything. You probably wanted:
return mergedParts.every(presentInString);
as the last line, which makes the return value of isMerge whatever every returns (true if presentInString returns a truthy value for each element, false if it doesn't).

Getting all positions of bit 1 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 6 years ago.
Improve this question
I have provided binary for example, 01001, and would like to get positions of bit 1, so I expect it will return me [0, 3].
Is there any function provided by javascript to get all positions of bit 1?
If it's a number, convert it to a string before hand, if it is a string you can do:
positionArray = [];
binary.split('');
for (i = 0; i < binary.length; i++){
if (binary[i] == "1"){
positionArray.push(i);
}
}
return positionArray;
What i'm essentially doing is converting the string to an array (or number to a string to an array) of characters and then going through each entry to find the positions of each '1'.
Not sure you can do it this way with numbers, which is why I suggested converting it to a string before hand. It's just a rough solution and I bet there are much better ways of doing it but hope it helps.
MDN has a useful piece of code that works numerically and will take a number like 9 or in binary 0b1001 and return you an array with true/false values depending on whether or not the corresponding bit is set in the input value. For 1001 it returns [true, false, false, true]
You can then use this array to create your desired output by checking which indexes are true, and getting [0,3]
The MDN snippet is here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Reverse_algorithm_an_array_of_booleans_from_a_mask
And a quick example of using it is here:
https://repl.it/DuEh/5
#DibsyJr has a nice solution if you are dealing with strings. However if you start from a number, then converting it to a string is an unnecessary overhead. You can do it efficiently with this function:
function get_idxs(x) {
var arr = [];
var idx = 0;
while (x) {
if (x & 1) {
arr.push(idx);
}
idx++;
x >>= 1;
}
return arr;
}
> get_idxs(0b1001);
[0, 3]
WARNING: It does not work for negative numbers. Unfortunately for negative numbers the answer to the question depends on the underlying cpu architecture.

Javascript multipying without using * sign [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 7 years ago.
Improve this question
Practice Problem 1
Parameters: The function accepts two positive integers N and M.
Return Value: The function returns the product of N and M. For example, if the integers 5 and 8 are supplied to
that function, it should return the product of 5 and 8—it should return 40.
Additional
Requirements:
Do this without using the multiplication operator (*). Hint: Multiplication is just a series of addition
operations.
function mult(N, M) {
return N / (1 / M);
}
Since this is a basic excercise, I think that this answer is not expected (but maybe you'll get bonus points if you can explain it), even though it does the math without *.
function mult(N,M){
var a = new Array(N);
return a.join(""+M).split("").reduce((x,y)=>(parseInt(x)+parseInt(y)))+M
}
Note: This does not work for N < 3. No time to correct it.
OK. Look. It sounds like you're quite young so I think giving you the benefit of the doubt is alright here. So you know for the future: Stackoverflow isn't a site that you can just drop a homework question and expect people to do the work for you.
We sometimes do help with homework questions but only if it looks like you've at least attempted to answer the question yourself, by showing us some code that you've written. If you want to use SO in the future you might find the help section useful, particularly the section on how to write a good question.
OK, lecture over.
What the question is asking about is how to use a simple for loop to add some numbers together:
function getProduct(num1, num2) {
// set total to zero
// we'll be adding to this number in the loop
var total = 0;
// i is the index, l is the number of times we
// iterate over the loop, in this case 8 (num2)
for (var i = 0, l = num2; i < l; i++) {
// for each loop iteration, add 5 to the total
total += num1;
}
// finally return the total
return total;
}
getProduct(5, 8); // 40

Categories