diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..3ffc669 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,425 @@ +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + + including for purposes of Section 3(b); and + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public licenses. +Notwithstanding, Creative Commons may elect to apply one of its public +licenses to material it publishes and in those instances will be +considered the "Licensor." Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the public +licenses. + +Creative Commons may be contacted at creativecommons.org. \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e431bbf --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +COFFEE = $(shell which coffee) + +watch: + ${COFFEE} -w -o ./js -c ./coffee + +build: + ${COFFEE} -o ./js -c ./coffee diff --git a/README.markdown b/README.markdown index 2d93b4c..aeca487 100644 --- a/README.markdown +++ b/README.markdown @@ -1,5 +1,6 @@ JavaScript equality comparison is a crazy thing, sometimes. When in doubt, use three equals signs. -Download the zip here: -https://github.com/dorey/JavaScript-Equality-Table/zipball/master \ No newline at end of file +You can view the demo [here](http://dorey.github.io/JavaScript-Equality-Table/). + +You can also check out a new, [unified version of the equality table](http://dorey.github.io/JavaScript-Equality-Table/unified/). diff --git a/coffee/comparison_table.coffee b/coffee/comparison_table.coffee new file mode 100644 index 0000000..42b1112 --- /dev/null +++ b/coffee/comparison_table.coffee @@ -0,0 +1,136 @@ +# log = -> console?.log?.apply(console, arguments) + +isString = (obj)-> + Object::toString.call(obj) is "[object String]" +isObject = (obj)-> + Object::toString.call(obj) is "[object Object]" + +class ForComparison + constructor: (@item)-> + ### + The goal here is to get a string that evaluates to the desired + value. This string is set to object.asString + + For complicated cases which can't be passed in JSON the value + can be passed as a string wrapped in backticks which is evaluated + here. + example: "`parseFloat("nan")`" means NaN. + ### + @asString = "#{@item}" + if isString(@item) + if @item.length > 0 and (mtch = @item.match(/^`(.*)`$/)) + match = mtch[1] + @item = new Function("return #{match}")() + if isString(@item) + @asString = JSON.stringify(@item) + else if @item is `undefined` + @asString = "undefined" + else if isObject(@item) + @asString = JSON.stringify(@item) + else if isNaN(@item) + @asString = "NaN" + else + @asString = JSON.stringify(@item) + else if @item.length is 0 + @asString = '""' + else if @item.toString() is "[object Object]" + @asString = "{}" + else if @item instanceof Array + @asString = JSON.stringify(@item) + testResults: (fc2, comparator="===")-> + evalStr = "" + @asString + comparator + fc2.asString + [evalStr, eval('(' + evalStr + ')')] + toString: -> + @asString + +### +The values which are strings wrapped in backticks (`) are evaluated +before being compared. +### +values = [true, false, 1, 0, -1, + "`'true'`", "`'false'`", "`'1'`", "`'0'`", "`'-1'`", "", + "`null`", "`undefined`", "`[]`", "`{}`", [[]], + [0], [1], "`parseFloat('nan')`"] + +# Ensure that the values going in are converted to string properly (for the table headers) +do -> + testRepr = (what, shouldBe)-> + fc = new ForComparison(what) + if fc.toString() isnt shouldBe + throw new Error("Value is not being represented correctly.") + testRepr(true,"true") + testRepr(false,"false") + testRepr(1,"1") + testRepr(0,"0") + testRepr(-1,"-1") + testRepr("`'true'`","\"true\"") + testRepr("`'false'`","\"false\"") + testRepr("`'1'`","\"1\"") + testRepr("`'0'`","\"0\"") + testRepr("`'-1'`","\"-1\"") + testRepr("","\"\"") + testRepr("`null`","null") + testRepr("`undefined`","undefined") + testRepr("`[]`","[]") + testRepr("`{}`","{}") + testRepr([[]],"[[]]") + testRepr([0],"[0]") + testRepr([1],"[1]") + testRepr("`parseFloat('nan')`","NaN") + +do -> + testEquality = (tf, item, comparator)-> + fc1 = new ForComparison(item) + if fc1.testResults(fc1, comparator)[1] isnt tf + throw new Error("Condition should be #{tf}") + # easy case + testEquality(`true==true`, "`true`", "==") + # these two were giving incorrect values before + testEquality(`[[]]==[[]]`, "`[[]]`", "==") + testEquality(`[]==[]`, "`[]`", "==") + +supportsCanvas = do -> + el = document.createElement "canvas" + !!(el.getContext && el.getContext("2d")) + +@buildComparisonTable = (values, comparator)-> + comps = (new ForComparison(v) for v in values) + $table = $("", class: "comparisons") + $headRow = $("").append("").appendTo($table) + $("
").appendTo($table) + for comp in comps + $el = if supportsCanvas then rotateText(comp.asString) else $("", class: "rotate", text: comp.asString) + $("", class: "header col").html($el).appendTo($headRow) + for valX, x in comps + $tr = $("
", class: "row header").text(valX.asString).appendTo($tr) + for valY, y in comps + td = $("", class: "cell", html: "
 
").appendTo($tr) + [evalStr, tf] = valX.testResults(valY, comparator) + td.attr("title", "#{evalStr} // #{tf}") + if tf + td.addClass("equal") + $table + +@buildComparisonTableForIf = (values)-> + comps = (new ForComparison(v) for v in values) + $table = $("", class: "comparisons") + for comp in comps + $tr = $("").html($("
", class: "header row", text: comp.asString)).appendTo($table) + $td = $("", class: "cell").html($("
", html: " ")).appendTo($tr) + val = (new Function("if(#{comp.asString}){return true}else{return false}"))() + if val + $td.addClass("equal") + expression = " if (#{comp.asString}) { /* #{if val then 'executes' else 'does not execute'} */ } " + $("
", class: "expression").html(expression).appendTo($tr) + $table + +rotateText = (txt, cHeight=80)-> + canv = document.createElement("canvas") + canv.width = "25" + canv.height = cHeight + c = canv.getContext("2d") + c.rotate(Math.PI / 2) + c.font = "15px Monospace" + c.textAlign = "right" + c.fillText(txt,cHeight,-10) + canv diff --git a/comparison-table.js b/comparison-table.js deleted file mode 100644 index 643941e..0000000 --- a/comparison-table.js +++ /dev/null @@ -1,83 +0,0 @@ - -var EqualityTable = (function(cmpStr){ - var comparisons = [true, false, 1, 0, -1, "1", "0", "-1", "", null, - undefined, [], {}, [[]], [0], [1], parseFloat("nan")]; - - function map(f, x) { - var result = []; - for (var i = 0; i < x.length; i += 1) - result.push(f(x[i])); - return result; - } - - function repr(x) { - if (typeof(x) === "string") return '"' + x.replace('"', '\\"') + '"'; - if (x && x.constructor === Array) return "[" + map(repr, x).join(", ") + "]"; - if (x && typeof(x) === "object") return "{}"; - return String(x); - } - - function buildTable(cmpStr) { - var _tableHtml = $("", {'class':'comparisons'}), - _curRow = $("").html(""); - _curRow.append($(""); - _curRow.append($("
"), - representations = [], - _tVal, i, j, result; - - $.each(comparisons, function(i){ - _tVal = repr(comparisons[i]); - _curRow.append($("", {'class':'col header'}).html($("").html(_tVal))) - representations.push(_tVal); - }) - _tableHtml.append(_curRow); - - if(cmpStr=="if-statement") { - _curRow = $("
", {'class':'row header'}).html("If (value)")) - var elem; - $.each(comparisons, function(i){ - elem = $("", {'class':'cell green'}).html("
") - if(comparisons[i]) { - elem.addClass('green'); - elem.attr('title', "if("+comparisons[i]+"){/*--executes--*/}") - } else { - elem.addClass('red'); - elem.attr('title', "if("+comparisons[i]+"){/*--does not execute--*/}") - } - _curRow.append(elem) - }) - _tableHtml.append(_curRow); - } else { - var elem; - for (i = 0; i < comparisons.length; i += 1) { - _curRow = $("
", {'class':'row header'}).html(representations[i])) - - for (j = 0; j < comparisons.length; j += 1) { - elem = $("", {'class': 'cell'}).html("
"); - if(cmpStr==="===") { - if(comparisons[i]===comparisons[j]) { - elem.addClass('green'); - elem.attr('title', ""+representations[i]+"==="+representations[j]+" » true ") - } else { - elem.addClass('red'); - elem.attr('title', ""+representations[i]+"==="+representations[j]+" » false ") - } - } else if(cmpStr==="=="){ - if(comparisons[i]==comparisons[j]) { - elem.addClass('green'); - elem.attr('title', ""+representations[i]+"=="+representations[j]+" » true ") - } else { - elem.addClass('red'); - elem.attr('title', ""+representations[i]+"=="+representations[j]+" » false ") - } - } - _curRow.append(elem); - } - _tableHtml.append(_curRow); - } - } - - return _tableHtml; - } - return buildTable; -})() diff --git a/index.html b/index.html index ef4dbc5..a5271f9 100644 --- a/index.html +++ b/index.html @@ -5,19 +5,22 @@ JS Comparison Table - + - + +
  • @@ -49,19 +52,29 @@

    === (negated: !==)

-

A standard IF statement. If(value) {/*- green -*/} else { /*- red -*/ }

+

A standard IF statement. If(value) {/*- green -*/} else { /*- white -*/ }

Note: This row does not match up with any of the rows in the other table.

Moral of the story:

-

Use three equals unless you fully understand the conversions that take place for two-equals.

+

+ Always use 3 equals unless you have a good reason to use 2. +

- + + + $("
  • New link: view everything in one table
  • ").appendTo("#tabs ul"); + + diff --git a/js/comparison_table.js b/js/comparison_table.js new file mode 100644 index 0000000..18c6a21 --- /dev/null +++ b/js/comparison_table.js @@ -0,0 +1,243 @@ +// Generated by CoffeeScript 1.6.3 +(function() { + var ForComparison, isObject, isString, rotateText, supportsCanvas, values; + + isString = function(obj) { + return Object.prototype.toString.call(obj) === "[object String]"; + }; + + isObject = function(obj) { + return Object.prototype.toString.call(obj) === "[object Object]"; + }; + + ForComparison = (function() { + function ForComparison(item) { + var match, mtch; + this.item = item; + /* + The goal here is to get a string that evaluates to the desired + value. This string is set to object.asString + + For complicated cases which can't be passed in JSON the value + can be passed as a string wrapped in backticks which is evaluated + here. + example: "`parseFloat("nan")`" means NaN. + */ + + this.asString = "" + this.item; + if (isString(this.item)) { + if (this.item.length > 0 && (mtch = this.item.match(/^`(.*)`$/))) { + match = mtch[1]; + this.item = new Function("return " + match)(); + if (isString(this.item)) { + this.asString = JSON.stringify(this.item); + } else if (this.item === undefined) { + this.asString = "undefined"; + } else if (isObject(this.item)) { + this.asString = JSON.stringify(this.item); + } else if (isNaN(this.item)) { + this.asString = "NaN"; + } else { + this.asString = JSON.stringify(this.item); + } + } else if (this.item.length === 0) { + this.asString = '""'; + } + } else if (this.item.toString() === "[object Object]") { + this.asString = "{}"; + } else if (this.item instanceof Array) { + this.asString = JSON.stringify(this.item); + } + } + + ForComparison.prototype.testResults = function(fc2, comparator) { + var evalStr; + if (comparator == null) { + comparator = "==="; + } + evalStr = "" + this.asString + comparator + fc2.asString; + return [evalStr, eval('(' + evalStr + ')')]; + }; + + ForComparison.prototype.toString = function() { + return this.asString; + }; + + return ForComparison; + + })(); + + /* + The values which are strings wrapped in backticks (`) are evaluated + before being compared. + */ + + + values = [true, false, 1, 0, -1, "`'true'`", "`'false'`", "`'1'`", "`'0'`", "`'-1'`", "", "`null`", "`undefined`", "`[]`", "`{}`", [[]], [0], [1], "`parseFloat('nan')`"]; + + (function() { + var testRepr; + testRepr = function(what, shouldBe) { + var fc; + fc = new ForComparison(what); + if (fc.toString() !== shouldBe) { + throw new Error("Value is not being represented correctly."); + } + }; + testRepr(true, "true"); + testRepr(false, "false"); + testRepr(1, "1"); + testRepr(0, "0"); + testRepr(-1, "-1"); + testRepr("`'true'`", "\"true\""); + testRepr("`'false'`", "\"false\""); + testRepr("`'1'`", "\"1\""); + testRepr("`'0'`", "\"0\""); + testRepr("`'-1'`", "\"-1\""); + testRepr("", "\"\""); + testRepr("`null`", "null"); + testRepr("`undefined`", "undefined"); + testRepr("`[]`", "[]"); + testRepr("`{}`", "{}"); + testRepr([[]], "[[]]"); + testRepr([0], "[0]"); + testRepr([1], "[1]"); + return testRepr("`parseFloat('nan')`", "NaN"); + })(); + + (function() { + var testEquality; + testEquality = function(tf, item, comparator) { + var fc1; + fc1 = new ForComparison(item); + if (fc1.testResults(fc1, comparator)[1] !== tf) { + throw new Error("Condition should be " + tf); + } + }; + testEquality(true==true, "`true`", "=="); + testEquality([[]]==[[]], "`[[]]`", "=="); + return testEquality([]==[], "`[]`", "=="); + })(); + + supportsCanvas = (function() { + var el; + el = document.createElement("canvas"); + return !!(el.getContext && el.getContext("2d")); + })(); + + this.buildComparisonTable = function(values, comparator) { + var $el, $headRow, $table, $tr, comp, comps, evalStr, td, tf, v, valX, valY, x, y, _i, _j, _k, _len, _len1, _len2, _ref; + comps = (function() { + var _i, _len, _results; + _results = []; + for (_i = 0, _len = values.length; _i < _len; _i++) { + v = values[_i]; + _results.push(new ForComparison(v)); + } + return _results; + })(); + $table = $("", { + "class": "comparisons" + }); + $headRow = $("").append("").appendTo($table); + $("
    ").appendTo($table); + for (_i = 0, _len = comps.length; _i < _len; _i++) { + comp = comps[_i]; + $el = supportsCanvas ? rotateText(comp.asString) : $("", { + "class": "rotate", + text: comp.asString + }); + $("", { + "class": "header col" + }).html($el).appendTo($headRow); + } + for (x = _j = 0, _len1 = comps.length; _j < _len1; x = ++_j) { + valX = comps[x]; + $tr = $("
    ", { + "class": "row header" + }).text(valX.asString).appendTo($tr); + for (y = _k = 0, _len2 = comps.length; _k < _len2; y = ++_k) { + valY = comps[y]; + td = $("", { + "class": "cell", + html: "
     
    " + }).appendTo($tr); + _ref = valX.testResults(valY, comparator), evalStr = _ref[0], tf = _ref[1]; + td.attr("title", "" + evalStr + " // " + tf); + if (tf) { + td.addClass("equal"); + } + } + } + highlightOnHover($table); + return $table; + }; + + this.buildComparisonTableForIf = function(values) { + var $table, $td, $tr, comp, comps, expression, v, val, _i, _len; + comps = (function() { + var _i, _len, _results; + _results = []; + for (_i = 0, _len = values.length; _i < _len; _i++) { + v = values[_i]; + _results.push(new ForComparison(v)); + } + return _results; + })(); + $table = $("", { + "class": "comparisons" + }); + for (_i = 0, _len = comps.length; _i < _len; _i++) { + comp = comps[_i]; + $tr = $("").html($("
    ", { + "class": "header row", + text: comp.asString + })).appendTo($table); + $td = $("", { + "class": "cell" + }).html($("
    ", { + html: " " + })).appendTo($tr); + val = (new Function("if(" + comp.asString + "){return true}else{return false}"))(); + if (val) { + $td.addClass("equal"); + } + expression = " if (" + comp.asString + ") { /* " + (val ? 'executes' : 'does not execute') + " */ } "; + $("
    ", { + "class": "expression" + }).html(expression).appendTo($tr); + } + return $table; + }; + + rotateText = function(txt, cHeight) { + var c, canv; + if (cHeight == null) { + cHeight = 80; + } + canv = document.createElement("canvas"); + canv.width = "25"; + canv.height = cHeight; + c = canv.getContext("2d"); + c.rotate(Math.PI / 2); + c.font = "15px Monospace"; + c.textAlign = "right"; + c.fillText(txt, cHeight, -10); + return canv; + }; + + highlightOnHover = function($table){ + $table + .delegate('td.cell', 'mouseenter', function(){ + var $headerColumnCell = $(this).closest('table').find('tr:first td:eq('+$(this).index()+')'); + var $headerRowCell = $(this).siblings(':first'); + $headerColumnCell.add($headerRowCell).addClass('highlight-cell'); + }) + .delegate('td.cell','mouseleave',function(){ + $(this).closest('table') + .find('td.highlight-cell') + .removeClass('highlight-cell'); + }); + }; + +}).call(this); diff --git a/styles/images/ui-bg_glass_100_f6f6f6_1x400.png b/styles/images/ui-bg_glass_100_f6f6f6_1x400.png new file mode 100644 index 0000000..9b383f4 Binary files /dev/null and b/styles/images/ui-bg_glass_100_f6f6f6_1x400.png differ diff --git a/styles/images/ui-bg_glass_100_fdf5ce_1x400.png b/styles/images/ui-bg_glass_100_fdf5ce_1x400.png new file mode 100644 index 0000000..a23baad Binary files /dev/null and b/styles/images/ui-bg_glass_100_fdf5ce_1x400.png differ diff --git a/styles/images/ui-bg_glass_65_ffffff_1x400.png b/styles/images/ui-bg_glass_65_ffffff_1x400.png new file mode 100644 index 0000000..42ccba2 Binary files /dev/null and b/styles/images/ui-bg_glass_65_ffffff_1x400.png differ diff --git a/styles/images/ui-bg_gloss-wave_35_f6a828_500x100.png b/styles/images/ui-bg_gloss-wave_35_f6a828_500x100.png new file mode 100644 index 0000000..39d5824 Binary files /dev/null and b/styles/images/ui-bg_gloss-wave_35_f6a828_500x100.png differ diff --git a/styles/images/ui-bg_highlight-soft_100_eeeeee_1x100.png b/styles/images/ui-bg_highlight-soft_100_eeeeee_1x100.png new file mode 100644 index 0000000..f127367 Binary files /dev/null and b/styles/images/ui-bg_highlight-soft_100_eeeeee_1x100.png differ diff --git a/simple.css b/styles/simple.css similarity index 96% rename from simple.css rename to styles/simple.css index d509cd1..534f999 100644 --- a/simple.css +++ b/styles/simple.css @@ -1,9 +1,20 @@ table.comparisons { border-spacing: 0; } +table.comparisons td.row.header { + text-align: right; + font-family: Monospace; + font-size: 15px; + font-weight: 600; + padding-right: 14px; + white-space: nowrap; +} table.comparisons td.cell { padding: 1.5px; } +table.comparisons td.highlight-cell { + background-color:#DDDDDD; +} table.comparisons td.cell div { width: 25px; height: 25px; @@ -11,25 +22,31 @@ table.comparisons td.cell div { -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; + background-color: white; + border-color: #b1b1b1; } -table.comparisons td.cell.green div { - background-color: #5bbe5b; - border-color: #0b6c0b; -} -table.comparisons td.cell.red div { - background-color: #ed9e98; - border-color: #be120d; +table.comparisons td.cell.equal div { + background-color: #5bbe5b; + border-color: #0b6c0b; } table.comparisons td.header.col { - height: 100px; + height: 90px; +} +table.comparisons td.header.col span.rotate { + position: absolute; + font-family: Monospace; + font-size: 15px; + font-weight: 600; + -moz-transform:rotate(90deg); + -webkit-transform:rotate(90deg); + -o-transform:rotate(90deg); + -ms-transform:rotate(90deg); + transform:rotate(90deg); } -table.comparisons td.header.col span { - position: absolute; - -moz-transform:rotate(90deg); - -webkit-transform:rotate(90deg); - -o-transform:rotate(90deg); - -ms-transform:rotate(90deg); - transform:rotate(90deg); +table.comparisons .expression { + font-size: 13px; + color: #666; + padding-left: 8px; } /* * jQuery UI CSS Framework 1.8.9 diff --git a/unified/index.html b/unified/index.html new file mode 100644 index 0000000..9231a5a --- /dev/null +++ b/unified/index.html @@ -0,0 +1,37 @@ + + + + + + JS Comparison Table + + + + + + + + +
    +

    Equality in JavaScript

    +
    +
    +
    +
    + + + + + Fork me on GitHub + + diff --git a/unified/unified_comparison_table.css b/unified/unified_comparison_table.css new file mode 100644 index 0000000..5deb9f0 --- /dev/null +++ b/unified/unified_comparison_table.css @@ -0,0 +1,102 @@ +body { + margin: 0; + font-family: Arial, Helvetica, sans-serif; +} +#content { + width: 1000px; + margin: 0 auto; +} +#table, #key { + float: left; +} +#table { + width: 780px; +} +#key { + margin-top: 120px; + width: 180px; +} + +table.comparisons { + border-spacing: 0; + color: #444; +} +table.comparisons p.desc { + margin: 0; + font-style: italic; + color: #666; + font-size: 14px; +} +table.comparisons td.row.header { + text-align: right; + font-family: Monospace; + font-size: 15px; + font-weight: 600; + white-space: nowrap; +} +table.comparisons td.row.header span { + color: #eee; + margin-right: -4px; +} +/*table.comparisons td.row.header.true { + background-color: #f8f8f8; +}*/ +table.comparisons td.row.header.true span { + color: #aaa; +} +table.comparisons.key td { + padding: 6px 0; +} +table.comparisons.key td.label { + padding-left: 6px; +} +table.comparisons td.cell { + padding: 1.5px; + cursor: pointer; +} +table.comparisons td.highlight-cell { + background-color:#E3E3E3; +} +table.comparisons td.cell div { + width: 25px; + height: 25px; + background-color: #ece3e2; + border: 2px solid #cecece; + border-radius: 3px; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + text-align: center; + line-height: 27px; + color: #c9c9c9; +} +table.comparisons td.strict-equality div, table.comparisons td.loose-equality div { + border-color: #817D7D; + background-color: #dbdbdb; + color: #817D7D; +} +table.comparisons td.strict-equality div { + color: #5f5f5f; + border-color: #464646; + background-color: #818181; + font-size: 28px; + font-weight: bold; +} +table.comparisons td.header.col { + height: 90px; +} +table.comparisons td.header.col span.rotate { + position: absolute; + font-family: Monospace; + font-size: 15px; + font-weight: 600; + -moz-transform:rotate(90deg); + -webkit-transform:rotate(90deg); + -o-transform:rotate(90deg); + -ms-transform:rotate(90deg); + transform:rotate(90deg); +} +table.comparisons .expression { + font-size: 13px; + color: #666; + padding-left: 8px; +} diff --git a/unified/unified_comparison_table.js b/unified/unified_comparison_table.js new file mode 100644 index 0000000..22271ad --- /dev/null +++ b/unified/unified_comparison_table.js @@ -0,0 +1,304 @@ +// Generated by CoffeeScript 1.6.3 +(function() { + var ForComparison, isObject, isString, rotateText, supportsCanvas, values; + + isString = function(obj) { + return Object.prototype.toString.call(obj) === "[object String]"; + }; + + isObject = function(obj) { + return Object.prototype.toString.call(obj) === "[object Object]"; + }; + + ForComparison = (function() { + function ForComparison(item) { + var match, mtch; + this.item = item; + /* + The goal here is to get a string that evaluates to the desired + value. This string is set to object.asString + + For complicated cases which can't be passed in JSON the value + can be passed as a string wrapped in backticks which is evaluated + here. + example: "`parseFloat("nan")`" means NaN. + */ + + this.asString = "" + this.item; + if (isString(this.item)) { + if (this.item.length > 0 && (mtch = this.item.match(/^`(.*)`$/))) { + match = mtch[1]; + this.item = new Function("return " + match)(); + if (isString(this.item)) { + this.asString = JSON.stringify(this.item); + } else if (this.item === undefined) { + this.asString = "undefined"; + } else if (isObject(this.item)) { + this.asString = JSON.stringify(this.item); + } else if (isNaN(this.item)) { + this.asString = "NaN"; + } else { + this.asString = JSON.stringify(this.item); + } + } else if (this.item.length === 0) { + this.asString = '""'; + } + } else if (this.item.toString() === "[object Object]") { + this.asString = "{}"; + } else if (this.item instanceof Array) { + this.asString = JSON.stringify(this.item); + } + } + + ForComparison.prototype.testResults = function(fc2, comparator) { + var evalStr; + if (comparator == null) { + comparator = "==="; + } + if (this.asString === "{}") { + evalStr = "[" + this.asString + comparator + fc2.asString + "][0]"; + } else { + evalStr = "" + this.asString + comparator + fc2.asString; + } + return [evalStr, eval(evalStr)]; + }; + + ForComparison.prototype.toString = function() { + return this.asString; + }; + + return ForComparison; + + })(); + + /* + The values which are strings wrapped in backticks (`) are evaluated + before being compared. + */ + + + values = [true, false, 1, 0, -1, "`'true'`", "`'false'`", "`'1'`", "`'0'`", "`'-1'`", "", "`null`", "`undefined`", "`[]`", "`{}`", [[]], [0], [1], "`parseFloat('nan')`"]; + + (function() { + var testRepr; + testRepr = function(what, shouldBe) { + var fc; + fc = new ForComparison(what); + if (fc.toString() !== shouldBe) { + throw new Error("Value is not being represented correctly."); + } + }; + testRepr(true, "true"); + testRepr(false, "false"); + testRepr(1, "1"); + testRepr(0, "0"); + testRepr(-1, "-1"); + testRepr("`'true'`", "\"true\""); + testRepr("`'false'`", "\"false\""); + testRepr("`'1'`", "\"1\""); + testRepr("`'0'`", "\"0\""); + testRepr("`'-1'`", "\"-1\""); + testRepr("", "\"\""); + testRepr("`null`", "null"); + testRepr("`undefined`", "undefined"); + testRepr("`[]`", "[]"); + testRepr("`{}`", "{}"); + testRepr([[]], "[[]]"); + testRepr([0], "[0]"); + testRepr([1], "[1]"); + return testRepr("`parseFloat('nan')`", "NaN"); + })(); + + (function() { + var testEquality; + testEquality = function(tf, item, comparator) { + var fc1; + fc1 = new ForComparison(item); + if (fc1.testResults(fc1, comparator)[1] !== tf) { + throw new Error("Condition should be " + tf); + } + }; + testEquality(true==true, "`true`", "=="); + testEquality([[]]==[[]], "`[[]]`", "=="); + return testEquality([]==[], "`[]`", "=="); + })(); + + supportsCanvas = (function() { + var el; + el = document.createElement("canvas"); + return !!(el.getContext && el.getContext("2d")); + })(); + + this.buildComparisonTable = function(values, comparator) { + var $el, $headRow, $table, $tr, comp, comps, evalStr, td, tf, v, valX, valY, x, y, _i, _j, _k, _len, _len1, _len2, _ref; + comps = (function() { + var _i, _len, _results; + _results = []; + for (_i = 0, _len = values.length; _i < _len; _i++) { + v = values[_i]; + _results.push(new ForComparison(v)); + } + return _results; + })(); + $table = $("", { + "class": "comparisons" + }); + $headRow = $("").append("").appendTo($table); + $("
    ").appendTo($table); + for (_i = 0, _len = comps.length; _i < _len; _i++) { + comp = comps[_i]; + $el = supportsCanvas ? rotateText(comp.asString) : $("", { + "class": "rotate", + text: comp.asString + }); + $("", { + "class": "header col" + }).html($el).appendTo($headRow); + } + for (x = _j = 0, _len1 = comps.length; _j < _len1; x = ++_j) { + valX = comps[x]; + $tr = $("
    ", { + "class": "row header" + }).text(valX.asString).appendTo($tr); + for (y = _k = 0, _len2 = comps.length; _k < _len2; y = ++_k) { + valY = comps[y]; + td = $("", { + "class": "cell", + html: "
     
    " + }).appendTo($tr); + _ref = valX.testResults(valY, comparator), evalStr = _ref[0], tf = _ref[1]; + td.attr("title", "" + evalStr + " // " + tf); + if (tf) { + td.addClass("green"); + } + } + } + highlightOnHover($table); + return $table; + }; + + this.buildUnifiedComparisonTable = function(values) { + var $el, $headRow, $table, $tr, comps, evalStr2, evalStr3, exprClass, r2, r3, status, td, txt, v, valX, valY, x, y, _i, _j, _len, _len1, _ref, _ref1; + comps = (function() { + var _i, _len, _results; + _results = []; + for (_i = 0, _len = values.length; _i < _len; _i++) { + v = values[_i]; + _results.push(new ForComparison(v)); + } + return _results; + })(); + $table = $("", { + "class": "comparisons" + }); + $headRow = $("").append("").appendTo($table); + exprClass = (function() { + var val; + val = (new Function("if(" + valX.asString + "){return true}else{return false}"))(); + if (val) { + return "true"; + } else { + return "false"; + } + })(); + $("
    ").appendTo($table); + for (x = _i = 0, _len = comps.length; _i < _len; x = ++_i) { + valX = comps[x]; + $el = supportsCanvas ? rotateText(valX.asString) : $("", { + "class": "rotate", + text: valX.asString + }); + $("", { + "class": "header col" + }).html($el).appendTo($headRow); + $tr = $("
    ", { + "class": "row header " + exprClass + }).text(valX.asString).append(":").appendTo($tr); + for (y = _j = 0, _len1 = comps.length; _j < _len1; y = ++_j) { + valY = comps[y]; + _ref = valX.testResults(valY, "=="), evalStr2 = _ref[0], r2 = _ref[1]; + _ref1 = valX.testResults(valY, "==="), evalStr3 = _ref1[0], r3 = _ref1[1]; + if (r2 && r3) { + status = "strict-equality"; + txt = "="; + } else if (r2) { + status = "loose-equality"; + txt = "≅"; + } else { + status = "no-equality"; + txt = "≠"; + } + td = $("", { + "class": "cell", + html: "
    " + txt + "
    " + }).appendTo($tr); + td.data("eval2", evalStr2); + td.data("eval3", evalStr3); + if (r2 && r3) { + td.addClass("strict-equality"); + } else if (r2) { + td.addClass("loose-equality"); + } + } + } + highlightOnHover($table); + return $table; + }; + + this.buildKeyTable = function() { + var $table, rowc, rowdesc, rowicon, rows, rowtxt, td, tr, _i, _len, _ref; + $table = $("", { + "class": "key comparisons" + }); + rows = [["no-eq", "≠", "Not equal"], ["loose-equality", "≅", "Loose equality", "Often gives \"false\" positives like \"1\" is true; [] is \"0\""], ["strict-equality", "=", "Strict equality", "Mostly evaluates as one would expect."]]; + for (_i = 0, _len = rows.length; _i < _len; _i++) { + _ref = rows[_i], rowc = _ref[0], rowicon = _ref[1], rowtxt = _ref[2], rowdesc = _ref[3]; + tr = $("").appendTo($table); + $("
    ", { + "class": "" + rowc + " cell" + }).html("
    " + rowicon + "
    ").appendTo(tr); + td = $("
    ", { + "class": "" + rowc + " label" + }).html(rowtxt); + if (rowdesc) { + $("

    ", { + "class": "desc", + html: rowdesc + }).appendTo(td); + } + td.appendTo(tr); + } + return $table; + }; + + rotateText = function(txt, cHeight) { + var c, canv; + if (cHeight == null) { + cHeight = 80; + } + canv = document.createElement("canvas"); + canv.width = "25"; + canv.height = cHeight; + c = canv.getContext("2d"); + c.rotate(Math.PI / 2); + c.font = "15px Monospace"; + c.textAlign = "right"; + c.fillText(txt, cHeight, -10); + return canv; + }; + + highlightOnHover = function($table){ + $table + .delegate('td.cell','mouseenter',function(){ + var $headerColumnCell = $(this).closest('table').find('tr:first td:eq('+$(this).index()+')'); + var $headerRowCell = $(this).siblings(':first'); + $headerColumnCell.add($headerRowCell).addClass('highlight-cell'); + }) + .delegate('td.cell','mouseleave',function(){ + $(this).closest('table') + .find('td.highlight-cell') + .removeClass('highlight-cell'); + }); + }; + +}).call(this); diff --git a/values.js b/values.js new file mode 100644 index 0000000..07c637c --- /dev/null +++ b/values.js @@ -0,0 +1,50 @@ +// Strings in backticks (`) are evaluated. +var values = [ + true, + false, + 1, + 0, + -1, + "`'true'`", + "`'false'`", + "`'1'`", + "`'0'`", + "`'-1'`", + "", + "`null`", + "`undefined`", + Infinity, + -Infinity, + "`[]`", + "`{}`", + [[]], + [0], + [1], + "`parseFloat('nan')`" +]; + +if ((""+window.location.search).match(/reordered/)) { + values = [ + false, + 0, + "`'0'`", + [0], + "", + "`[]`", + [[]], + true, + 1, + "`'1'`", + [1], + -1, + "`'-1'`", + "`'true'`", + "`'false'`", + Infinity, + -Infinity, + "`null`", + "`undefined`", + "`{}`", + "`parseFloat('nan')`" + ]; +} \ No newline at end of file