UNPKG

8.18 kBMarkdownView Raw
1# lazy-ass
2
3> Lazy assertions without performance penalty
4
5[![NPM][lazy-ass-icon] ][lazy-ass-url]
6
7[![Build status][lazy-ass-ci-image] ][lazy-ass-ci-url]
8[![manpm](https://img.shields.io/badge/manpm-compatible-3399ff.svg)](https://github.com/bahmutov/manpm)
9[![dependencies][lazy-ass-dependencies-image] ][lazy-ass-dependencies-url]
10[![devdependencies][lazy-ass-devdependencies-image] ][lazy-ass-devdependencies-url]
11
12[![semantic-release][semantic-image] ][semantic-url]
13[![Coverage Status][lazy-ass-coverage-image]][lazy-ass-coverage-url]
14[![Codacy][lazy-ass-codacy-image]][lazy-ass-codacy-url]
15[![Code Climate][lazy-ass-code-climate-image]][lazy-ass-code-climate-url]
16
17[Demo](http://glebbahmutov.com/lazy-ass/)
18
19Is the current code breaking dependencies if released?
20[![Dont-break][circle-ci-image] ][circle-ci-url] - checks using
21[dont-break](https://github.com/bahmutov/dont-break)
22[circle-ci-image]: https://circleci.com/gh/bahmutov/lazy-ass.svg?style=svg
23[circle-ci-url]: https://circleci.com/gh/bahmutov/lazy-ass
24
25## Example
26
27Regular assertions evaluate all arguments and concatenate message
28EVERY time, even if the condition is true.
29
30```js
31console.assert(typeof foo === 'object',
32 'expected ' + JSON.stringify(foo, null, 2) + ' to be an object');
33```
34
35Lazy assertion function evaluates its arguments and forms
36a message ONLY IF the condition is false
37
38```js
39lazyAss(typeof foo === 'object', 'expected', foo, 'to be an object');
40```
41
42Concatenates strings, stringifies objects, calls functions - only if
43condition is false.
44
45```js
46function environment() {
47 // returns string
48}
49var user = {} // an object
50lazyAsync(condition, 'something went wrong for', user, 'in', environment);
51// throws an error with message equivalent of
52// 'something went wrong for ' + JSON.stringify(user) + ' in ' + environment()
53```
54
55## Why?
56
57* Passing an object reference to a function is about
58[2000-3000 times faster](http://jsperf.com/object-json-stringify)
59than serializing an object and passing it as a string.
60* Concatenating 2 strings before passing to a function is about
61[30% slower](http://jsperf.com/string-concat-vs-pass-string-reference)
62than passing 2 separate strings.
63
64## Install
65
66Node: `npm install lazy-ass --save` then `var la = require('lazy-ass');`.
67You can attach the methods to the global object using
68`require('lazy-ass').globalRegister();`.
69
70Browser: `bower install lazy-ass --save`, include `index.js`,
71attaches functions `lazyAss` and `la` to `window` object.
72
73## Notes
74
75You can pass as many arguments to *lazyAss* after the condition. The condition
76will be evaluated every time (this is required for any assertion). The rest of arguments
77will be concatenated according to rules
78
79* string will be left unchanged.
80* function will be called and its output will be concatenated.
81* any array or object will be JSON stringified.
82
83There will be single space between the individual parts.
84
85## Lazy async assertions
86
87Sometimes you do not want to throw an error synchronously, breaking the entire
88execution stack. Instead you can throw an error asynchronously using `lazyAssync`,
89which internally implements logic like this:
90
91```js
92if (!condition) {
93 setTimeout(function () {
94 throw new Error('Conditions is false!');
95 }, 0);
96}
97```
98
99This allows the execution to continue, while your global error handler (like
100my favorite [Sentry](http://glebbahmutov.com/blog/know-unknown-unknowns-with-sentry/))
101can still forward the error with all specified information to your server.
102
103```js
104lazyAss.async(false, 'foo');
105console.log('after assync');
106// output
107after assync
108Uncaught Error: foo
109```
110
111In this case, there is no meaningful error stack, so use good message
112arguments - there is no performance penalty!
113
114## Predicate function as a condition
115
116Typically, JavaScript evaluates the condition expression first, then calls *lazyAss*.
117This means the function itself sees only the true / false result, and not the expression
118itself. This makes makes the error messages cryptic
119
120 lazyAss(2 + 2 === 5);
121 // Error
122
123We usually get around this by giving at least one additional message argument to
124explain the condition tested
125
126 lazyAss(2 + 2 === 5, 'addition')
127 // Error: addition
128
129*lazyAss* has a better solution: if you give a function that evaluates the condition
130expression, if the function returns false, the error message will include the source
131of the function, making the extra arguments unnecessary
132
133 lazyAss(function () { return 2 + 2 === 5; });
134 // Error: function () { return 2 + 2 === 5; }
135
136The condition function has access to any variables in the scope, making it extremely
137powerful
138
139 var foo = 2, bar = 2;
140 lazyAss(function () { return foo + bar === 5; });
141 // Error: function () { return foo + bar === 5; }
142
143In practical terms, I recommend using separate predicates function and
144passing relevant values to the *lazyAss* function. Remember, there is no performance
145penalty!
146
147 var foo = 2, bar = 2;
148 function isValidPair() {
149 return foo + bar === 5;
150 }
151 lazyAss(isValidPair, 'foo', foo, 'bar', bar);
152 // Error: function isValidPair() {
153 // return foo + bar === 5;
154 // } foo 2 bar 2
155
156## Testing
157
158This library is fully tested under Node and inside browser environment (CasperJs).
159I described how one can test asynchronous assertion throwing in your own projects
160using Jasmine in [a blog post](http://glebbahmutov.com/blog/testing-async-lazy-assertion/).
161
162### Small print
163
164Author: Gleb Bahmutov © 2014
165
166* [@bahmutov](https://twitter.com/bahmutov)
167* [glebbahmutov.com](http://glebbahmutov.com)
168* [blog](http://glebbahmutov.com/blog)
169
170License: MIT - do anything with the code, but don't blame me if it does not work.
171
172Spread the word: tweet, star on github, etc.
173
174Support: if you find any problems with this module, email / tweet /
175[open issue](https://github.com/bahmutov/lazy-ass/issues) on Github
176
177## MIT License
178
179Copyright (c) 2014 Gleb Bahmutov
180
181Permission is hereby granted, free of charge, to any person
182obtaining a copy of this software and associated documentation
183files (the "Software"), to deal in the Software without
184restriction, including without limitation the rights to use,
185copy, modify, merge, publish, distribute, sublicense, and/or sell
186copies of the Software, and to permit persons to whom the
187Software is furnished to do so, subject to the following
188conditions:
189
190The above copyright notice and this permission notice shall be
191included in all copies or substantial portions of the Software.
192
193THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
194EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
195OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
196NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
197HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
198WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
199FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
200OTHER DEALINGS IN THE SOFTWARE.
201
202[lazy-ass-icon]: https://nodei.co/npm/lazy-ass.png?downloads=true
203[lazy-ass-url]: https://npmjs.org/package/lazy-ass
204[lazy-ass-ci-image]: https://travis-ci.org/bahmutov/lazy-ass.png?branch=master
205[lazy-ass-ci-url]: https://travis-ci.org/bahmutov/lazy-ass
206[lazy-ass-coverage-image]: https://coveralls.io/repos/bahmutov/lazy-ass/badge.png
207[lazy-ass-coverage-url]: https://coveralls.io/r/bahmutov/lazy-ass
208[lazy-ass-code-climate-image]: https://codeclimate.com/github/bahmutov/lazy-ass/badges/gpa.svg
209[lazy-ass-code-climate-url]: https://codeclimate.com/github/bahmutov/lazy-ass
210[lazy-ass-codacy-image]: https://www.codacy.com/project/badge/b60a0810c9af4fe4b2ae685932dbbdb8
211[lazy-ass-codacy-url]: https://www.codacy.com/public/bahmutov/lazy-ass.git
212[lazy-ass-dependencies-image]: https://david-dm.org/bahmutov/lazy-ass.png
213[lazy-ass-dependencies-url]: https://david-dm.org/bahmutov/lazy-ass
214[lazy-ass-devdependencies-image]: https://david-dm.org/bahmutov/lazy-ass/dev-status.png
215[lazy-ass-devdependencies-url]: https://david-dm.org/bahmutov/lazy-ass#info=devDependencies
216[semantic-image]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
217[semantic-url]: https://github.com/semantic-release/semantic-release