Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.teledata-fn.de!newsfeed.arcor.de!newsspool2.arcor-online.net!news.arcor.de.POSTED!not-for-mail Content-Type: text/plain; charset="ISO-8859-1" Message-ID: <2493601.R5VuAm1OKa@PointedEars.de> From: Thomas 'PointedEars' Lahn Reply-To: Thomas 'PointedEars' Lahn Organization: PointedEars Software (PES) Date: Tue, 26 Jun 2012 22:38:44 +0200 User-Agent: KNode/4.4.11 Content-Transfer-Encoding: 7Bit X-Face: %i>XG-yXR'\"2P/C_aO%~;2o~?g0pPKmbOw^=NT`tprDEf++D.m7"}HW6.#=U:?2GGctkL,f89@H46O$ASoW&?s}.k+&. <4454122.7EdHYbU6jS@PointedEars.de> Followup-To: comp.lang.javascript MIME-Version: 1.0 Lines: 118 NNTP-Posting-Date: 26 Jun 2012 22:38:44 CEST NNTP-Posting-Host: ee0d84e1.newsspool4.arcor-online.net X-Trace: DXC=HBNhMdjccQ2_A0jCfgHO6>4IUK On 2012-06-25 05:14, Thomas 'PointedEars' Lahn wrote: >> JSX:color.js [1] defines jsx.dom.css.Color.prototype.getWebSafe() which >> computes the nearest Web-safe color for a given color. > ... >> [1] >> > > Interesting. Thanks. > As an aside, How is that an aside? :) > this function - > > function getNearestSafeValue (value) > { > if (value >= 0xFF) > { > return 0xFF; > } > > if (value <= 0) > { > return 0; > } > > for (var safeValues = [0, 0x33, 0x66, 0x99, 0xCC, 0xFF], > i = safeValues.length - 1; > i--;) > { > var item = safeValues[i]; > > if (value >= item) > { > if (value == item) > { > return value; > } > > var nextItem = safeValues[i + 1]; > if (value - item < nextItem - value) > { > return item; > } > > return nextItem; > } > } > return -1; > } > > - could be simplified to: > > function getNearestSafeValue (n) { > if (n >= 0xFF) { > return 0xFF; > } > if (n <= 0) { > return 0; > } > return Math.round(n / 0x33) * 0x33; > } Yes, indeed. I never considered multiples. I think it could be further optimized as follows: function getNearestSafeValue (value) { if (value >= 0xFF) { return 0xFF; } if (value <= 0) { return 0; } if (value % 0x33 == 0) { return value; } return Math.round(value / 0x33) * 0x33; } If there are no objections or further suggestions, I will use that from now on. > Or even in a single line (although less readable): > > function getNearestSafeValue (n) { > return n >= 0xFF ? 0xFF : n <= 0 ? 0 : Math.round(n / 0x33) * 0x33; > } No, thanks :) > A half-hearted benchmark indicates that the last version could be > between 2x faster (Chrome, Opera) and 5x faster (Firefox) than the > original. AISB, I am not that interested in benchmark results as they are treacherous. I am more interested in provably working, efficient algorithms. You have provided one. Thank you. PointedEars -- Use any version of Microsoft Frontpage to create your site. (This won't prevent people from viewing your source, but no one will want to steal it.) -- from (404-comp.)