• Had the need to fill a string with '0' at the end.

    var len = 64;   
    var sb = parseInt(1023).toString(2);
    var sbl = sb.length;
    var sbFixedLenStart = ('0').repeat((len-sbl)?(len-sbl):0) + sb;
    var sbFixedLenEnd = sb + ('0').repeat((len-sbl)?(len-sbl):0);
    console.log(sbFixedLenStart);
    console.log(sbFixedLenEnd);
    
    /* output
    0000000000000000000000000000000000000000­000000000000001111111111
    1111111111000000000000000000000000000000­000000000000000000000000
    */
    
  • Almost there, but this blows up of the len is smaller than the length of the string without padding. A small modification solves it ((len-sbl>0)):

    var len = 6;   
    var sb = parseInt(1023).toString(2);
    var sbl = sb.length;
    var sbFixedLenStart = ('0').repeat((len-sbl>0)?(len-sbl):0) + sb;
    var sbFixedLenEnd = sb + ('0').repeat((len-sbl>0)?(len-sbl):0);
    console.log(sbFixedLenStart);
    console.log(sbFixedLenEnd);
    

    MDN usually has polyfills or in this case, a link to polyfills: https://developer.mozilla.org/en-US/docs­/Web/JavaScript/Reference/Global_Objects­/String/padStart
    Altho might need some tweaks to better fit Espruino's constraints...

  • Hmm, isn’t a negative value : false?

    Edit:

    just tested - it is not ........

    So many thanks for your input!

  • WAT Video is super funny - It is a must - wat a cool guy!

  • !! 0
    > false
    !! "0"
    > true
    

    gives different results which is interesting because

    "0"==0
    > true
    

    btw tried stuff from wat video in node.js and

    > {} + {}
    '[object Object][object Object]'
    

    which is not very sophisticated answer, NaN answer was much wiser :-)

  • Interesting - thanks! If padStart/padEnd really are that simple then they could probably be added to the firmware. It's one of those things that is pretty commonly used

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Workaround for not jet implemented String.padStart/padEnd

Posted by Avatar for MaBe @MaBe

Actions