Is it possible to return compared value + a string from a ternary operation without repeating said value?Conditional spread elementTernary Operators in JavaScript Without an “Else”How to return value from an asynchronous callback function?single return of ternary operatorIf without else ternary operatorUsing Ternary Operator without the Else statement PHPHow to use the ternary operator inside an interpolated string?how to set a date to expire in 72hoursHow to write a ternary operator (aka if) expression without repeating yourselfTernary operator with a null in 2nd valueHow to show the expiry time as timer for an offer in vue js html?

Authorship dispute on a paper that came out of a final report of a course?

Parser for STL stereolithography data files

Will copper pour help on my single-layer PCB?

Align the contents of a numerical matrix when you have minus signs

Making a Dataset that emulates `ls -tlra`?

Dative single noun Bankautomaten?

What are my hardware upgrade optoins for a late 2009 iMac?

Which modern firearm should a time traveler bring to be easily reproducible for a historic civilization?

How did Jayne know when to shoot?

Should I work for free if client's requirement changed

How do you name this compound using IUPAC system (including steps)?

Manager is asking me to eat breakfast from now on

Is "repository" pronounced /rɪˈpɒzɪt(ə)ri/ or ri-ˈpä-zə-ˌtȯr-ē or /rəˈpäzəˌtôrē/?

Could Europeans in Europe demand protection under UN Declaration on the Rights of Indigenous Peoples?

When we are talking about black hole evaporation - what exactly happens?

Why don't humans perceive sound waves as twice the frequency they are?

Simplest instruction set that has an c++/C compiler to write an emulator for?

How was Luke's prosthetic hand in Episode V filmed?

Suggestions for how to track down the source of this force:source:push error?

Why are flying carpets banned while flying brooms are not?

What makes MOVEQ quicker than a normal MOVE in 68000 assembly?

Is encryption still applied if you ignore the SSL certificate warning for self-signed certs?

Did Hitler say this quote about homeschooling?

Counting multiples of 3 up to a given number



Is it possible to return compared value + a string from a ternary operation without repeating said value?


Conditional spread elementTernary Operators in JavaScript Without an “Else”How to return value from an asynchronous callback function?single return of ternary operatorIf without else ternary operatorUsing Ternary Operator without the Else statement PHPHow to use the ternary operator inside an interpolated string?how to set a date to expire in 72hoursHow to write a ternary operator (aka if) expression without repeating yourselfTernary operator with a null in 2nd valueHow to show the expiry time as timer for an offer in vue js html?






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








4















I'm trying to find an easier solution to a problem.



Problem:



I want to attempt and simplify this but I have no idea where to start.



let days = Math.floor(distance / (1000 * 60 * 60 * 24));
if(days > 0)
days = days + "d";



Attempt:



I was thinking I could use ternary operators to return the calculation + "d" like so:



let days = Math.floor(distance / (1000 * 60 * 60 * 24)) === 0 ? Math.floor(distance / (1000 * 60 * 60 * 24)) + "d" : "";


this is however very messy in my opinion and I can't figure out another way.



Current structure



I am currently calculating days, hours, minutes and seconds for a timer like this:



let distance = expiry - now;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);


After that I want to only show days if it's greater than 0 or minutes if it's greater than 0 and so on. I'm currently doing it with a bunch of if statements and a boolean to check if a value greater than 0 has been found already. Like so:



let isSet = false;

if (days > 0 && !isSet)
current = days + "d";
isSet = true;


if (hours > 0 && !isSet)
current = hours + "h";
isSet = true;


if (minutes > 0 && !isSet)
current = minutes + "m";
isSet = true;


if (seconds > 0 && !isSet)
current = seconds + "s";
isSet = true;


if (seconds < 0 && !isSet)
current = "expired";
isSet = true;



This does however feel very repetitive and wrong (even if it works).










share|improve this question

















  • 1





    The short answer to the title question is no. Your ternary argument in the example above must repeat itself. You can make it more readable by assigning days as you did at first: let days = Math.floor(distance / (1000 * 60 * 60 * 24)); and then assigning it again with a ternary: days = (days === 0) ? "" : days.

    – Jordan Stubblefield
    Mar 26 at 12:30

















4















I'm trying to find an easier solution to a problem.



Problem:



I want to attempt and simplify this but I have no idea where to start.



let days = Math.floor(distance / (1000 * 60 * 60 * 24));
if(days > 0)
days = days + "d";



Attempt:



I was thinking I could use ternary operators to return the calculation + "d" like so:



let days = Math.floor(distance / (1000 * 60 * 60 * 24)) === 0 ? Math.floor(distance / (1000 * 60 * 60 * 24)) + "d" : "";


this is however very messy in my opinion and I can't figure out another way.



Current structure



I am currently calculating days, hours, minutes and seconds for a timer like this:



let distance = expiry - now;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);


After that I want to only show days if it's greater than 0 or minutes if it's greater than 0 and so on. I'm currently doing it with a bunch of if statements and a boolean to check if a value greater than 0 has been found already. Like so:



let isSet = false;

if (days > 0 && !isSet)
current = days + "d";
isSet = true;


if (hours > 0 && !isSet)
current = hours + "h";
isSet = true;


if (minutes > 0 && !isSet)
current = minutes + "m";
isSet = true;


if (seconds > 0 && !isSet)
current = seconds + "s";
isSet = true;


if (seconds < 0 && !isSet)
current = "expired";
isSet = true;



This does however feel very repetitive and wrong (even if it works).










share|improve this question

















  • 1





    The short answer to the title question is no. Your ternary argument in the example above must repeat itself. You can make it more readable by assigning days as you did at first: let days = Math.floor(distance / (1000 * 60 * 60 * 24)); and then assigning it again with a ternary: days = (days === 0) ? "" : days.

    – Jordan Stubblefield
    Mar 26 at 12:30













4












4








4








I'm trying to find an easier solution to a problem.



Problem:



I want to attempt and simplify this but I have no idea where to start.



let days = Math.floor(distance / (1000 * 60 * 60 * 24));
if(days > 0)
days = days + "d";



Attempt:



I was thinking I could use ternary operators to return the calculation + "d" like so:



let days = Math.floor(distance / (1000 * 60 * 60 * 24)) === 0 ? Math.floor(distance / (1000 * 60 * 60 * 24)) + "d" : "";


this is however very messy in my opinion and I can't figure out another way.



Current structure



I am currently calculating days, hours, minutes and seconds for a timer like this:



let distance = expiry - now;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);


After that I want to only show days if it's greater than 0 or minutes if it's greater than 0 and so on. I'm currently doing it with a bunch of if statements and a boolean to check if a value greater than 0 has been found already. Like so:



let isSet = false;

if (days > 0 && !isSet)
current = days + "d";
isSet = true;


if (hours > 0 && !isSet)
current = hours + "h";
isSet = true;


if (minutes > 0 && !isSet)
current = minutes + "m";
isSet = true;


if (seconds > 0 && !isSet)
current = seconds + "s";
isSet = true;


if (seconds < 0 && !isSet)
current = "expired";
isSet = true;



This does however feel very repetitive and wrong (even if it works).










share|improve this question














I'm trying to find an easier solution to a problem.



Problem:



I want to attempt and simplify this but I have no idea where to start.



let days = Math.floor(distance / (1000 * 60 * 60 * 24));
if(days > 0)
days = days + "d";



Attempt:



I was thinking I could use ternary operators to return the calculation + "d" like so:



let days = Math.floor(distance / (1000 * 60 * 60 * 24)) === 0 ? Math.floor(distance / (1000 * 60 * 60 * 24)) + "d" : "";


this is however very messy in my opinion and I can't figure out another way.



Current structure



I am currently calculating days, hours, minutes and seconds for a timer like this:



let distance = expiry - now;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);


After that I want to only show days if it's greater than 0 or minutes if it's greater than 0 and so on. I'm currently doing it with a bunch of if statements and a boolean to check if a value greater than 0 has been found already. Like so:



let isSet = false;

if (days > 0 && !isSet)
current = days + "d";
isSet = true;


if (hours > 0 && !isSet)
current = hours + "h";
isSet = true;


if (minutes > 0 && !isSet)
current = minutes + "m";
isSet = true;


if (seconds > 0 && !isSet)
current = seconds + "s";
isSet = true;


if (seconds < 0 && !isSet)
current = "expired";
isSet = true;



This does however feel very repetitive and wrong (even if it works).







javascript if-statement ternary-operator






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 11:28









alex Hexanalex Hexan

481 silver badge5 bronze badges




481 silver badge5 bronze badges







  • 1





    The short answer to the title question is no. Your ternary argument in the example above must repeat itself. You can make it more readable by assigning days as you did at first: let days = Math.floor(distance / (1000 * 60 * 60 * 24)); and then assigning it again with a ternary: days = (days === 0) ? "" : days.

    – Jordan Stubblefield
    Mar 26 at 12:30












  • 1





    The short answer to the title question is no. Your ternary argument in the example above must repeat itself. You can make it more readable by assigning days as you did at first: let days = Math.floor(distance / (1000 * 60 * 60 * 24)); and then assigning it again with a ternary: days = (days === 0) ? "" : days.

    – Jordan Stubblefield
    Mar 26 at 12:30







1




1





The short answer to the title question is no. Your ternary argument in the example above must repeat itself. You can make it more readable by assigning days as you did at first: let days = Math.floor(distance / (1000 * 60 * 60 * 24)); and then assigning it again with a ternary: days = (days === 0) ? "" : days.

– Jordan Stubblefield
Mar 26 at 12:30





The short answer to the title question is no. Your ternary argument in the example above must repeat itself. You can make it more readable by assigning days as you did at first: let days = Math.floor(distance / (1000 * 60 * 60 * 24)); and then assigning it again with a ternary: days = (days === 0) ? "" : days.

– Jordan Stubblefield
Mar 26 at 12:30












7 Answers
7






active

oldest

votes


















5














I think the best solution for patterns like this, is to define the ranges in an array, then compare against it, to avoid code duplication.



var ranges = [
[86400000, 'd'],
[3600000, 'h'],
[60000, 'm'],
[1000, 's'],
]


Then loop over this array and check if the provided value is greater than the current period.



function humanDiff(milliseconds) 
for (var i = 0; i < ranges.length; i++)
if (milliseconds >= ranges[i][0])
return Math.round((milliseconds / ranges[i][0])) + ranges[i][1]
;

return milliseconds;



Example:



var expiry = new Date('2019-03-26 08:29');
var now = new Date('2019-03-26 05:00');
humanDiff(expiry - now) // 3h


Advantages:



  • Avoid unnecessary calculations (don't calculate hours and minutes when days are appropriate)

  • Avoid code repetition

  • Separate the setup from the execution (adding more metrics is as easy as adding a new record in the ranges array)





share|improve this answer






























    1














    Instead of storing the information as variables you could store them as properties of an object. You can then iterate through each property and just set the text you wish.






    const dateInfo = 
    days: 1E3 * 60 * 60 * 24,
    hours: 1E3 * 60 * 60,
    minutes: 1E3 * 60,
    seconds: 1E3
    ;

    function check(distance)
    return Object.keys(dateInfo).reduce(function(result, key)
    result[key] = Math.floor(distance / dateInfo[key]);
    distance -= dateInfo[key] * result[key];
    result[key] = result[key] > 0 ? `$result[key]$key` : "";
    return result;
    , );


    let result = check(1E9);
    console.log(result); // result
    console.log(Object.values(result).join(" ")); // Print all properties
    console.log(Object.values(result).find(item => item) || "Expired"); // Print first property





    The most efficient and compact way is:






    const dateInfo = 
    d: 1E3 * 60 * 60 * 24,
    h: 1E3 * 60 * 60,
    m: 1E3 * 60,
    s: 1E3
    ;

    function check(distance)
    // Find the biggest proprty that is still smaller than the total difference
    var key = Object.keys(dateInfo).find(key => dateInfo[key] <= distance);
    // No need for % since distance > dateInfo[key]
    return `$Math.floor(distance / dateInfo[key]) $ ""`;


    console.log(check(3E9)); //34d
    console.log(check(3E7)); //8h
    console.log(check(3E5)); //5m
    console.log(check(3E3)); //3s
    console.log(check(3E0)); //expired








    share|improve this answer
































      0














      You may use conditional spread






      const now = new Date(2018, 1, 5, 10, 11);
      const expiry = new Date(2018, 2, 5, 5, 6);

      let distance = expiry - now;
      let days = Math.floor(distance / (1000 * 60 * 60 * 24));
      let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      let seconds = Math.floor((distance % (1000 * 60)) / 1000);

      const arr = [
      ...(days > 0 ? [days + "d"] : []),
      ...(hours > 0 ? [hours + "h"] : []),
      ...(minutes > 0 ? [minutes + "m"] : []),
      ...(seconds > 0 ? [seconds + "s"] : []),
      ];

      const current = arr.length ? arr.join(' ') : "expired";

      console.log(current);








      share|improve this answer






























        0














        getDurationDetails:function(duration)
        var result = [];
        var units =
        Year:31536000,
        Month:2592000,
        Week:604800,
        Day: 86400,
        Hour: 3600,
        Minute: 60,
        Second:1,
        ;

        for(var name in units)
        var res = Math.floor(duration/units[name]);
        if(res == 1) result.push(" " + res + " " + name);
        if(res >= 2) result.push(" " + res + " " + name + "s");
        duration %= units[name];

        return result;
        ,


        try this one






        share|improve this answer






























          0














          Your biggest issue is the isSet variable, not that you are using an if statement.



          Instead of setting isSet, you should just use else:



          var current;
          if (days > 0)
          current = days + "d";
          else if (hours > 0)
          current = hours + "h";
          else if (minutes > 0)
          current = minutes + "m";
          else if (seconds > 0)
          current = seconds + "s";
          else if (seconds < 0)
          current = "expired";
          // else seconds == 0


          You might want to use conditional operators here. You should not try to merge them into the days = Math.floor(distance / (1000 * 60 * 60 * 24)) computation, leave that as is - days is just a temporary variable. Store the result of the conditional in a different variable (current), not in days:



          const distance = expiry - now;
          const days = Math.floor(distance / (1000 * 60 * 60 * 24));
          const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
          const seconds = Math.floor((distance % (1000 * 60)) / 1000);

          const current =
          (days > 0) ? days + "d" :
          (hours > 0) ? hours + "h" :
          (minutes > 0) ? minutes + "m" :
          (seconds > 0) ? seconds + "s" :
          //(seconds == 0) ? undefined :
          "expired";





          share|improve this answer
































            0














            A waterfall method such as you have is not a bad idea. I would modify it to update the distance variable when you add to the string, such as this (e.g. 4d 3h 17m 1s):



            function formatDuration (seconds) 'expired';



            And a more expressive version (e.g. 4 days, 3 hours, 17 minutes, and 1 second):



            function formatDuration (seconds) 
            let s = seconds, r = '', t;

            // if (s % 31536000 !== s) updateR(' year', 31536000);
            if (s % 86400 !== s) updateR(' day', 86400);
            if (s % 3600 !== s) updateR(' hour', 3600);
            if (s % 60 !== s) updateR(' minute', 60);
            if (s > 0) updateR(' second', 1);

            function updateR(unit, n)
            t = Math.floor(s / n);
            s %= n;
            r += (r === '' ? '' : ', ') + t + unit + (t === 1 ? '' : 's');


            return r.replace(/,s(?=d1,2sw+$)/, ' and ')





            share|improve this answer






























              0














              You could take an array of the values and if you find an index, take this index as accessor for the value and the postfix or take 'expired' as value.



              let distance = expiry - now,
              factors = [86400000, 3600000, 60000, 1000],
              values = factors.map(f => [Math.floor(distance / f), distance %= f][0]),
              index = values.findIndex(v => v > 0),
              result = index === -1 ? 'expired' : value[index] + 'DHMS'[index];

              console.log(result);





              share|improve this answer



























                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%2f55356035%2fis-it-possible-to-return-compared-value-a-string-from-a-ternary-operation-with%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                7 Answers
                7






                active

                oldest

                votes








                7 Answers
                7






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                5














                I think the best solution for patterns like this, is to define the ranges in an array, then compare against it, to avoid code duplication.



                var ranges = [
                [86400000, 'd'],
                [3600000, 'h'],
                [60000, 'm'],
                [1000, 's'],
                ]


                Then loop over this array and check if the provided value is greater than the current period.



                function humanDiff(milliseconds) 
                for (var i = 0; i < ranges.length; i++)
                if (milliseconds >= ranges[i][0])
                return Math.round((milliseconds / ranges[i][0])) + ranges[i][1]
                ;

                return milliseconds;



                Example:



                var expiry = new Date('2019-03-26 08:29');
                var now = new Date('2019-03-26 05:00');
                humanDiff(expiry - now) // 3h


                Advantages:



                • Avoid unnecessary calculations (don't calculate hours and minutes when days are appropriate)

                • Avoid code repetition

                • Separate the setup from the execution (adding more metrics is as easy as adding a new record in the ranges array)





                share|improve this answer



























                  5














                  I think the best solution for patterns like this, is to define the ranges in an array, then compare against it, to avoid code duplication.



                  var ranges = [
                  [86400000, 'd'],
                  [3600000, 'h'],
                  [60000, 'm'],
                  [1000, 's'],
                  ]


                  Then loop over this array and check if the provided value is greater than the current period.



                  function humanDiff(milliseconds) 
                  for (var i = 0; i < ranges.length; i++)
                  if (milliseconds >= ranges[i][0])
                  return Math.round((milliseconds / ranges[i][0])) + ranges[i][1]
                  ;

                  return milliseconds;



                  Example:



                  var expiry = new Date('2019-03-26 08:29');
                  var now = new Date('2019-03-26 05:00');
                  humanDiff(expiry - now) // 3h


                  Advantages:



                  • Avoid unnecessary calculations (don't calculate hours and minutes when days are appropriate)

                  • Avoid code repetition

                  • Separate the setup from the execution (adding more metrics is as easy as adding a new record in the ranges array)





                  share|improve this answer

























                    5












                    5








                    5







                    I think the best solution for patterns like this, is to define the ranges in an array, then compare against it, to avoid code duplication.



                    var ranges = [
                    [86400000, 'd'],
                    [3600000, 'h'],
                    [60000, 'm'],
                    [1000, 's'],
                    ]


                    Then loop over this array and check if the provided value is greater than the current period.



                    function humanDiff(milliseconds) 
                    for (var i = 0; i < ranges.length; i++)
                    if (milliseconds >= ranges[i][0])
                    return Math.round((milliseconds / ranges[i][0])) + ranges[i][1]
                    ;

                    return milliseconds;



                    Example:



                    var expiry = new Date('2019-03-26 08:29');
                    var now = new Date('2019-03-26 05:00');
                    humanDiff(expiry - now) // 3h


                    Advantages:



                    • Avoid unnecessary calculations (don't calculate hours and minutes when days are appropriate)

                    • Avoid code repetition

                    • Separate the setup from the execution (adding more metrics is as easy as adding a new record in the ranges array)





                    share|improve this answer













                    I think the best solution for patterns like this, is to define the ranges in an array, then compare against it, to avoid code duplication.



                    var ranges = [
                    [86400000, 'd'],
                    [3600000, 'h'],
                    [60000, 'm'],
                    [1000, 's'],
                    ]


                    Then loop over this array and check if the provided value is greater than the current period.



                    function humanDiff(milliseconds) 
                    for (var i = 0; i < ranges.length; i++)
                    if (milliseconds >= ranges[i][0])
                    return Math.round((milliseconds / ranges[i][0])) + ranges[i][1]
                    ;

                    return milliseconds;



                    Example:



                    var expiry = new Date('2019-03-26 08:29');
                    var now = new Date('2019-03-26 05:00');
                    humanDiff(expiry - now) // 3h


                    Advantages:



                    • Avoid unnecessary calculations (don't calculate hours and minutes when days are appropriate)

                    • Avoid code repetition

                    • Separate the setup from the execution (adding more metrics is as easy as adding a new record in the ranges array)






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 26 at 11:56









                    amdamd

                    14.9k5 gold badges37 silver badges55 bronze badges




                    14.9k5 gold badges37 silver badges55 bronze badges























                        1














                        Instead of storing the information as variables you could store them as properties of an object. You can then iterate through each property and just set the text you wish.






                        const dateInfo = 
                        days: 1E3 * 60 * 60 * 24,
                        hours: 1E3 * 60 * 60,
                        minutes: 1E3 * 60,
                        seconds: 1E3
                        ;

                        function check(distance)
                        return Object.keys(dateInfo).reduce(function(result, key)
                        result[key] = Math.floor(distance / dateInfo[key]);
                        distance -= dateInfo[key] * result[key];
                        result[key] = result[key] > 0 ? `$result[key]$key` : "";
                        return result;
                        , );


                        let result = check(1E9);
                        console.log(result); // result
                        console.log(Object.values(result).join(" ")); // Print all properties
                        console.log(Object.values(result).find(item => item) || "Expired"); // Print first property





                        The most efficient and compact way is:






                        const dateInfo = 
                        d: 1E3 * 60 * 60 * 24,
                        h: 1E3 * 60 * 60,
                        m: 1E3 * 60,
                        s: 1E3
                        ;

                        function check(distance)
                        // Find the biggest proprty that is still smaller than the total difference
                        var key = Object.keys(dateInfo).find(key => dateInfo[key] <= distance);
                        // No need for % since distance > dateInfo[key]
                        return `$Math.floor(distance / dateInfo[key]) $ ""`;


                        console.log(check(3E9)); //34d
                        console.log(check(3E7)); //8h
                        console.log(check(3E5)); //5m
                        console.log(check(3E3)); //3s
                        console.log(check(3E0)); //expired








                        share|improve this answer





























                          1














                          Instead of storing the information as variables you could store them as properties of an object. You can then iterate through each property and just set the text you wish.






                          const dateInfo = 
                          days: 1E3 * 60 * 60 * 24,
                          hours: 1E3 * 60 * 60,
                          minutes: 1E3 * 60,
                          seconds: 1E3
                          ;

                          function check(distance)
                          return Object.keys(dateInfo).reduce(function(result, key)
                          result[key] = Math.floor(distance / dateInfo[key]);
                          distance -= dateInfo[key] * result[key];
                          result[key] = result[key] > 0 ? `$result[key]$key` : "";
                          return result;
                          , );


                          let result = check(1E9);
                          console.log(result); // result
                          console.log(Object.values(result).join(" ")); // Print all properties
                          console.log(Object.values(result).find(item => item) || "Expired"); // Print first property





                          The most efficient and compact way is:






                          const dateInfo = 
                          d: 1E3 * 60 * 60 * 24,
                          h: 1E3 * 60 * 60,
                          m: 1E3 * 60,
                          s: 1E3
                          ;

                          function check(distance)
                          // Find the biggest proprty that is still smaller than the total difference
                          var key = Object.keys(dateInfo).find(key => dateInfo[key] <= distance);
                          // No need for % since distance > dateInfo[key]
                          return `$Math.floor(distance / dateInfo[key]) $ ""`;


                          console.log(check(3E9)); //34d
                          console.log(check(3E7)); //8h
                          console.log(check(3E5)); //5m
                          console.log(check(3E3)); //3s
                          console.log(check(3E0)); //expired








                          share|improve this answer



























                            1












                            1








                            1







                            Instead of storing the information as variables you could store them as properties of an object. You can then iterate through each property and just set the text you wish.






                            const dateInfo = 
                            days: 1E3 * 60 * 60 * 24,
                            hours: 1E3 * 60 * 60,
                            minutes: 1E3 * 60,
                            seconds: 1E3
                            ;

                            function check(distance)
                            return Object.keys(dateInfo).reduce(function(result, key)
                            result[key] = Math.floor(distance / dateInfo[key]);
                            distance -= dateInfo[key] * result[key];
                            result[key] = result[key] > 0 ? `$result[key]$key` : "";
                            return result;
                            , );


                            let result = check(1E9);
                            console.log(result); // result
                            console.log(Object.values(result).join(" ")); // Print all properties
                            console.log(Object.values(result).find(item => item) || "Expired"); // Print first property





                            The most efficient and compact way is:






                            const dateInfo = 
                            d: 1E3 * 60 * 60 * 24,
                            h: 1E3 * 60 * 60,
                            m: 1E3 * 60,
                            s: 1E3
                            ;

                            function check(distance)
                            // Find the biggest proprty that is still smaller than the total difference
                            var key = Object.keys(dateInfo).find(key => dateInfo[key] <= distance);
                            // No need for % since distance > dateInfo[key]
                            return `$Math.floor(distance / dateInfo[key]) $ ""`;


                            console.log(check(3E9)); //34d
                            console.log(check(3E7)); //8h
                            console.log(check(3E5)); //5m
                            console.log(check(3E3)); //3s
                            console.log(check(3E0)); //expired








                            share|improve this answer















                            Instead of storing the information as variables you could store them as properties of an object. You can then iterate through each property and just set the text you wish.






                            const dateInfo = 
                            days: 1E3 * 60 * 60 * 24,
                            hours: 1E3 * 60 * 60,
                            minutes: 1E3 * 60,
                            seconds: 1E3
                            ;

                            function check(distance)
                            return Object.keys(dateInfo).reduce(function(result, key)
                            result[key] = Math.floor(distance / dateInfo[key]);
                            distance -= dateInfo[key] * result[key];
                            result[key] = result[key] > 0 ? `$result[key]$key` : "";
                            return result;
                            , );


                            let result = check(1E9);
                            console.log(result); // result
                            console.log(Object.values(result).join(" ")); // Print all properties
                            console.log(Object.values(result).find(item => item) || "Expired"); // Print first property





                            The most efficient and compact way is:






                            const dateInfo = 
                            d: 1E3 * 60 * 60 * 24,
                            h: 1E3 * 60 * 60,
                            m: 1E3 * 60,
                            s: 1E3
                            ;

                            function check(distance)
                            // Find the biggest proprty that is still smaller than the total difference
                            var key = Object.keys(dateInfo).find(key => dateInfo[key] <= distance);
                            // No need for % since distance > dateInfo[key]
                            return `$Math.floor(distance / dateInfo[key]) $ ""`;


                            console.log(check(3E9)); //34d
                            console.log(check(3E7)); //8h
                            console.log(check(3E5)); //5m
                            console.log(check(3E3)); //3s
                            console.log(check(3E0)); //expired








                            const dateInfo = 
                            days: 1E3 * 60 * 60 * 24,
                            hours: 1E3 * 60 * 60,
                            minutes: 1E3 * 60,
                            seconds: 1E3
                            ;

                            function check(distance)
                            return Object.keys(dateInfo).reduce(function(result, key)
                            result[key] = Math.floor(distance / dateInfo[key]);
                            distance -= dateInfo[key] * result[key];
                            result[key] = result[key] > 0 ? `$result[key]$key` : "";
                            return result;
                            , );


                            let result = check(1E9);
                            console.log(result); // result
                            console.log(Object.values(result).join(" ")); // Print all properties
                            console.log(Object.values(result).find(item => item) || "Expired"); // Print first property





                            const dateInfo = 
                            days: 1E3 * 60 * 60 * 24,
                            hours: 1E3 * 60 * 60,
                            minutes: 1E3 * 60,
                            seconds: 1E3
                            ;

                            function check(distance)
                            return Object.keys(dateInfo).reduce(function(result, key)
                            result[key] = Math.floor(distance / dateInfo[key]);
                            distance -= dateInfo[key] * result[key];
                            result[key] = result[key] > 0 ? `$result[key]$key` : "";
                            return result;
                            , );


                            let result = check(1E9);
                            console.log(result); // result
                            console.log(Object.values(result).join(" ")); // Print all properties
                            console.log(Object.values(result).find(item => item) || "Expired"); // Print first property





                            const dateInfo = 
                            d: 1E3 * 60 * 60 * 24,
                            h: 1E3 * 60 * 60,
                            m: 1E3 * 60,
                            s: 1E3
                            ;

                            function check(distance)
                            // Find the biggest proprty that is still smaller than the total difference
                            var key = Object.keys(dateInfo).find(key => dateInfo[key] <= distance);
                            // No need for % since distance > dateInfo[key]
                            return `$Math.floor(distance / dateInfo[key]) $ ""`;


                            console.log(check(3E9)); //34d
                            console.log(check(3E7)); //8h
                            console.log(check(3E5)); //5m
                            console.log(check(3E3)); //3s
                            console.log(check(3E0)); //expired





                            const dateInfo = 
                            d: 1E3 * 60 * 60 * 24,
                            h: 1E3 * 60 * 60,
                            m: 1E3 * 60,
                            s: 1E3
                            ;

                            function check(distance)
                            // Find the biggest proprty that is still smaller than the total difference
                            var key = Object.keys(dateInfo).find(key => dateInfo[key] <= distance);
                            // No need for % since distance > dateInfo[key]
                            return `$Math.floor(distance / dateInfo[key]) $ ""`;


                            console.log(check(3E9)); //34d
                            console.log(check(3E7)); //8h
                            console.log(check(3E5)); //5m
                            console.log(check(3E3)); //3s
                            console.log(check(3E0)); //expired






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Mar 26 at 14:14

























                            answered Mar 26 at 11:37









                            nick zoumnick zoum

                            2,9432 gold badges15 silver badges42 bronze badges




                            2,9432 gold badges15 silver badges42 bronze badges





















                                0














                                You may use conditional spread






                                const now = new Date(2018, 1, 5, 10, 11);
                                const expiry = new Date(2018, 2, 5, 5, 6);

                                let distance = expiry - now;
                                let days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                let seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                const arr = [
                                ...(days > 0 ? [days + "d"] : []),
                                ...(hours > 0 ? [hours + "h"] : []),
                                ...(minutes > 0 ? [minutes + "m"] : []),
                                ...(seconds > 0 ? [seconds + "s"] : []),
                                ];

                                const current = arr.length ? arr.join(' ') : "expired";

                                console.log(current);








                                share|improve this answer



























                                  0














                                  You may use conditional spread






                                  const now = new Date(2018, 1, 5, 10, 11);
                                  const expiry = new Date(2018, 2, 5, 5, 6);

                                  let distance = expiry - now;
                                  let days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                  let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                  let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                  let seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                  const arr = [
                                  ...(days > 0 ? [days + "d"] : []),
                                  ...(hours > 0 ? [hours + "h"] : []),
                                  ...(minutes > 0 ? [minutes + "m"] : []),
                                  ...(seconds > 0 ? [seconds + "s"] : []),
                                  ];

                                  const current = arr.length ? arr.join(' ') : "expired";

                                  console.log(current);








                                  share|improve this answer

























                                    0












                                    0








                                    0







                                    You may use conditional spread






                                    const now = new Date(2018, 1, 5, 10, 11);
                                    const expiry = new Date(2018, 2, 5, 5, 6);

                                    let distance = expiry - now;
                                    let days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                    let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                    let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                    let seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                    const arr = [
                                    ...(days > 0 ? [days + "d"] : []),
                                    ...(hours > 0 ? [hours + "h"] : []),
                                    ...(minutes > 0 ? [minutes + "m"] : []),
                                    ...(seconds > 0 ? [seconds + "s"] : []),
                                    ];

                                    const current = arr.length ? arr.join(' ') : "expired";

                                    console.log(current);








                                    share|improve this answer













                                    You may use conditional spread






                                    const now = new Date(2018, 1, 5, 10, 11);
                                    const expiry = new Date(2018, 2, 5, 5, 6);

                                    let distance = expiry - now;
                                    let days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                    let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                    let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                    let seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                    const arr = [
                                    ...(days > 0 ? [days + "d"] : []),
                                    ...(hours > 0 ? [hours + "h"] : []),
                                    ...(minutes > 0 ? [minutes + "m"] : []),
                                    ...(seconds > 0 ? [seconds + "s"] : []),
                                    ];

                                    const current = arr.length ? arr.join(' ') : "expired";

                                    console.log(current);








                                    const now = new Date(2018, 1, 5, 10, 11);
                                    const expiry = new Date(2018, 2, 5, 5, 6);

                                    let distance = expiry - now;
                                    let days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                    let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                    let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                    let seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                    const arr = [
                                    ...(days > 0 ? [days + "d"] : []),
                                    ...(hours > 0 ? [hours + "h"] : []),
                                    ...(minutes > 0 ? [minutes + "m"] : []),
                                    ...(seconds > 0 ? [seconds + "s"] : []),
                                    ];

                                    const current = arr.length ? arr.join(' ') : "expired";

                                    console.log(current);





                                    const now = new Date(2018, 1, 5, 10, 11);
                                    const expiry = new Date(2018, 2, 5, 5, 6);

                                    let distance = expiry - now;
                                    let days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                    let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                    let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                    let seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                    const arr = [
                                    ...(days > 0 ? [days + "d"] : []),
                                    ...(hours > 0 ? [hours + "h"] : []),
                                    ...(minutes > 0 ? [minutes + "m"] : []),
                                    ...(seconds > 0 ? [seconds + "s"] : []),
                                    ];

                                    const current = arr.length ? arr.join(' ') : "expired";

                                    console.log(current);






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 26 at 11:36









                                    AlexanderAlexander

                                    1,1753 silver badges14 bronze badges




                                    1,1753 silver badges14 bronze badges





















                                        0














                                        getDurationDetails:function(duration)
                                        var result = [];
                                        var units =
                                        Year:31536000,
                                        Month:2592000,
                                        Week:604800,
                                        Day: 86400,
                                        Hour: 3600,
                                        Minute: 60,
                                        Second:1,
                                        ;

                                        for(var name in units)
                                        var res = Math.floor(duration/units[name]);
                                        if(res == 1) result.push(" " + res + " " + name);
                                        if(res >= 2) result.push(" " + res + " " + name + "s");
                                        duration %= units[name];

                                        return result;
                                        ,


                                        try this one






                                        share|improve this answer



























                                          0














                                          getDurationDetails:function(duration)
                                          var result = [];
                                          var units =
                                          Year:31536000,
                                          Month:2592000,
                                          Week:604800,
                                          Day: 86400,
                                          Hour: 3600,
                                          Minute: 60,
                                          Second:1,
                                          ;

                                          for(var name in units)
                                          var res = Math.floor(duration/units[name]);
                                          if(res == 1) result.push(" " + res + " " + name);
                                          if(res >= 2) result.push(" " + res + " " + name + "s");
                                          duration %= units[name];

                                          return result;
                                          ,


                                          try this one






                                          share|improve this answer

























                                            0












                                            0








                                            0







                                            getDurationDetails:function(duration)
                                            var result = [];
                                            var units =
                                            Year:31536000,
                                            Month:2592000,
                                            Week:604800,
                                            Day: 86400,
                                            Hour: 3600,
                                            Minute: 60,
                                            Second:1,
                                            ;

                                            for(var name in units)
                                            var res = Math.floor(duration/units[name]);
                                            if(res == 1) result.push(" " + res + " " + name);
                                            if(res >= 2) result.push(" " + res + " " + name + "s");
                                            duration %= units[name];

                                            return result;
                                            ,


                                            try this one






                                            share|improve this answer













                                            getDurationDetails:function(duration)
                                            var result = [];
                                            var units =
                                            Year:31536000,
                                            Month:2592000,
                                            Week:604800,
                                            Day: 86400,
                                            Hour: 3600,
                                            Minute: 60,
                                            Second:1,
                                            ;

                                            for(var name in units)
                                            var res = Math.floor(duration/units[name]);
                                            if(res == 1) result.push(" " + res + " " + name);
                                            if(res >= 2) result.push(" " + res + " " + name + "s");
                                            duration %= units[name];

                                            return result;
                                            ,


                                            try this one







                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Mar 26 at 11:53









                                            Harish CHHHarish CHH

                                            797 bronze badges




                                            797 bronze badges





















                                                0














                                                Your biggest issue is the isSet variable, not that you are using an if statement.



                                                Instead of setting isSet, you should just use else:



                                                var current;
                                                if (days > 0)
                                                current = days + "d";
                                                else if (hours > 0)
                                                current = hours + "h";
                                                else if (minutes > 0)
                                                current = minutes + "m";
                                                else if (seconds > 0)
                                                current = seconds + "s";
                                                else if (seconds < 0)
                                                current = "expired";
                                                // else seconds == 0


                                                You might want to use conditional operators here. You should not try to merge them into the days = Math.floor(distance / (1000 * 60 * 60 * 24)) computation, leave that as is - days is just a temporary variable. Store the result of the conditional in a different variable (current), not in days:



                                                const distance = expiry - now;
                                                const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                                const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                                const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                                const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                                const current =
                                                (days > 0) ? days + "d" :
                                                (hours > 0) ? hours + "h" :
                                                (minutes > 0) ? minutes + "m" :
                                                (seconds > 0) ? seconds + "s" :
                                                //(seconds == 0) ? undefined :
                                                "expired";





                                                share|improve this answer





























                                                  0














                                                  Your biggest issue is the isSet variable, not that you are using an if statement.



                                                  Instead of setting isSet, you should just use else:



                                                  var current;
                                                  if (days > 0)
                                                  current = days + "d";
                                                  else if (hours > 0)
                                                  current = hours + "h";
                                                  else if (minutes > 0)
                                                  current = minutes + "m";
                                                  else if (seconds > 0)
                                                  current = seconds + "s";
                                                  else if (seconds < 0)
                                                  current = "expired";
                                                  // else seconds == 0


                                                  You might want to use conditional operators here. You should not try to merge them into the days = Math.floor(distance / (1000 * 60 * 60 * 24)) computation, leave that as is - days is just a temporary variable. Store the result of the conditional in a different variable (current), not in days:



                                                  const distance = expiry - now;
                                                  const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                                  const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                                  const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                                  const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                                  const current =
                                                  (days > 0) ? days + "d" :
                                                  (hours > 0) ? hours + "h" :
                                                  (minutes > 0) ? minutes + "m" :
                                                  (seconds > 0) ? seconds + "s" :
                                                  //(seconds == 0) ? undefined :
                                                  "expired";





                                                  share|improve this answer



























                                                    0












                                                    0








                                                    0







                                                    Your biggest issue is the isSet variable, not that you are using an if statement.



                                                    Instead of setting isSet, you should just use else:



                                                    var current;
                                                    if (days > 0)
                                                    current = days + "d";
                                                    else if (hours > 0)
                                                    current = hours + "h";
                                                    else if (minutes > 0)
                                                    current = minutes + "m";
                                                    else if (seconds > 0)
                                                    current = seconds + "s";
                                                    else if (seconds < 0)
                                                    current = "expired";
                                                    // else seconds == 0


                                                    You might want to use conditional operators here. You should not try to merge them into the days = Math.floor(distance / (1000 * 60 * 60 * 24)) computation, leave that as is - days is just a temporary variable. Store the result of the conditional in a different variable (current), not in days:



                                                    const distance = expiry - now;
                                                    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                                    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                                    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                                    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                                    const current =
                                                    (days > 0) ? days + "d" :
                                                    (hours > 0) ? hours + "h" :
                                                    (minutes > 0) ? minutes + "m" :
                                                    (seconds > 0) ? seconds + "s" :
                                                    //(seconds == 0) ? undefined :
                                                    "expired";





                                                    share|improve this answer















                                                    Your biggest issue is the isSet variable, not that you are using an if statement.



                                                    Instead of setting isSet, you should just use else:



                                                    var current;
                                                    if (days > 0)
                                                    current = days + "d";
                                                    else if (hours > 0)
                                                    current = hours + "h";
                                                    else if (minutes > 0)
                                                    current = minutes + "m";
                                                    else if (seconds > 0)
                                                    current = seconds + "s";
                                                    else if (seconds < 0)
                                                    current = "expired";
                                                    // else seconds == 0


                                                    You might want to use conditional operators here. You should not try to merge them into the days = Math.floor(distance / (1000 * 60 * 60 * 24)) computation, leave that as is - days is just a temporary variable. Store the result of the conditional in a different variable (current), not in days:



                                                    const distance = expiry - now;
                                                    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                                    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                                    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                                    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                                                    const current =
                                                    (days > 0) ? days + "d" :
                                                    (hours > 0) ? hours + "h" :
                                                    (minutes > 0) ? minutes + "m" :
                                                    (seconds > 0) ? seconds + "s" :
                                                    //(seconds == 0) ? undefined :
                                                    "expired";






                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Mar 26 at 11:54

























                                                    answered Mar 26 at 11:49









                                                    BergiBergi

                                                    397k66 gold badges623 silver badges948 bronze badges




                                                    397k66 gold badges623 silver badges948 bronze badges





















                                                        0














                                                        A waterfall method such as you have is not a bad idea. I would modify it to update the distance variable when you add to the string, such as this (e.g. 4d 3h 17m 1s):



                                                        function formatDuration (seconds) 'expired';



                                                        And a more expressive version (e.g. 4 days, 3 hours, 17 minutes, and 1 second):



                                                        function formatDuration (seconds) 
                                                        let s = seconds, r = '', t;

                                                        // if (s % 31536000 !== s) updateR(' year', 31536000);
                                                        if (s % 86400 !== s) updateR(' day', 86400);
                                                        if (s % 3600 !== s) updateR(' hour', 3600);
                                                        if (s % 60 !== s) updateR(' minute', 60);
                                                        if (s > 0) updateR(' second', 1);

                                                        function updateR(unit, n)
                                                        t = Math.floor(s / n);
                                                        s %= n;
                                                        r += (r === '' ? '' : ', ') + t + unit + (t === 1 ? '' : 's');


                                                        return r.replace(/,s(?=d1,2sw+$)/, ' and ')





                                                        share|improve this answer



























                                                          0














                                                          A waterfall method such as you have is not a bad idea. I would modify it to update the distance variable when you add to the string, such as this (e.g. 4d 3h 17m 1s):



                                                          function formatDuration (seconds) 'expired';



                                                          And a more expressive version (e.g. 4 days, 3 hours, 17 minutes, and 1 second):



                                                          function formatDuration (seconds) 
                                                          let s = seconds, r = '', t;

                                                          // if (s % 31536000 !== s) updateR(' year', 31536000);
                                                          if (s % 86400 !== s) updateR(' day', 86400);
                                                          if (s % 3600 !== s) updateR(' hour', 3600);
                                                          if (s % 60 !== s) updateR(' minute', 60);
                                                          if (s > 0) updateR(' second', 1);

                                                          function updateR(unit, n)
                                                          t = Math.floor(s / n);
                                                          s %= n;
                                                          r += (r === '' ? '' : ', ') + t + unit + (t === 1 ? '' : 's');


                                                          return r.replace(/,s(?=d1,2sw+$)/, ' and ')





                                                          share|improve this answer

























                                                            0












                                                            0








                                                            0







                                                            A waterfall method such as you have is not a bad idea. I would modify it to update the distance variable when you add to the string, such as this (e.g. 4d 3h 17m 1s):



                                                            function formatDuration (seconds) 'expired';



                                                            And a more expressive version (e.g. 4 days, 3 hours, 17 minutes, and 1 second):



                                                            function formatDuration (seconds) 
                                                            let s = seconds, r = '', t;

                                                            // if (s % 31536000 !== s) updateR(' year', 31536000);
                                                            if (s % 86400 !== s) updateR(' day', 86400);
                                                            if (s % 3600 !== s) updateR(' hour', 3600);
                                                            if (s % 60 !== s) updateR(' minute', 60);
                                                            if (s > 0) updateR(' second', 1);

                                                            function updateR(unit, n)
                                                            t = Math.floor(s / n);
                                                            s %= n;
                                                            r += (r === '' ? '' : ', ') + t + unit + (t === 1 ? '' : 's');


                                                            return r.replace(/,s(?=d1,2sw+$)/, ' and ')





                                                            share|improve this answer













                                                            A waterfall method such as you have is not a bad idea. I would modify it to update the distance variable when you add to the string, such as this (e.g. 4d 3h 17m 1s):



                                                            function formatDuration (seconds) 'expired';



                                                            And a more expressive version (e.g. 4 days, 3 hours, 17 minutes, and 1 second):



                                                            function formatDuration (seconds) 
                                                            let s = seconds, r = '', t;

                                                            // if (s % 31536000 !== s) updateR(' year', 31536000);
                                                            if (s % 86400 !== s) updateR(' day', 86400);
                                                            if (s % 3600 !== s) updateR(' hour', 3600);
                                                            if (s % 60 !== s) updateR(' minute', 60);
                                                            if (s > 0) updateR(' second', 1);

                                                            function updateR(unit, n)
                                                            t = Math.floor(s / n);
                                                            s %= n;
                                                            r += (r === '' ? '' : ', ') + t + unit + (t === 1 ? '' : 's');


                                                            return r.replace(/,s(?=d1,2sw+$)/, ' and ')






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Mar 26 at 12:24









                                                            Jordan StubblefieldJordan Stubblefield

                                                            3432 silver badges13 bronze badges




                                                            3432 silver badges13 bronze badges





















                                                                0














                                                                You could take an array of the values and if you find an index, take this index as accessor for the value and the postfix or take 'expired' as value.



                                                                let distance = expiry - now,
                                                                factors = [86400000, 3600000, 60000, 1000],
                                                                values = factors.map(f => [Math.floor(distance / f), distance %= f][0]),
                                                                index = values.findIndex(v => v > 0),
                                                                result = index === -1 ? 'expired' : value[index] + 'DHMS'[index];

                                                                console.log(result);





                                                                share|improve this answer





























                                                                  0














                                                                  You could take an array of the values and if you find an index, take this index as accessor for the value and the postfix or take 'expired' as value.



                                                                  let distance = expiry - now,
                                                                  factors = [86400000, 3600000, 60000, 1000],
                                                                  values = factors.map(f => [Math.floor(distance / f), distance %= f][0]),
                                                                  index = values.findIndex(v => v > 0),
                                                                  result = index === -1 ? 'expired' : value[index] + 'DHMS'[index];

                                                                  console.log(result);





                                                                  share|improve this answer



























                                                                    0












                                                                    0








                                                                    0







                                                                    You could take an array of the values and if you find an index, take this index as accessor for the value and the postfix or take 'expired' as value.



                                                                    let distance = expiry - now,
                                                                    factors = [86400000, 3600000, 60000, 1000],
                                                                    values = factors.map(f => [Math.floor(distance / f), distance %= f][0]),
                                                                    index = values.findIndex(v => v > 0),
                                                                    result = index === -1 ? 'expired' : value[index] + 'DHMS'[index];

                                                                    console.log(result);





                                                                    share|improve this answer















                                                                    You could take an array of the values and if you find an index, take this index as accessor for the value and the postfix or take 'expired' as value.



                                                                    let distance = expiry - now,
                                                                    factors = [86400000, 3600000, 60000, 1000],
                                                                    values = factors.map(f => [Math.floor(distance / f), distance %= f][0]),
                                                                    index = values.findIndex(v => v > 0),
                                                                    result = index === -1 ? 'expired' : value[index] + 'DHMS'[index];

                                                                    console.log(result);






                                                                    share|improve this answer














                                                                    share|improve this answer



                                                                    share|improve this answer








                                                                    edited Mar 26 at 12:29

























                                                                    answered Mar 26 at 12:04









                                                                    Nina ScholzNina Scholz

                                                                    217k16 gold badges130 silver badges194 bronze badges




                                                                    217k16 gold badges130 silver badges194 bronze badges



























                                                                        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%2f55356035%2fis-it-possible-to-return-compared-value-a-string-from-a-ternary-operation-with%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

                                                                        Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                                        Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                                                        Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript