Friday 25 March 2016

Noob questions about leftpad. 1) Is it efficient? 2) Would node need to read it for each page? 3) Would node need to re-interpret it for each page?

This is the code for leftpad module.exports = leftpad; function leftpad (str, len, ch) { str = String(str); var i = -1; if (!ch && ch !== 0) ch = ' '; len = len - str.length; while (++i < len) { foo: str = ch + str; } return str; } Is that actually an efficient way to prepend a string with a fixed number of characters?More specifically, how many times in this implementation will "str" be copied into the new string at the step I've labeled foo? Naively it looks like str will be recopied 'len' times. Naively it seems a better implementation would first create then prefix string then append (copy) str to the end of it.Is Node's Javascript engine smart enough to optimize that?If not, are thousands of packages really using this open source implementation that apparently no one thought might be, or should be reasonably optimized? function leftpad (str, len, ch) { str = String(str); var prefix = ''; var i = -1; if (!ch && ch !== 0) ch = ' '; len = len - str.length; while (++i < len) { bar: prefix = prefix + ch; } return prefix + str; } If open source really does work, I have to assume one of:the original code is optimal and I need to learn morethe original code is sufficient and people don't use kik for prepending long stringsJavascript is smart enough to optimize the original codeOr maybe open source doesn't "work".Anyway, here are my real noob question:If IN A BROWSER my code depended on leftpadWould my browser try to download leftpad for each and every page that referenced it?Would my browser have to read, parse, implement the module for each and every page that referenced it?And then in the context of node the same two questions:Would node try to read leftpad for each and every page that referenced it?Would node to read, parse, implement the module for each and every page that referenced it?Does either the browser or node have a context of library functions (or state) that survives a page load?

Submitted March 25, 2016 at 05:58PM by jpflathead

No comments:

Post a Comment