Expanding powers of expressions of the form ax+bJavaScript app to search GitHub using JSON APIString representation of a polynomialUnivariate polynomial multiplication using Doubly Linked ListChoosing a CSS class based on an HTTP status codeCalculating Garland Degree of StringFind deviations for a class in C# and present the values in a browser with TypeScript/JavaScriptFunction to map letters to numbersCalculate function with optional operator argument

Add 2 new columns to existing dataframe using apply

Limitations with dynamical systems vs. PDEs?

Nothing like a good ol' game of ModTen

How to check whether a sublist exist in a huge database lists in a fast way?

Prison offence - trespassing underwood fence

Tex Quotes(UVa 272)

How does the OS tell whether an "Address is already in use"?

Are game port joystick buttons ever more than plain switches? Is this one just faulty?

Movie where people enter a church but find they can't leave, not in English

Semantic difference between regular and irregular 'backen'

How can I download a file through 2 SSH connections?

Thought experiment and possible contradiction between electromagnetism and special relativity

Changing JPEG to RAW to use on Lightroom?

What does "rel" in `mathrel` and `stackrel` stands for?

What are the occurences of total war in the Native Americans?

Do Bayesian credible intervals treat the estimated parameter as a random variable?

Talk interpreter

Expressing the act of drawing

Redacting URLs as an email-phishing preventative?

How many lines of code does the original TeX contain?

How is linear momentum conserved in case of a freely falling body?

Heyacrazy: Empty Space

What to look for in a spotting scope?

What happened to the HDEV ISS Experiment? Is it over?



Expanding powers of expressions of the form ax+b


JavaScript app to search GitHub using JSON APIString representation of a polynomialUnivariate polynomial multiplication using Doubly Linked ListChoosing a CSS class based on an HTTP status codeCalculating Garland Degree of StringFind deviations for a class in C# and present the values in a browser with TypeScript/JavaScriptFunction to map letters to numbersCalculate function with optional operator argument






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


I solved the following problem:




Write a function expand that takes in an expresion with a single, one character variable, and expands it. The expresion is in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any one-character long variable, and n is a natural number. If a = 1, no coeficient will be placed in front of the variable. If a = -1, a "-" will be placed in front of the variable.
The expanded form should be returned as a string in the form ax^b+cx^d+ex^f... where a, c, and e are the coefficients of the term, x is the original one character variable that was passed in the original expression and b, d, and f, are the powers that x is being raised to in each term and are in decreasing order. If the coeficient of a term is zero, the term should not be included. If the coeficient of a term is one, the coeficient should not be included. If the coeficient of a term is -1, only the "-" should be included. If the power of the term is 0, only the coeficient should be included. If the power of the term is 1, the carrot and power should be excluded.




Examples:



expand("(p-1)^3"); // returns "p^3-3p^2+3p-1"
expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096"
expand("(-2a-4)^0"); // returns "1"
expand("(-12t+43)^2"); // returns "144t^2-1032t+1849"
expand("(r+0)^203"); // returns "r^203"
expand("(-x-1)^2"); // returns "x^2+2x+1"


My solution passed all tests but I would like to know how can it be improved.



function expand(str) 
const fac = n => n < 2 ? 1 : n * fac(n - 1);
let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);

a = a ? a == '-' ? -1 : parseInt(a) : 1;
b = parseInt(b); n = parseInt(n);

for (let i = n; i >= 0; i--)
let k = n - i;
let c = !b && k > 0
? 0
: a**i * b**k * (k == 0
? 1
: fac(n) / (fac(k) * fac(n - k)));

if (Math.abs(c) == 1 && i > 0) c = c > 0 ? '+' : '-';
else c = c > 0 ? `+$c` : c;
if (c) result += c;

if (i > 0 && c) result += x;
if (i > 1 && c) result += `^$i`;


return result[0] == '+' ? result.substr(1) : result;










share|improve this question









New contributor



haxor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$













  • $begingroup$
    "I solved the following problem:" how did you solve it? Code Review is for soliciting feedback on working code: we can't help you if you don't provide your code along with an explanation of how it came about.
    $endgroup$
    – VisualMelon
    8 hours ago










  • $begingroup$
    What's with all the single-letter variables? Did you obfuscate this on purpose or do you always write like this? Genuinely concerned.
    $endgroup$
    – Mast
    7 mins ago

















2












$begingroup$


I solved the following problem:




Write a function expand that takes in an expresion with a single, one character variable, and expands it. The expresion is in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any one-character long variable, and n is a natural number. If a = 1, no coeficient will be placed in front of the variable. If a = -1, a "-" will be placed in front of the variable.
The expanded form should be returned as a string in the form ax^b+cx^d+ex^f... where a, c, and e are the coefficients of the term, x is the original one character variable that was passed in the original expression and b, d, and f, are the powers that x is being raised to in each term and are in decreasing order. If the coeficient of a term is zero, the term should not be included. If the coeficient of a term is one, the coeficient should not be included. If the coeficient of a term is -1, only the "-" should be included. If the power of the term is 0, only the coeficient should be included. If the power of the term is 1, the carrot and power should be excluded.




Examples:



expand("(p-1)^3"); // returns "p^3-3p^2+3p-1"
expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096"
expand("(-2a-4)^0"); // returns "1"
expand("(-12t+43)^2"); // returns "144t^2-1032t+1849"
expand("(r+0)^203"); // returns "r^203"
expand("(-x-1)^2"); // returns "x^2+2x+1"


My solution passed all tests but I would like to know how can it be improved.



function expand(str) 
const fac = n => n < 2 ? 1 : n * fac(n - 1);
let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);

a = a ? a == '-' ? -1 : parseInt(a) : 1;
b = parseInt(b); n = parseInt(n);

for (let i = n; i >= 0; i--)
let k = n - i;
let c = !b && k > 0
? 0
: a**i * b**k * (k == 0
? 1
: fac(n) / (fac(k) * fac(n - k)));

if (Math.abs(c) == 1 && i > 0) c = c > 0 ? '+' : '-';
else c = c > 0 ? `+$c` : c;
if (c) result += c;

if (i > 0 && c) result += x;
if (i > 1 && c) result += `^$i`;


return result[0] == '+' ? result.substr(1) : result;










share|improve this question









New contributor



haxor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$













  • $begingroup$
    "I solved the following problem:" how did you solve it? Code Review is for soliciting feedback on working code: we can't help you if you don't provide your code along with an explanation of how it came about.
    $endgroup$
    – VisualMelon
    8 hours ago










  • $begingroup$
    What's with all the single-letter variables? Did you obfuscate this on purpose or do you always write like this? Genuinely concerned.
    $endgroup$
    – Mast
    7 mins ago













2












2








2





$begingroup$


I solved the following problem:




Write a function expand that takes in an expresion with a single, one character variable, and expands it. The expresion is in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any one-character long variable, and n is a natural number. If a = 1, no coeficient will be placed in front of the variable. If a = -1, a "-" will be placed in front of the variable.
The expanded form should be returned as a string in the form ax^b+cx^d+ex^f... where a, c, and e are the coefficients of the term, x is the original one character variable that was passed in the original expression and b, d, and f, are the powers that x is being raised to in each term and are in decreasing order. If the coeficient of a term is zero, the term should not be included. If the coeficient of a term is one, the coeficient should not be included. If the coeficient of a term is -1, only the "-" should be included. If the power of the term is 0, only the coeficient should be included. If the power of the term is 1, the carrot and power should be excluded.




Examples:



expand("(p-1)^3"); // returns "p^3-3p^2+3p-1"
expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096"
expand("(-2a-4)^0"); // returns "1"
expand("(-12t+43)^2"); // returns "144t^2-1032t+1849"
expand("(r+0)^203"); // returns "r^203"
expand("(-x-1)^2"); // returns "x^2+2x+1"


My solution passed all tests but I would like to know how can it be improved.



function expand(str) 
const fac = n => n < 2 ? 1 : n * fac(n - 1);
let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);

a = a ? a == '-' ? -1 : parseInt(a) : 1;
b = parseInt(b); n = parseInt(n);

for (let i = n; i >= 0; i--)
let k = n - i;
let c = !b && k > 0
? 0
: a**i * b**k * (k == 0
? 1
: fac(n) / (fac(k) * fac(n - k)));

if (Math.abs(c) == 1 && i > 0) c = c > 0 ? '+' : '-';
else c = c > 0 ? `+$c` : c;
if (c) result += c;

if (i > 0 && c) result += x;
if (i > 1 && c) result += `^$i`;


return result[0] == '+' ? result.substr(1) : result;










share|improve this question









New contributor



haxor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$




I solved the following problem:




Write a function expand that takes in an expresion with a single, one character variable, and expands it. The expresion is in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any one-character long variable, and n is a natural number. If a = 1, no coeficient will be placed in front of the variable. If a = -1, a "-" will be placed in front of the variable.
The expanded form should be returned as a string in the form ax^b+cx^d+ex^f... where a, c, and e are the coefficients of the term, x is the original one character variable that was passed in the original expression and b, d, and f, are the powers that x is being raised to in each term and are in decreasing order. If the coeficient of a term is zero, the term should not be included. If the coeficient of a term is one, the coeficient should not be included. If the coeficient of a term is -1, only the "-" should be included. If the power of the term is 0, only the coeficient should be included. If the power of the term is 1, the carrot and power should be excluded.




Examples:



expand("(p-1)^3"); // returns "p^3-3p^2+3p-1"
expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096"
expand("(-2a-4)^0"); // returns "1"
expand("(-12t+43)^2"); // returns "144t^2-1032t+1849"
expand("(r+0)^203"); // returns "r^203"
expand("(-x-1)^2"); // returns "x^2+2x+1"


My solution passed all tests but I would like to know how can it be improved.



function expand(str) 
const fac = n => n < 2 ? 1 : n * fac(n - 1);
let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);

a = a ? a == '-' ? -1 : parseInt(a) : 1;
b = parseInt(b); n = parseInt(n);

for (let i = n; i >= 0; i--)
let k = n - i;
let c = !b && k > 0
? 0
: a**i * b**k * (k == 0
? 1
: fac(n) / (fac(k) * fac(n - k)));

if (Math.abs(c) == 1 && i > 0) c = c > 0 ? '+' : '-';
else c = c > 0 ? `+$c` : c;
if (c) result += c;

if (i > 0 && c) result += x;
if (i > 1 && c) result += `^$i`;


return result[0] == '+' ? result.substr(1) : result;







javascript algorithm programming-challenge symbolic-math






share|improve this question









New contributor



haxor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



haxor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 48 mins ago









200_success

135k21 gold badges173 silver badges443 bronze badges




135k21 gold badges173 silver badges443 bronze badges






New contributor



haxor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 8 hours ago









haxorhaxor

162 bronze badges




162 bronze badges




New contributor



haxor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




haxor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • $begingroup$
    "I solved the following problem:" how did you solve it? Code Review is for soliciting feedback on working code: we can't help you if you don't provide your code along with an explanation of how it came about.
    $endgroup$
    – VisualMelon
    8 hours ago










  • $begingroup$
    What's with all the single-letter variables? Did you obfuscate this on purpose or do you always write like this? Genuinely concerned.
    $endgroup$
    – Mast
    7 mins ago
















  • $begingroup$
    "I solved the following problem:" how did you solve it? Code Review is for soliciting feedback on working code: we can't help you if you don't provide your code along with an explanation of how it came about.
    $endgroup$
    – VisualMelon
    8 hours ago










  • $begingroup$
    What's with all the single-letter variables? Did you obfuscate this on purpose or do you always write like this? Genuinely concerned.
    $endgroup$
    – Mast
    7 mins ago















$begingroup$
"I solved the following problem:" how did you solve it? Code Review is for soliciting feedback on working code: we can't help you if you don't provide your code along with an explanation of how it came about.
$endgroup$
– VisualMelon
8 hours ago




$begingroup$
"I solved the following problem:" how did you solve it? Code Review is for soliciting feedback on working code: we can't help you if you don't provide your code along with an explanation of how it came about.
$endgroup$
– VisualMelon
8 hours ago












$begingroup$
What's with all the single-letter variables? Did you obfuscate this on purpose or do you always write like this? Genuinely concerned.
$endgroup$
– Mast
7 mins ago




$begingroup$
What's with all the single-letter variables? Did you obfuscate this on purpose or do you always write like this? Genuinely concerned.
$endgroup$
– Mast
7 mins ago










2 Answers
2






active

oldest

votes


















2













$begingroup$

You don't need the special case for k == 0. When k == 0, the result of the other expression will be 1 as well.



For this sequence of binomial coefficients you don't need to calculate the full fak expression each time. You can also start with c = a ** i, and then, for each k, multiply by (n - k) / (k + 1). That's a bit faster and provides less risk of producing numeric overflows, which would result in slightly incorrect coefficients. The Wikipedia article on binomial coefficients should explain this in more detail.






share|improve this answer









$endgroup$






















    1













    $begingroup$

    Due to the lack of real context here (and issues I'll mention later), I can't really speak to the algorithm. I'll just focus on style.



    First, you need to take far greater care in creating meaningful names. This is incredibly hard to comprehend; and naming is the biggest contributor to the problem.



    Take a step back, pretend you didn't write this, and look at



    let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);


    What are a, x, b, and n? Because they're coming from a regex match, they aren't self-descriptive. You need to give them proper names so that people like me (and others reading your code) can know the intent of the variable at a glance without needed to dig through and "discover" what they're for. I can't give suggestions due to the lack of context, but any names would be better than the single-letters being used now.



    If the line gets long, split it up. Do the deconstruction on a second line if need-be.




    I'm not a fan of your use of nested ternaries here. A line like



    a = a ? a == '-' ? -1 : parseInt(a) : 1;


    is unfortunate and takes longer to comprehend than it should, but is still mostly legible. At the very least, I'd add some brackets in so the grouping is more obvious:



    a = a ? (a == '-' ? -1 : parseInt(a)) : 1;


    or maybe, split that off into a function (local or otherwise):



    function magnitude(a) 
    return a == '-' ? -1 : parseInt(a);


    . . .

    a = a ? magnitude(a) : 1;


    At least now the line is simplified, and there's a name associated with part of the operation (magnitude was a bad guess. You know the intent so you'll be able to come up with a better name).



    On the other hand though,



    let c = !b && k > 0
    ? 0
    : a**i * b**k * (k == 0
    ? 1
    : fac(n) / (fac(k) * fac(n - k)));


    is bad. You are attempting to cram far too much functionality into too small of a space. Between the lack of proper names and the density, this is very hard to comprehend. I would definitely split this up. Maybe split it over a couple lines (with descriptively-named variables holding intermediate results), or maybe even split some off into a function.



    Along the same theme, you also have lines like



    let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);

    b = parseInt(b); n = parseInt(n);


    There's little need to put them on the same line like this. I always advocate for declarations to be split over multiple lines in most cases (with the exception being maybe a simple destructuring).



    I would split these up:



    let [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);
    let result = "";

    let b = parseInt(b);
    let n = parseInt(n);




    Overall, I would encourage you to spend far more time practicing making your code readable. Practice putting yourself in the shoes of someone who has never seen your code before. This can be hard to do, but allows you to find your own readability problems. I would also like to emphasize that dense, packed, small code is not good in most scenarios. If code needs to be minified, it can be run through a minifier after the fact. Your base source should be readable so it can be maintained into the future.




    It was pointed out that a, x, b, and n are pulled directly from the question, so they're appropriate. If possible I still think they should have better names, but if those are the accepted names to be used in the math equation, or they're too arbitrary for proper names, then yes, they're fine. k and c though both seem like they're not directly related to the equation, so better name there would help.






    share|improve this answer











    $endgroup$










    • 1




      $begingroup$
      Most of the single-letter names come directly from the task, so there's nothing from with them.
      $endgroup$
      – Roland Illig
      7 hours ago













    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    haxor is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226797%2fexpanding-powers-of-expressions-of-the-form-axb%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2













    $begingroup$

    You don't need the special case for k == 0. When k == 0, the result of the other expression will be 1 as well.



    For this sequence of binomial coefficients you don't need to calculate the full fak expression each time. You can also start with c = a ** i, and then, for each k, multiply by (n - k) / (k + 1). That's a bit faster and provides less risk of producing numeric overflows, which would result in slightly incorrect coefficients. The Wikipedia article on binomial coefficients should explain this in more detail.






    share|improve this answer









    $endgroup$



















      2













      $begingroup$

      You don't need the special case for k == 0. When k == 0, the result of the other expression will be 1 as well.



      For this sequence of binomial coefficients you don't need to calculate the full fak expression each time. You can also start with c = a ** i, and then, for each k, multiply by (n - k) / (k + 1). That's a bit faster and provides less risk of producing numeric overflows, which would result in slightly incorrect coefficients. The Wikipedia article on binomial coefficients should explain this in more detail.






      share|improve this answer









      $endgroup$

















        2














        2










        2







        $begingroup$

        You don't need the special case for k == 0. When k == 0, the result of the other expression will be 1 as well.



        For this sequence of binomial coefficients you don't need to calculate the full fak expression each time. You can also start with c = a ** i, and then, for each k, multiply by (n - k) / (k + 1). That's a bit faster and provides less risk of producing numeric overflows, which would result in slightly incorrect coefficients. The Wikipedia article on binomial coefficients should explain this in more detail.






        share|improve this answer









        $endgroup$



        You don't need the special case for k == 0. When k == 0, the result of the other expression will be 1 as well.



        For this sequence of binomial coefficients you don't need to calculate the full fak expression each time. You can also start with c = a ** i, and then, for each k, multiply by (n - k) / (k + 1). That's a bit faster and provides less risk of producing numeric overflows, which would result in slightly incorrect coefficients. The Wikipedia article on binomial coefficients should explain this in more detail.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 7 hours ago









        Roland IlligRoland Illig

        14.9k2 gold badges24 silver badges56 bronze badges




        14.9k2 gold badges24 silver badges56 bronze badges


























            1













            $begingroup$

            Due to the lack of real context here (and issues I'll mention later), I can't really speak to the algorithm. I'll just focus on style.



            First, you need to take far greater care in creating meaningful names. This is incredibly hard to comprehend; and naming is the biggest contributor to the problem.



            Take a step back, pretend you didn't write this, and look at



            let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);


            What are a, x, b, and n? Because they're coming from a regex match, they aren't self-descriptive. You need to give them proper names so that people like me (and others reading your code) can know the intent of the variable at a glance without needed to dig through and "discover" what they're for. I can't give suggestions due to the lack of context, but any names would be better than the single-letters being used now.



            If the line gets long, split it up. Do the deconstruction on a second line if need-be.




            I'm not a fan of your use of nested ternaries here. A line like



            a = a ? a == '-' ? -1 : parseInt(a) : 1;


            is unfortunate and takes longer to comprehend than it should, but is still mostly legible. At the very least, I'd add some brackets in so the grouping is more obvious:



            a = a ? (a == '-' ? -1 : parseInt(a)) : 1;


            or maybe, split that off into a function (local or otherwise):



            function magnitude(a) 
            return a == '-' ? -1 : parseInt(a);


            . . .

            a = a ? magnitude(a) : 1;


            At least now the line is simplified, and there's a name associated with part of the operation (magnitude was a bad guess. You know the intent so you'll be able to come up with a better name).



            On the other hand though,



            let c = !b && k > 0
            ? 0
            : a**i * b**k * (k == 0
            ? 1
            : fac(n) / (fac(k) * fac(n - k)));


            is bad. You are attempting to cram far too much functionality into too small of a space. Between the lack of proper names and the density, this is very hard to comprehend. I would definitely split this up. Maybe split it over a couple lines (with descriptively-named variables holding intermediate results), or maybe even split some off into a function.



            Along the same theme, you also have lines like



            let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);

            b = parseInt(b); n = parseInt(n);


            There's little need to put them on the same line like this. I always advocate for declarations to be split over multiple lines in most cases (with the exception being maybe a simple destructuring).



            I would split these up:



            let [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);
            let result = "";

            let b = parseInt(b);
            let n = parseInt(n);




            Overall, I would encourage you to spend far more time practicing making your code readable. Practice putting yourself in the shoes of someone who has never seen your code before. This can be hard to do, but allows you to find your own readability problems. I would also like to emphasize that dense, packed, small code is not good in most scenarios. If code needs to be minified, it can be run through a minifier after the fact. Your base source should be readable so it can be maintained into the future.




            It was pointed out that a, x, b, and n are pulled directly from the question, so they're appropriate. If possible I still think they should have better names, but if those are the accepted names to be used in the math equation, or they're too arbitrary for proper names, then yes, they're fine. k and c though both seem like they're not directly related to the equation, so better name there would help.






            share|improve this answer











            $endgroup$










            • 1




              $begingroup$
              Most of the single-letter names come directly from the task, so there's nothing from with them.
              $endgroup$
              – Roland Illig
              7 hours ago















            1













            $begingroup$

            Due to the lack of real context here (and issues I'll mention later), I can't really speak to the algorithm. I'll just focus on style.



            First, you need to take far greater care in creating meaningful names. This is incredibly hard to comprehend; and naming is the biggest contributor to the problem.



            Take a step back, pretend you didn't write this, and look at



            let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);


            What are a, x, b, and n? Because they're coming from a regex match, they aren't self-descriptive. You need to give them proper names so that people like me (and others reading your code) can know the intent of the variable at a glance without needed to dig through and "discover" what they're for. I can't give suggestions due to the lack of context, but any names would be better than the single-letters being used now.



            If the line gets long, split it up. Do the deconstruction on a second line if need-be.




            I'm not a fan of your use of nested ternaries here. A line like



            a = a ? a == '-' ? -1 : parseInt(a) : 1;


            is unfortunate and takes longer to comprehend than it should, but is still mostly legible. At the very least, I'd add some brackets in so the grouping is more obvious:



            a = a ? (a == '-' ? -1 : parseInt(a)) : 1;


            or maybe, split that off into a function (local or otherwise):



            function magnitude(a) 
            return a == '-' ? -1 : parseInt(a);


            . . .

            a = a ? magnitude(a) : 1;


            At least now the line is simplified, and there's a name associated with part of the operation (magnitude was a bad guess. You know the intent so you'll be able to come up with a better name).



            On the other hand though,



            let c = !b && k > 0
            ? 0
            : a**i * b**k * (k == 0
            ? 1
            : fac(n) / (fac(k) * fac(n - k)));


            is bad. You are attempting to cram far too much functionality into too small of a space. Between the lack of proper names and the density, this is very hard to comprehend. I would definitely split this up. Maybe split it over a couple lines (with descriptively-named variables holding intermediate results), or maybe even split some off into a function.



            Along the same theme, you also have lines like



            let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);

            b = parseInt(b); n = parseInt(n);


            There's little need to put them on the same line like this. I always advocate for declarations to be split over multiple lines in most cases (with the exception being maybe a simple destructuring).



            I would split these up:



            let [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);
            let result = "";

            let b = parseInt(b);
            let n = parseInt(n);




            Overall, I would encourage you to spend far more time practicing making your code readable. Practice putting yourself in the shoes of someone who has never seen your code before. This can be hard to do, but allows you to find your own readability problems. I would also like to emphasize that dense, packed, small code is not good in most scenarios. If code needs to be minified, it can be run through a minifier after the fact. Your base source should be readable so it can be maintained into the future.




            It was pointed out that a, x, b, and n are pulled directly from the question, so they're appropriate. If possible I still think they should have better names, but if those are the accepted names to be used in the math equation, or they're too arbitrary for proper names, then yes, they're fine. k and c though both seem like they're not directly related to the equation, so better name there would help.






            share|improve this answer











            $endgroup$










            • 1




              $begingroup$
              Most of the single-letter names come directly from the task, so there's nothing from with them.
              $endgroup$
              – Roland Illig
              7 hours ago













            1














            1










            1







            $begingroup$

            Due to the lack of real context here (and issues I'll mention later), I can't really speak to the algorithm. I'll just focus on style.



            First, you need to take far greater care in creating meaningful names. This is incredibly hard to comprehend; and naming is the biggest contributor to the problem.



            Take a step back, pretend you didn't write this, and look at



            let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);


            What are a, x, b, and n? Because they're coming from a regex match, they aren't self-descriptive. You need to give them proper names so that people like me (and others reading your code) can know the intent of the variable at a glance without needed to dig through and "discover" what they're for. I can't give suggestions due to the lack of context, but any names would be better than the single-letters being used now.



            If the line gets long, split it up. Do the deconstruction on a second line if need-be.




            I'm not a fan of your use of nested ternaries here. A line like



            a = a ? a == '-' ? -1 : parseInt(a) : 1;


            is unfortunate and takes longer to comprehend than it should, but is still mostly legible. At the very least, I'd add some brackets in so the grouping is more obvious:



            a = a ? (a == '-' ? -1 : parseInt(a)) : 1;


            or maybe, split that off into a function (local or otherwise):



            function magnitude(a) 
            return a == '-' ? -1 : parseInt(a);


            . . .

            a = a ? magnitude(a) : 1;


            At least now the line is simplified, and there's a name associated with part of the operation (magnitude was a bad guess. You know the intent so you'll be able to come up with a better name).



            On the other hand though,



            let c = !b && k > 0
            ? 0
            : a**i * b**k * (k == 0
            ? 1
            : fac(n) / (fac(k) * fac(n - k)));


            is bad. You are attempting to cram far too much functionality into too small of a space. Between the lack of proper names and the density, this is very hard to comprehend. I would definitely split this up. Maybe split it over a couple lines (with descriptively-named variables holding intermediate results), or maybe even split some off into a function.



            Along the same theme, you also have lines like



            let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);

            b = parseInt(b); n = parseInt(n);


            There's little need to put them on the same line like this. I always advocate for declarations to be split over multiple lines in most cases (with the exception being maybe a simple destructuring).



            I would split these up:



            let [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);
            let result = "";

            let b = parseInt(b);
            let n = parseInt(n);




            Overall, I would encourage you to spend far more time practicing making your code readable. Practice putting yourself in the shoes of someone who has never seen your code before. This can be hard to do, but allows you to find your own readability problems. I would also like to emphasize that dense, packed, small code is not good in most scenarios. If code needs to be minified, it can be run through a minifier after the fact. Your base source should be readable so it can be maintained into the future.




            It was pointed out that a, x, b, and n are pulled directly from the question, so they're appropriate. If possible I still think they should have better names, but if those are the accepted names to be used in the math equation, or they're too arbitrary for proper names, then yes, they're fine. k and c though both seem like they're not directly related to the equation, so better name there would help.






            share|improve this answer











            $endgroup$



            Due to the lack of real context here (and issues I'll mention later), I can't really speak to the algorithm. I'll just focus on style.



            First, you need to take far greater care in creating meaningful names. This is incredibly hard to comprehend; and naming is the biggest contributor to the problem.



            Take a step back, pretend you didn't write this, and look at



            let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);


            What are a, x, b, and n? Because they're coming from a regex match, they aren't self-descriptive. You need to give them proper names so that people like me (and others reading your code) can know the intent of the variable at a glance without needed to dig through and "discover" what they're for. I can't give suggestions due to the lack of context, but any names would be better than the single-letters being used now.



            If the line gets long, split it up. Do the deconstruction on a second line if need-be.




            I'm not a fan of your use of nested ternaries here. A line like



            a = a ? a == '-' ? -1 : parseInt(a) : 1;


            is unfortunate and takes longer to comprehend than it should, but is still mostly legible. At the very least, I'd add some brackets in so the grouping is more obvious:



            a = a ? (a == '-' ? -1 : parseInt(a)) : 1;


            or maybe, split that off into a function (local or otherwise):



            function magnitude(a) 
            return a == '-' ? -1 : parseInt(a);


            . . .

            a = a ? magnitude(a) : 1;


            At least now the line is simplified, and there's a name associated with part of the operation (magnitude was a bad guess. You know the intent so you'll be able to come up with a better name).



            On the other hand though,



            let c = !b && k > 0
            ? 0
            : a**i * b**k * (k == 0
            ? 1
            : fac(n) / (fac(k) * fac(n - k)));


            is bad. You are attempting to cram far too much functionality into too small of a space. Between the lack of proper names and the density, this is very hard to comprehend. I would definitely split this up. Maybe split it over a couple lines (with descriptively-named variables holding intermediate results), or maybe even split some off into a function.



            Along the same theme, you also have lines like



            let result = '', [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);

            b = parseInt(b); n = parseInt(n);


            There's little need to put them on the same line like this. I always advocate for declarations to be split over multiple lines in most cases (with the exception being maybe a simple destructuring).



            I would split these up:



            let [_, a, x, b, n] = str.match(/((-?d*)([a-z])([-+]d+))^(d+)/);
            let result = "";

            let b = parseInt(b);
            let n = parseInt(n);




            Overall, I would encourage you to spend far more time practicing making your code readable. Practice putting yourself in the shoes of someone who has never seen your code before. This can be hard to do, but allows you to find your own readability problems. I would also like to emphasize that dense, packed, small code is not good in most scenarios. If code needs to be minified, it can be run through a minifier after the fact. Your base source should be readable so it can be maintained into the future.




            It was pointed out that a, x, b, and n are pulled directly from the question, so they're appropriate. If possible I still think they should have better names, but if those are the accepted names to be used in the math equation, or they're too arbitrary for proper names, then yes, they're fine. k and c though both seem like they're not directly related to the equation, so better name there would help.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 7 hours ago

























            answered 7 hours ago









            CarcigenicateCarcigenicate

            6,0971 gold badge18 silver badges40 bronze badges




            6,0971 gold badge18 silver badges40 bronze badges










            • 1




              $begingroup$
              Most of the single-letter names come directly from the task, so there's nothing from with them.
              $endgroup$
              – Roland Illig
              7 hours ago












            • 1




              $begingroup$
              Most of the single-letter names come directly from the task, so there's nothing from with them.
              $endgroup$
              – Roland Illig
              7 hours ago







            1




            1




            $begingroup$
            Most of the single-letter names come directly from the task, so there's nothing from with them.
            $endgroup$
            – Roland Illig
            7 hours ago




            $begingroup$
            Most of the single-letter names come directly from the task, so there's nothing from with them.
            $endgroup$
            – Roland Illig
            7 hours ago










            haxor is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            haxor is a new contributor. Be nice, and check out our Code of Conduct.












            haxor is a new contributor. Be nice, and check out our Code of Conduct.











            haxor is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226797%2fexpanding-powers-of-expressions-of-the-form-axb%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її