JavaScript function to be create to calculate Price based on some info (example - store offers)












0















I have an array [2,5,1]$ which is prices, Customer pays 2$ for the first item because no discount for first item,
5-2 = 3 for the second item,
min(1st item, 2nd item) min(2,5) = 2 for 3rd Item; but if next item is lesser in cost compared to second item e.g. 1 is less 2 the cost will be zero;



so 2+3+0 is output of calculate price.


If i have one more input



[2,5,1,6]
2 + (5-2) + 0 + (6 - min(2,5,1))


How I can achieve this -



I was trying to write something like this -



function calculateAmount(prices) {
// Write your code here
var totalCostPurchase;
var cost = ;
var zero = 0;
for (var i = 0; i < prices.length; i++) {
if (i === 0) {
cost.push(prices[i]);
} else if (i === 1) {
cost.push(prices[i] - cost[i - 1]);
} else {
var minCost = Math.min(...prices.slice(0,i));
console.log(minCost);
if (minCost > prices[i]) {
cost.push(zero);
} else {
cost.push(prices[i] - minCost);
}
}
}
totalCostPurchase = cost.reduce((a, b) => a + b, 0);
console.log(totalCostPurchase);
return totalCostPurchase;
}

Please guide.









share|improve this question




















  • 1





    Please write the formula. Why the 3th item is 0, it should be 1 (2 - 1), no?

    – Chayim Friedman
    Nov 25 '18 at 6:47











  • Agreed-- a clearer understanding of what the input data represents and your requirements would probably help you get a meaningful answer more quickly.

    – Alexander Nied
    Nov 25 '18 at 6:49











  • Will the array size increase? If you've some pattern over calculation of every item, you can write recursive function and will be easier to understand.

    – Abhishek
    Nov 25 '18 at 6:52











  • yes, array size will increae, my function works for upto 4 but not working for 10 items

    – Javascript Coder
    Nov 25 '18 at 6:54
















0















I have an array [2,5,1]$ which is prices, Customer pays 2$ for the first item because no discount for first item,
5-2 = 3 for the second item,
min(1st item, 2nd item) min(2,5) = 2 for 3rd Item; but if next item is lesser in cost compared to second item e.g. 1 is less 2 the cost will be zero;



so 2+3+0 is output of calculate price.


If i have one more input



[2,5,1,6]
2 + (5-2) + 0 + (6 - min(2,5,1))


How I can achieve this -



I was trying to write something like this -



function calculateAmount(prices) {
// Write your code here
var totalCostPurchase;
var cost = ;
var zero = 0;
for (var i = 0; i < prices.length; i++) {
if (i === 0) {
cost.push(prices[i]);
} else if (i === 1) {
cost.push(prices[i] - cost[i - 1]);
} else {
var minCost = Math.min(...prices.slice(0,i));
console.log(minCost);
if (minCost > prices[i]) {
cost.push(zero);
} else {
cost.push(prices[i] - minCost);
}
}
}
totalCostPurchase = cost.reduce((a, b) => a + b, 0);
console.log(totalCostPurchase);
return totalCostPurchase;
}

Please guide.









share|improve this question




















  • 1





    Please write the formula. Why the 3th item is 0, it should be 1 (2 - 1), no?

    – Chayim Friedman
    Nov 25 '18 at 6:47











  • Agreed-- a clearer understanding of what the input data represents and your requirements would probably help you get a meaningful answer more quickly.

    – Alexander Nied
    Nov 25 '18 at 6:49











  • Will the array size increase? If you've some pattern over calculation of every item, you can write recursive function and will be easier to understand.

    – Abhishek
    Nov 25 '18 at 6:52











  • yes, array size will increae, my function works for upto 4 but not working for 10 items

    – Javascript Coder
    Nov 25 '18 at 6:54














0












0








0








I have an array [2,5,1]$ which is prices, Customer pays 2$ for the first item because no discount for first item,
5-2 = 3 for the second item,
min(1st item, 2nd item) min(2,5) = 2 for 3rd Item; but if next item is lesser in cost compared to second item e.g. 1 is less 2 the cost will be zero;



so 2+3+0 is output of calculate price.


If i have one more input



[2,5,1,6]
2 + (5-2) + 0 + (6 - min(2,5,1))


How I can achieve this -



I was trying to write something like this -



function calculateAmount(prices) {
// Write your code here
var totalCostPurchase;
var cost = ;
var zero = 0;
for (var i = 0; i < prices.length; i++) {
if (i === 0) {
cost.push(prices[i]);
} else if (i === 1) {
cost.push(prices[i] - cost[i - 1]);
} else {
var minCost = Math.min(...prices.slice(0,i));
console.log(minCost);
if (minCost > prices[i]) {
cost.push(zero);
} else {
cost.push(prices[i] - minCost);
}
}
}
totalCostPurchase = cost.reduce((a, b) => a + b, 0);
console.log(totalCostPurchase);
return totalCostPurchase;
}

Please guide.









share|improve this question
















I have an array [2,5,1]$ which is prices, Customer pays 2$ for the first item because no discount for first item,
5-2 = 3 for the second item,
min(1st item, 2nd item) min(2,5) = 2 for 3rd Item; but if next item is lesser in cost compared to second item e.g. 1 is less 2 the cost will be zero;



so 2+3+0 is output of calculate price.


If i have one more input



[2,5,1,6]
2 + (5-2) + 0 + (6 - min(2,5,1))


How I can achieve this -



I was trying to write something like this -



function calculateAmount(prices) {
// Write your code here
var totalCostPurchase;
var cost = ;
var zero = 0;
for (var i = 0; i < prices.length; i++) {
if (i === 0) {
cost.push(prices[i]);
} else if (i === 1) {
cost.push(prices[i] - cost[i - 1]);
} else {
var minCost = Math.min(...prices.slice(0,i));
console.log(minCost);
if (minCost > prices[i]) {
cost.push(zero);
} else {
cost.push(prices[i] - minCost);
}
}
}
totalCostPurchase = cost.reduce((a, b) => a + b, 0);
console.log(totalCostPurchase);
return totalCostPurchase;
}

Please guide.






javascript arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 7:31







Javascript Coder

















asked Nov 25 '18 at 6:36









Javascript CoderJavascript Coder

3,41053059




3,41053059








  • 1





    Please write the formula. Why the 3th item is 0, it should be 1 (2 - 1), no?

    – Chayim Friedman
    Nov 25 '18 at 6:47











  • Agreed-- a clearer understanding of what the input data represents and your requirements would probably help you get a meaningful answer more quickly.

    – Alexander Nied
    Nov 25 '18 at 6:49











  • Will the array size increase? If you've some pattern over calculation of every item, you can write recursive function and will be easier to understand.

    – Abhishek
    Nov 25 '18 at 6:52











  • yes, array size will increae, my function works for upto 4 but not working for 10 items

    – Javascript Coder
    Nov 25 '18 at 6:54














  • 1





    Please write the formula. Why the 3th item is 0, it should be 1 (2 - 1), no?

    – Chayim Friedman
    Nov 25 '18 at 6:47











  • Agreed-- a clearer understanding of what the input data represents and your requirements would probably help you get a meaningful answer more quickly.

    – Alexander Nied
    Nov 25 '18 at 6:49











  • Will the array size increase? If you've some pattern over calculation of every item, you can write recursive function and will be easier to understand.

    – Abhishek
    Nov 25 '18 at 6:52











  • yes, array size will increae, my function works for upto 4 but not working for 10 items

    – Javascript Coder
    Nov 25 '18 at 6:54








1




1





Please write the formula. Why the 3th item is 0, it should be 1 (2 - 1), no?

– Chayim Friedman
Nov 25 '18 at 6:47





Please write the formula. Why the 3th item is 0, it should be 1 (2 - 1), no?

– Chayim Friedman
Nov 25 '18 at 6:47













Agreed-- a clearer understanding of what the input data represents and your requirements would probably help you get a meaningful answer more quickly.

– Alexander Nied
Nov 25 '18 at 6:49





Agreed-- a clearer understanding of what the input data represents and your requirements would probably help you get a meaningful answer more quickly.

– Alexander Nied
Nov 25 '18 at 6:49













Will the array size increase? If you've some pattern over calculation of every item, you can write recursive function and will be easier to understand.

– Abhishek
Nov 25 '18 at 6:52





Will the array size increase? If you've some pattern over calculation of every item, you can write recursive function and will be easier to understand.

– Abhishek
Nov 25 '18 at 6:52













yes, array size will increae, my function works for upto 4 but not working for 10 items

– Javascript Coder
Nov 25 '18 at 6:54





yes, array size will increae, my function works for upto 4 but not working for 10 items

– Javascript Coder
Nov 25 '18 at 6:54












3 Answers
3






active

oldest

votes


















1














You can use Array.map and Array.reduce for this






var a = [2,5,1,6]

let res = a.map((d,i) => i != 0
? d - Math.min(...a.slice(0, i+1))
: d)
.reduce((x, y) => x + y)


console.log(res)








share|improve this answer
























  • Nice. However, this has O(n^2) time complexity.

    – slider
    Nov 25 '18 at 7:13











  • Hi @slider. Nice to e meet you again.. No it does not have O(n^2).. Its rather O(2n) .... no ?

    – Nitish Narang
    Nov 25 '18 at 7:14











  • It's clearly O(n^2) because you compute the minimum using Math.min(...a.slice(0, i+1)) for each element.

    – slider
    Nov 25 '18 at 7:16








  • 1





    hmmm.. i see but i think it's less than n^2, i am not sure how to calculate it exactly.. neverthless if array length is not in hundreds/thousands then difference is hardly noticeble :) Btw good point @slider It's a good learning experience answering with you...

    – Nitish Narang
    Nov 25 '18 at 7:20



















1














You can use reduce where the accumulator keeps track of the sum and min and updates based on your rules:






function total(prices) {
return prices.reduce(([sum, min], p, i) => {
if (i === 0) return [p, p];
let newSum = sum;
if (p >= min) newSum += p - min;
return [newSum, Math.min(p, min)];
}, )[0];
}


console.log(total([2, 5, 1]));
console.log(total([2, 5, 1, 6]));








share|improve this answer































    0














    I tried the answer, And this seems to work for all the cases, this may not be best solution but this is what i think through.



    function calculateAmount(prices) {
    // Write your code here
    var totalCostPurchase;
    var cost = ;
    var zero = 0;
    for (var i = 0; i < prices.length; i++) {
    if (i === 0) {
    cost.push(prices[i]);
    } else if (i === 1) {
    if ((prices[i] - cost[i - 1]) < 0) {
    cost.push(zero);
    } else {
    cost.push(prices[i] - cost[i - 1]);
    }
    } else {
    var minCost = Math.min(...prices.slice(0,i));
    if (minCost > prices[i]) {
    cost.push(zero);
    } else {
    if ((prices[i] - minCost) < 0) {
    cost.push(zero);
    } else {
    cost.push(prices[i] - minCost);
    }
    }
    }
    }
    totalCostPurchase = cost.reduce((a, b) => a + b, 0);
    return totalCostPurchase;
    }





    share|improve this answer
























    • I will try to reduce the code and will try to clean up.

      – Javascript Coder
      Nov 25 '18 at 7:11











    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: "1"
    };
    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: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    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
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465237%2fjavascript-function-to-be-create-to-calculate-price-based-on-some-info-example%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You can use Array.map and Array.reduce for this






    var a = [2,5,1,6]

    let res = a.map((d,i) => i != 0
    ? d - Math.min(...a.slice(0, i+1))
    : d)
    .reduce((x, y) => x + y)


    console.log(res)








    share|improve this answer
























    • Nice. However, this has O(n^2) time complexity.

      – slider
      Nov 25 '18 at 7:13











    • Hi @slider. Nice to e meet you again.. No it does not have O(n^2).. Its rather O(2n) .... no ?

      – Nitish Narang
      Nov 25 '18 at 7:14











    • It's clearly O(n^2) because you compute the minimum using Math.min(...a.slice(0, i+1)) for each element.

      – slider
      Nov 25 '18 at 7:16








    • 1





      hmmm.. i see but i think it's less than n^2, i am not sure how to calculate it exactly.. neverthless if array length is not in hundreds/thousands then difference is hardly noticeble :) Btw good point @slider It's a good learning experience answering with you...

      – Nitish Narang
      Nov 25 '18 at 7:20
















    1














    You can use Array.map and Array.reduce for this






    var a = [2,5,1,6]

    let res = a.map((d,i) => i != 0
    ? d - Math.min(...a.slice(0, i+1))
    : d)
    .reduce((x, y) => x + y)


    console.log(res)








    share|improve this answer
























    • Nice. However, this has O(n^2) time complexity.

      – slider
      Nov 25 '18 at 7:13











    • Hi @slider. Nice to e meet you again.. No it does not have O(n^2).. Its rather O(2n) .... no ?

      – Nitish Narang
      Nov 25 '18 at 7:14











    • It's clearly O(n^2) because you compute the minimum using Math.min(...a.slice(0, i+1)) for each element.

      – slider
      Nov 25 '18 at 7:16








    • 1





      hmmm.. i see but i think it's less than n^2, i am not sure how to calculate it exactly.. neverthless if array length is not in hundreds/thousands then difference is hardly noticeble :) Btw good point @slider It's a good learning experience answering with you...

      – Nitish Narang
      Nov 25 '18 at 7:20














    1












    1








    1







    You can use Array.map and Array.reduce for this






    var a = [2,5,1,6]

    let res = a.map((d,i) => i != 0
    ? d - Math.min(...a.slice(0, i+1))
    : d)
    .reduce((x, y) => x + y)


    console.log(res)








    share|improve this answer













    You can use Array.map and Array.reduce for this






    var a = [2,5,1,6]

    let res = a.map((d,i) => i != 0
    ? d - Math.min(...a.slice(0, i+1))
    : d)
    .reduce((x, y) => x + y)


    console.log(res)








    var a = [2,5,1,6]

    let res = a.map((d,i) => i != 0
    ? d - Math.min(...a.slice(0, i+1))
    : d)
    .reduce((x, y) => x + y)


    console.log(res)





    var a = [2,5,1,6]

    let res = a.map((d,i) => i != 0
    ? d - Math.min(...a.slice(0, i+1))
    : d)
    .reduce((x, y) => x + y)


    console.log(res)






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 25 '18 at 7:11









    Nitish NarangNitish Narang

    2,9601815




    2,9601815













    • Nice. However, this has O(n^2) time complexity.

      – slider
      Nov 25 '18 at 7:13











    • Hi @slider. Nice to e meet you again.. No it does not have O(n^2).. Its rather O(2n) .... no ?

      – Nitish Narang
      Nov 25 '18 at 7:14











    • It's clearly O(n^2) because you compute the minimum using Math.min(...a.slice(0, i+1)) for each element.

      – slider
      Nov 25 '18 at 7:16








    • 1





      hmmm.. i see but i think it's less than n^2, i am not sure how to calculate it exactly.. neverthless if array length is not in hundreds/thousands then difference is hardly noticeble :) Btw good point @slider It's a good learning experience answering with you...

      – Nitish Narang
      Nov 25 '18 at 7:20



















    • Nice. However, this has O(n^2) time complexity.

      – slider
      Nov 25 '18 at 7:13











    • Hi @slider. Nice to e meet you again.. No it does not have O(n^2).. Its rather O(2n) .... no ?

      – Nitish Narang
      Nov 25 '18 at 7:14











    • It's clearly O(n^2) because you compute the minimum using Math.min(...a.slice(0, i+1)) for each element.

      – slider
      Nov 25 '18 at 7:16








    • 1





      hmmm.. i see but i think it's less than n^2, i am not sure how to calculate it exactly.. neverthless if array length is not in hundreds/thousands then difference is hardly noticeble :) Btw good point @slider It's a good learning experience answering with you...

      – Nitish Narang
      Nov 25 '18 at 7:20

















    Nice. However, this has O(n^2) time complexity.

    – slider
    Nov 25 '18 at 7:13





    Nice. However, this has O(n^2) time complexity.

    – slider
    Nov 25 '18 at 7:13













    Hi @slider. Nice to e meet you again.. No it does not have O(n^2).. Its rather O(2n) .... no ?

    – Nitish Narang
    Nov 25 '18 at 7:14





    Hi @slider. Nice to e meet you again.. No it does not have O(n^2).. Its rather O(2n) .... no ?

    – Nitish Narang
    Nov 25 '18 at 7:14













    It's clearly O(n^2) because you compute the minimum using Math.min(...a.slice(0, i+1)) for each element.

    – slider
    Nov 25 '18 at 7:16







    It's clearly O(n^2) because you compute the minimum using Math.min(...a.slice(0, i+1)) for each element.

    – slider
    Nov 25 '18 at 7:16






    1




    1





    hmmm.. i see but i think it's less than n^2, i am not sure how to calculate it exactly.. neverthless if array length is not in hundreds/thousands then difference is hardly noticeble :) Btw good point @slider It's a good learning experience answering with you...

    – Nitish Narang
    Nov 25 '18 at 7:20





    hmmm.. i see but i think it's less than n^2, i am not sure how to calculate it exactly.. neverthless if array length is not in hundreds/thousands then difference is hardly noticeble :) Btw good point @slider It's a good learning experience answering with you...

    – Nitish Narang
    Nov 25 '18 at 7:20













    1














    You can use reduce where the accumulator keeps track of the sum and min and updates based on your rules:






    function total(prices) {
    return prices.reduce(([sum, min], p, i) => {
    if (i === 0) return [p, p];
    let newSum = sum;
    if (p >= min) newSum += p - min;
    return [newSum, Math.min(p, min)];
    }, )[0];
    }


    console.log(total([2, 5, 1]));
    console.log(total([2, 5, 1, 6]));








    share|improve this answer




























      1














      You can use reduce where the accumulator keeps track of the sum and min and updates based on your rules:






      function total(prices) {
      return prices.reduce(([sum, min], p, i) => {
      if (i === 0) return [p, p];
      let newSum = sum;
      if (p >= min) newSum += p - min;
      return [newSum, Math.min(p, min)];
      }, )[0];
      }


      console.log(total([2, 5, 1]));
      console.log(total([2, 5, 1, 6]));








      share|improve this answer


























        1












        1








        1







        You can use reduce where the accumulator keeps track of the sum and min and updates based on your rules:






        function total(prices) {
        return prices.reduce(([sum, min], p, i) => {
        if (i === 0) return [p, p];
        let newSum = sum;
        if (p >= min) newSum += p - min;
        return [newSum, Math.min(p, min)];
        }, )[0];
        }


        console.log(total([2, 5, 1]));
        console.log(total([2, 5, 1, 6]));








        share|improve this answer













        You can use reduce where the accumulator keeps track of the sum and min and updates based on your rules:






        function total(prices) {
        return prices.reduce(([sum, min], p, i) => {
        if (i === 0) return [p, p];
        let newSum = sum;
        if (p >= min) newSum += p - min;
        return [newSum, Math.min(p, min)];
        }, )[0];
        }


        console.log(total([2, 5, 1]));
        console.log(total([2, 5, 1, 6]));








        function total(prices) {
        return prices.reduce(([sum, min], p, i) => {
        if (i === 0) return [p, p];
        let newSum = sum;
        if (p >= min) newSum += p - min;
        return [newSum, Math.min(p, min)];
        }, )[0];
        }


        console.log(total([2, 5, 1]));
        console.log(total([2, 5, 1, 6]));





        function total(prices) {
        return prices.reduce(([sum, min], p, i) => {
        if (i === 0) return [p, p];
        let newSum = sum;
        if (p >= min) newSum += p - min;
        return [newSum, Math.min(p, min)];
        }, )[0];
        }


        console.log(total([2, 5, 1]));
        console.log(total([2, 5, 1, 6]));






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 25 '18 at 6:59









        sliderslider

        8,47311231




        8,47311231























            0














            I tried the answer, And this seems to work for all the cases, this may not be best solution but this is what i think through.



            function calculateAmount(prices) {
            // Write your code here
            var totalCostPurchase;
            var cost = ;
            var zero = 0;
            for (var i = 0; i < prices.length; i++) {
            if (i === 0) {
            cost.push(prices[i]);
            } else if (i === 1) {
            if ((prices[i] - cost[i - 1]) < 0) {
            cost.push(zero);
            } else {
            cost.push(prices[i] - cost[i - 1]);
            }
            } else {
            var minCost = Math.min(...prices.slice(0,i));
            if (minCost > prices[i]) {
            cost.push(zero);
            } else {
            if ((prices[i] - minCost) < 0) {
            cost.push(zero);
            } else {
            cost.push(prices[i] - minCost);
            }
            }
            }
            }
            totalCostPurchase = cost.reduce((a, b) => a + b, 0);
            return totalCostPurchase;
            }





            share|improve this answer
























            • I will try to reduce the code and will try to clean up.

              – Javascript Coder
              Nov 25 '18 at 7:11
















            0














            I tried the answer, And this seems to work for all the cases, this may not be best solution but this is what i think through.



            function calculateAmount(prices) {
            // Write your code here
            var totalCostPurchase;
            var cost = ;
            var zero = 0;
            for (var i = 0; i < prices.length; i++) {
            if (i === 0) {
            cost.push(prices[i]);
            } else if (i === 1) {
            if ((prices[i] - cost[i - 1]) < 0) {
            cost.push(zero);
            } else {
            cost.push(prices[i] - cost[i - 1]);
            }
            } else {
            var minCost = Math.min(...prices.slice(0,i));
            if (minCost > prices[i]) {
            cost.push(zero);
            } else {
            if ((prices[i] - minCost) < 0) {
            cost.push(zero);
            } else {
            cost.push(prices[i] - minCost);
            }
            }
            }
            }
            totalCostPurchase = cost.reduce((a, b) => a + b, 0);
            return totalCostPurchase;
            }





            share|improve this answer
























            • I will try to reduce the code and will try to clean up.

              – Javascript Coder
              Nov 25 '18 at 7:11














            0












            0








            0







            I tried the answer, And this seems to work for all the cases, this may not be best solution but this is what i think through.



            function calculateAmount(prices) {
            // Write your code here
            var totalCostPurchase;
            var cost = ;
            var zero = 0;
            for (var i = 0; i < prices.length; i++) {
            if (i === 0) {
            cost.push(prices[i]);
            } else if (i === 1) {
            if ((prices[i] - cost[i - 1]) < 0) {
            cost.push(zero);
            } else {
            cost.push(prices[i] - cost[i - 1]);
            }
            } else {
            var minCost = Math.min(...prices.slice(0,i));
            if (minCost > prices[i]) {
            cost.push(zero);
            } else {
            if ((prices[i] - minCost) < 0) {
            cost.push(zero);
            } else {
            cost.push(prices[i] - minCost);
            }
            }
            }
            }
            totalCostPurchase = cost.reduce((a, b) => a + b, 0);
            return totalCostPurchase;
            }





            share|improve this answer













            I tried the answer, And this seems to work for all the cases, this may not be best solution but this is what i think through.



            function calculateAmount(prices) {
            // Write your code here
            var totalCostPurchase;
            var cost = ;
            var zero = 0;
            for (var i = 0; i < prices.length; i++) {
            if (i === 0) {
            cost.push(prices[i]);
            } else if (i === 1) {
            if ((prices[i] - cost[i - 1]) < 0) {
            cost.push(zero);
            } else {
            cost.push(prices[i] - cost[i - 1]);
            }
            } else {
            var minCost = Math.min(...prices.slice(0,i));
            if (minCost > prices[i]) {
            cost.push(zero);
            } else {
            if ((prices[i] - minCost) < 0) {
            cost.push(zero);
            } else {
            cost.push(prices[i] - minCost);
            }
            }
            }
            }
            totalCostPurchase = cost.reduce((a, b) => a + b, 0);
            return totalCostPurchase;
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 25 '18 at 7:10









            Javascript CoderJavascript Coder

            3,41053059




            3,41053059













            • I will try to reduce the code and will try to clean up.

              – Javascript Coder
              Nov 25 '18 at 7:11



















            • I will try to reduce the code and will try to clean up.

              – Javascript Coder
              Nov 25 '18 at 7:11

















            I will try to reduce the code and will try to clean up.

            – Javascript Coder
            Nov 25 '18 at 7:11





            I will try to reduce the code and will try to clean up.

            – Javascript Coder
            Nov 25 '18 at 7:11


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • 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.


            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%2fstackoverflow.com%2fquestions%2f53465237%2fjavascript-function-to-be-create-to-calculate-price-based-on-some-info-example%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

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Fotorealismo