Installations
npm install lazy-ass
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
> 0.8
Typescript Support
Yes
Node Version
14.18.0
NPM Version
6.14.15
Statistics
69 Stars
125 Commits
5 Forks
3 Watching
2 Branches
1 Contributors
Updated on 21 Oct 2024
Bundle Size
1.84 kB
Minified
851.00 B
Minified + Gzipped
Languages
TypeScript (76.15%)
JavaScript (12.29%)
HTML (11.57%)
Total Downloads
Cumulative downloads
Total Downloads
932,460,344
Last day
-6.6%
1,034,606
Compared to previous day
Last week
2.8%
5,808,367
Compared to previous week
Last month
5.2%
24,480,956
Compared to previous month
Last year
7.3%
274,499,339
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
lazy-ass
Lazy assertions without performance penalty
Note: only tested against Node 4+
Example
Regular assertions evaluate all arguments and concatenate message EVERY time, even if the condition is true.
1console.assert(typeof foo === 'object', 2 'expected ' + JSON.stringify(foo, null, 2) + ' to be an object');
Lazy assertion function evaluates its arguments and forms a message ONLY IF the condition is false
1const {lazyAss} = require('lazy-ass') 2lazyAss(typeof foo === 'object', 'expected', foo, 'to be an object'); 3// shorter version 4const {lazyAss: la} = require('lazy-ass') 5la(typeof foo === 'object', 'expected', foo, 'to be an object');
Concatenates strings, stringifies objects, calls functions - only if condition is false.
1function environment() {
2 // returns string
3}
4var user = {} // an object
5lazyAsync(condition, 'something went wrong for', user, 'in', environment);
6// throws an error with message equivalent of
7// 'something went wrong for ' + JSON.stringify(user) + ' in ' + environment()
Why?
- Passing an object reference to a function is about 2000-3000 times faster than serializing an object and passing it as a string.
- Concatenating 2 strings before passing to a function is about 30% slower than passing 2 separate strings.
Install
Node: npm install lazy-ass --save
then var la = require('lazy-ass');
.
You can attach the methods to the global object using
require('lazy-ass').globalRegister();
.
Browser: bower install lazy-ass --save
, include index.js
,
attaches functions lazyAss
and la
to window
object.
Notes
You can pass as many arguments to lazyAss after the condition. The condition will be evaluated every time (this is required for any assertion). The rest of arguments will be concatenated according to rules
- string will be left unchanged.
- function will be called and its output will be concatenated.
- any array or object will be JSON stringified.
There will be single space between the individual parts.
Lazy async assertions
Sometimes you do not want to throw an error synchronously, breaking the entire
execution stack. Instead you can throw an error asynchronously using lazyAssync
,
which internally implements logic like this:
1if (!condition) { 2 setTimeout(function () { 3 throw new Error('Conditions is false!'); 4 }, 0); 5}
This allows the execution to continue, while your global error handler (like my favorite Sentry) can still forward the error with all specified information to your server.
1lazyAss.async(false, 'foo'); 2console.log('after assync'); 3// output 4after assync 5Uncaught Error: foo
In this case, there is no meaningful error stack, so use good message arguments - there is no performance penalty!
Rethrowing errors
If the condition itself is an instance of Error, it is simply rethrown (synchronously or asynchronously).
1lazyAss(new Error('foo'));
2// Uncaught Error: foo
Useful to make sure errors in the promise chains are not silently ignored.
For example, a rejected promise below this will be ignored.
1var p = new Promise(function (resolve, reject) { 2 reject(new Error('foo')); 3}); 4p.then(...);
We can catch it and rethrow it synchronously, but it will be ignored too (same way, only one step further)
1var p = new Promise(function (resolve, reject) { 2 reject(new Error('foo')); 3}); 4p.then(..., lazyAss);
But we can actually trigger global error if we rethrow the error asynchronously
1var p = new Promise(function (resolve, reject) { 2 reject(new Error('foo')); 3}); 4p.then(..., lazyAssync); 5// Uncaught Error: foo
Predicate function as a condition
Typically, JavaScript evaluates the condition expression first, then calls lazyAss. This means the function itself sees only the true / false result, and not the expression itself. This makes makes the error messages cryptic
lazyAss(2 + 2 === 5);
// Error
We usually get around this by giving at least one additional message argument to explain the condition tested
lazyAss(2 + 2 === 5, 'addition')
// Error: addition
lazyAss has a better solution: if you give a function that evaluates the condition expression, if the function returns false, the error message will include the source of the function, making the extra arguments unnecessary
lazyAss(function () { return 2 + 2 === 5; });
// Error: function () { return 2 + 2 === 5; }
The condition function has access to any variables in the scope, making it extremely powerful
var foo = 2, bar = 2;
lazyAss(function () { return foo + bar === 5; });
// Error: function () { return foo + bar === 5; }
In practical terms, I recommend using separate predicates function and passing relevant values to the lazyAss function. Remember, there is no performance penalty!
var foo = 2, bar = 2;
function isValidPair() {
return foo + bar === 5;
}
lazyAss(isValidPair, 'foo', foo, 'bar', bar);
// Error: function isValidPair() {
// return foo + bar === 5;
// } foo 2 bar 2
Testing
This library is fully tested under Node and inside browser environment (CasperJs). I described how one can test asynchronous assertion throwing in your own projects using Jasmine in a blog post.
TypeScript
If you use this function from a TypeScript project, we provide ambient type definition file. Because this is CommonJS library, use it like this
1import la = require('lazy-ass') 2// la should have type signature
Small print
Author: Gleb Bahmutov © 2014
License: MIT - do anything with the code, but don't blame me if it does not work.
Spread the word: tweet, star on github, etc.
Support: if you find any problems with this module, email / tweet / open issue on Github
MIT License
Copyright (c) 2014 Gleb Bahmutov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 0/27 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:8: update your workflow using https://app.stepsecurity.io/secureworkflow/bahmutov/lazy-ass/ci.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/bahmutov/lazy-ass/ci.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/bahmutov/lazy-ass/ci.yml/master?enable=pin
- Info: 0 out of 1 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 2 third-party GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 6 are checked with a SAST tool
Reason
43 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-9vvw-cc9w-f27h
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-h6ch-v84p-w6p9
- Warn: Project is vulnerable to: GHSA-qh2h-chj9-jffq
- Warn: Project is vulnerable to: GHSA-w5mw-f2hq-5fw8
- Warn: Project is vulnerable to: GHSA-44pw-h2cw-w3vq
- Warn: Project is vulnerable to: GHSA-jp4x-w63m-7wgm
- Warn: Project is vulnerable to: GHSA-c429-5p7v-vgjp
- Warn: Project is vulnerable to: GHSA-rc47-6667-2j5j
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-2pr6-76vf-7546
- Warn: Project is vulnerable to: GHSA-8j8c-7jfh-h6hx
- Warn: Project is vulnerable to: GHSA-896r-f27r-55mw
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-282f-qqgm-c34q
- Warn: Project is vulnerable to: GHSA-5v2h-r2cx-5xgj
- Warn: Project is vulnerable to: GHSA-rrrm-qjm4-v8hf
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-vh95-rmgr-6w4m / GHSA-xvch-5gv4-984h
- Warn: Project is vulnerable to: GHSA-r683-j2x4-v87g
- Warn: Project is vulnerable to: GHSA-hj9c-8jmm-8c52
- Warn: Project is vulnerable to: GHSA-4p35-cfcx-8653
- Warn: Project is vulnerable to: GHSA-7f3x-x4pr-wqhj
- Warn: Project is vulnerable to: GHSA-jpp7-7chh-cf67
- Warn: Project is vulnerable to: GHSA-q6wq-5p59-983w
- Warn: Project is vulnerable to: GHSA-j9fq-vwqv-2fm2
- Warn: Project is vulnerable to: GHSA-pqw5-jmp5-px4v
- Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp
- Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
- Warn: Project is vulnerable to: GHSA-x2pg-mjhr-2m5x
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-4x5v-gmq8-25ch
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-xc7v-wxcw-j472
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Score
2.5
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to lazy-ass
lazy-ass-helpful
lazy-ass plugin to automatically show helpful info for failed assertions
define-lazy-prop
Define a lazily evaluated property on an object
available-versions
Returns a promise with new versions higher than given for a npm module
lazy-cache
Cache requires to be lazy-loaded when needed.