Dataset Viewer
Auto-converted to Parquet
code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
async function getCLS(url) { const browser = await puppeteer.launch({ args: ['--no-sandbox'], timeout: 10000, }); try { const page = await browser.newPage(); const client = await page.target().createCDPSession(); await client.send('Network.enable'); await client.send('ServiceWorker.enable'); await page.emulateNetworkConditions(puppeteer.networkConditions['Good 3G']); await page.emulateCPUThrottling(4); await page.emulate(phone); // inject a function with the code from // https://web.dev/cls/#measure-cls-in-javascript await page.evaluateOnNewDocument(calculateShifts); await page.goto(url, {waitUntil: 'load', timeout: 60000}); const cls = await page.evaluate(() => { return window.cumulativeLayoutShiftScore; }); browser.close(); return cls; } catch (error) { console.log(error); browser.close(); } }
Get cumulative layout shift for a URL @param {String} url - url to measure @return {Number} - cumulative layout shift
getCLS
javascript
addyosmani/puppeteer-webperf
cumulative-layout-shift.js
https://github.com/addyosmani/puppeteer-webperf/blob/master/cumulative-layout-shift.js
Apache-2.0
async function getLCP(url) { const browser = await puppeteer.launch({ args: ['--no-sandbox'], timeout: 10000, }); try { const page = await browser.newPage(); const client = await page.target().createCDPSession(); await client.send('Network.enable'); await client.send('ServiceWorker.enable'); await page.emulateNetworkConditions(puppeteer.networkConditions['Good 3G']); await page.emulateCPUThrottling(4); await page.emulate(phone); await page.evaluateOnNewDocument(calculateLCP); await page.goto(url, {waitUntil: 'load', timeout: 60000}); const lcp = await page.evaluate(() => { return window.largestContentfulPaint; }); browser.close(); return lcp; } catch (error) { console.log(error); browser.close(); } }
Get LCP for a provided URL @param {*} url @return {Number} lcp
getLCP
javascript
addyosmani/puppeteer-webperf
largest-contentful-paint.js
https://github.com/addyosmani/puppeteer-webperf/blob/master/largest-contentful-paint.js
Apache-2.0
async function lighthouseFromPuppeteer(url, options, config = null) { // Launch chrome using chrome-launcher const chrome = await chromeLauncher.launch(options); options.port = chrome.port; // Connect chrome-launcher to puppeteer const resp = await util.promisify(request)(`http://localhost:${options.port}/json/version`); const {webSocketDebuggerUrl} = JSON.parse(resp.body); const browser = await puppeteer.connect({ browserWSEndpoint: webSocketDebuggerUrl, }); // Run Lighthouse const {lhr} = await lighthouse(url, options, config); await browser.disconnect(); await chrome.kill(); const html = reportGenerator.generateReport(lhr, 'html'); fs.writeFile('report.html', html, function(err) { if (err) throw err; }); }
Perform a Lighthouse run @param {String} url - url The URL to test @param {Object} options - Optional settings for the Lighthouse run @param {Object} [config=null] - Configuration for the Lighthouse run. If not present, the default config is used.
lighthouseFromPuppeteer
javascript
addyosmani/puppeteer-webperf
lighthouse-report.js
https://github.com/addyosmani/puppeteer-webperf/blob/master/lighthouse-report.js
Apache-2.0
constructor (name, cpus) { this.name = name || 'HTTP'; this._watchers = null; this._error = null; this._server = null; this._port = null; this._paused = false; this.cpus = parseInt(cpus) || os.cpus().length; this.children = []; process.on('exit', (code) => { console.log(`[${this.name}.Daemon] Shutdown: Exited with code ${code}`); }); }
Multi-process HTTP Daemon that resets when files changed (in development) @class
constructor
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
start(port) { this._port = port || 3000; console.log(`[${this.name}.Daemon] Startup: Initializing`); if ((process.env.NODE_ENV || 'development') === 'development') { this.watch('', (changes) => { changes.forEach(change => { console.log(`[${this.name}.Daemon] ${change.event[0].toUpperCase()}${change.event.substr(1)}: ${change.path}`); }); this.children.forEach(child => child.send({invalidate: true})); this.children = []; !this.children.length && this.unwatch() && this.start(); }); } this._server && this._server.close(); this._server = null; for (var i = 0; i < this.cpus; i++) { let child = cluster.fork(); this.children.push(child); child.on('message', this.message.bind(this)); child.on('exit', this.exit.bind(this, child)); } console.log(`[${this.name}.Daemon] Startup: Spawning HTTP Workers`); }
Starts the Daemon. If all application services fail, will launch a dummy error app on the port provided. @param {Number} port
start
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
idle() { let port = this._port || 3000; this._server = http .createServer((req, res) => { this.error(req, res, this._error); req.connection.destroy(); }) .listen(port); console.log(`[${this.name}.Daemon] Idle: Unable to spawn HTTP Workers, listening on port ${port}`); }
Daemon failed to load, set it in idle state (accept connections, give dummy response)
idle
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
error(req, res, error) { res.writeHead(500, {'Content-Type': 'text/plain'}); res.end(`Application Error:\n${error.stack}`); }
Daemon failed to load, set it in idle state (accept connections, give dummy response)
error
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
message(data) { if (data.error) { this.logError(data.error); } }
Daemon failed to load, set it in idle state (accept connections, give dummy response)
message
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
exit(child, code) { let index = this.children.indexOf(child); if (index === -1) { return; } this.children.splice(index, 1); if (code === 0) { child = cluster.fork(); this.children.push(child); child.on('message', this.message.bind(this)); child.on('exit', this.exit.bind(this, child)); } if (this.children.length === 0) { this.idle(); } }
Shut down a child process given a specific exit code. (Reboot if clean shutdown.) @param {child_process} child @param {Number} code Exit status codes
exit
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
logError(error) { this._error = error; this._server = null; console.log(`[${this.name}.Daemon] ${error.name}: ${error.message}`); console.log(error.stack); }
Log an error on the Daemon @param {Error} error
logError
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
unwatch() { clearInterval(this._watchers.interval); this._watchers = null; return true; }
Stops watching a directory tree for changes
unwatch
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
watch (root, onChange) { let cwd = process.cwd(); function watchDir (dirname, watchers) { if (!watchers) { watchers = Object.create(null); watchers.directories = Object.create(null); watchers.interval = null; } let pathname = path.join(cwd, dirname); let files = fs.readdirSync(pathname); watchers.directories[dirname] = Object.create(null); files.forEach(function (name) { if (name === 'node_modules' || name.indexOf('.') === 0) { return; } let filename = path.join(dirname, name); let fullPath = path.join(cwd, filename); let stat = fs.statSync(fullPath); if (stat.isDirectory()) { watchDir(filename, watchers); return; } watchers.directories[dirname][name] = stat; }); return watchers; } let watchers = watchDir(root || ''); let self = this; watchers.iterate = function (changes) { if (!fs.existsSync(path.join(process.cwd(), '.daemon.pause'))) { // Skip a cycle if just unpaused... if (!this._paused) { if (changes.length) { onChange.call(self, changes); } } else { this._paused = false; } } else { this._paused = true; } }; watchers.interval = setInterval(function() { let changes = []; Object.keys(watchers.directories).forEach(function (dirname) { let dir = watchers.directories[dirname]; let dirPath = path.join(cwd, dirname); if (!fs.existsSync(dirPath)) { delete watchers.directories[dirname]; changes.push({event: 'removed', path: dirPath}); } else { let files = fs.readdirSync(dirPath); let added = []; let contents = Object.create(null); files.forEach(function (filename) { if (filename === 'node_modules' || filename.indexOf('.') === 0) { return; } let fullPath = path.join(dirPath, filename); let stat = fs.statSync(fullPath); if (stat.isDirectory()) { let checkPath = path.join(dirname, filename); if (!watchers.directories[checkPath]) { watchDir(checkPath, watchers); } } else { if (!dir[filename]) { added.push([filename, stat]); changes.push({event: 'added', path: fullPath}); return; } if (stat.mtime.toString() !== dir[filename].mtime.toString()) { dir[filename] = stat; changes.push({event: 'modified', path: fullPath}); } contents[filename] = true; } }); Object.keys(dir).forEach(function (filename) { let fullPath = path.join(cwd, dirname, filename); if (!contents[filename]) { delete dir[filename]; changes.push({event: 'removed', path: fullPath}); } }); added.forEach(function (change) { let [filename, stat] = change; dir[filename] = stat; }); } }); watchers.iterate(changes); }, 1000); return this._watchers = watchers; }
Watches a directory tree for changes @param {string} root Directory tree to watch @param {function} onChange Method to be executed when a change is detected
watch
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
function watchDir (dirname, watchers) { if (!watchers) { watchers = Object.create(null); watchers.directories = Object.create(null); watchers.interval = null; } let pathname = path.join(cwd, dirname); let files = fs.readdirSync(pathname); watchers.directories[dirname] = Object.create(null); files.forEach(function (name) { if (name === 'node_modules' || name.indexOf('.') === 0) { return; } let filename = path.join(dirname, name); let fullPath = path.join(cwd, filename); let stat = fs.statSync(fullPath); if (stat.isDirectory()) { watchDir(filename, watchers); return; } watchers.directories[dirname][name] = stat; }); return watchers; }
Watches a directory tree for changes @param {string} root Directory tree to watch @param {function} onChange Method to be executed when a change is detected
watchDir
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
constructor (cpus) { super('FunctionScript', cpus); }
Watches a directory tree for changes @param {string} root Directory tree to watch @param {function} onChange Method to be executed when a change is detected
constructor
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
constructor (cfg) { super(cfg); process.on('uncaughtException', e => { if (typeof process.send === 'function') { process.send({ error: { name: e.name, message: e.message, stack: e.stack } }); } process.exit(1); }); process.on('message', data => data.invalidate && process.exit(0)); process.on('exit', code => this.log(null, `Shutdown: Exited with code ${code}`)); }
Watches a directory tree for changes @param {string} root Directory tree to watch @param {function} onChange Method to be executed when a change is detected
constructor
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
listen (port, callback, opts) { super.listen(port, callback, opts); if (typeof process.send === 'function') { process.send({message: 'ready'}); } return this.server; }
Watches a directory tree for changes @param {string} root Directory tree to watch @param {function} onChange Method to be executed when a change is detected
listen
javascript
acode/FunctionScript
lib/daemon.js
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
MIT
renderComponent = (jsx, renderToDOM) => { if (renderToDOM) { const testDiv = document.createElement('div'); document.body.appendChild(testDiv); return render(jsx, testDiv); } return ReactTestUtils.renderIntoDocument(jsx); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
renderComponent
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
renderComponent = (jsx, renderToDOM) => { if (renderToDOM) { const testDiv = document.createElement('div'); document.body.appendChild(testDiv); return render(jsx, testDiv); } return ReactTestUtils.renderIntoDocument(jsx); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
renderComponent
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
findPaneByOrder = paneString => paneString === 'first' ? findTopPane() : findBottomPane()
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
findPaneByOrder
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
findPaneByOrder = paneString => paneString === 'first' ? findTopPane() : findBottomPane()
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
findPaneByOrder
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertStyles = (componentName, actualStyles, expectedStyles) => { Object.keys(expectedStyles).forEach(prop => { // console.log(`${prop}: '${actualStyles[prop]}',`); if (expectedStyles[prop] && expectedStyles[prop] !== '') { // console.log(`${prop}: '${actualStyles[prop]}',`); expect(actualStyles[prop]).to.equal( expectedStyles[prop], `${componentName} has incorrect css property for '${prop}'` ); } }); return this; }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertStyles
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertStyles = (componentName, actualStyles, expectedStyles) => { Object.keys(expectedStyles).forEach(prop => { // console.log(`${prop}: '${actualStyles[prop]}',`); if (expectedStyles[prop] && expectedStyles[prop] !== '') { // console.log(`${prop}: '${actualStyles[prop]}',`); expect(actualStyles[prop]).to.equal( expectedStyles[prop], `${componentName} has incorrect css property for '${prop}'` ); } }); return this; }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertStyles
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertPaneStyles = (expectedStyles, paneString) => { const pane = findPaneByOrder(paneString); return assertStyles( `${paneString} Pane`, findDOMNode(pane).style, expectedStyles ); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertPaneStyles
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertPaneStyles = (expectedStyles, paneString) => { const pane = findPaneByOrder(paneString); return assertStyles( `${paneString} Pane`, findDOMNode(pane).style, expectedStyles ); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertPaneStyles
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertCallbacks = ( expectedDragStartedCallback, expectedDragFinishedCallback ) => { expect(expectedDragStartedCallback).to.have.been.called(); expect(expectedDragFinishedCallback).to.have.been.called(); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertCallbacks
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertCallbacks = ( expectedDragStartedCallback, expectedDragFinishedCallback ) => { expect(expectedDragStartedCallback).to.have.been.called(); expect(expectedDragFinishedCallback).to.have.been.called(); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertCallbacks
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
getResizerPosition = () => { const resizerNode = findDOMNode(findResizer()[0]); return resizerNode.getBoundingClientRect(); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
getResizerPosition
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
getResizerPosition = () => { const resizerNode = findDOMNode(findResizer()[0]); return resizerNode.getBoundingClientRect(); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
getResizerPosition
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
calculateMouseMove = mousePositionDifference => { const resizerPosition = getResizerPosition(); const mouseMove = { start: { clientX: resizerPosition.left, clientY: resizerPosition.top, }, end: { clientX: resizerPosition.left, clientY: resizerPosition.top, }, }; if (mousePositionDifference.x) { mouseMove.end.clientX = resizerPosition.left + mousePositionDifference.x; } else if (mousePositionDifference.y) { mouseMove.end.clientY = resizerPosition.top + mousePositionDifference.y; } return mouseMove; }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
calculateMouseMove
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
calculateMouseMove = mousePositionDifference => { const resizerPosition = getResizerPosition(); const mouseMove = { start: { clientX: resizerPosition.left, clientY: resizerPosition.top, }, end: { clientX: resizerPosition.left, clientY: resizerPosition.top, }, }; if (mousePositionDifference.x) { mouseMove.end.clientX = resizerPosition.left + mousePositionDifference.x; } else if (mousePositionDifference.y) { mouseMove.end.clientY = resizerPosition.top + mousePositionDifference.y; } return mouseMove; }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
calculateMouseMove
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
simulateDragAndDrop = mousePositionDifference => { const mouseMove = calculateMouseMove(mousePositionDifference); component.onMouseDown(mouseMove.start); component.onMouseMove(mouseMove.end); component.onMouseUp(); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
simulateDragAndDrop
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
simulateDragAndDrop = mousePositionDifference => { const mouseMove = calculateMouseMove(mousePositionDifference); component.onMouseDown(mouseMove.start); component.onMouseMove(mouseMove.end); component.onMouseUp(); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
simulateDragAndDrop
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
changeSize = (newSize, comp) => { const parent = ReactTestUtils.findRenderedComponentWithType( splitPane, comp ); parent.setState({ size: newSize }); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
changeSize
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
changeSize = (newSize, comp) => { const parent = ReactTestUtils.findRenderedComponentWithType( splitPane, comp ); parent.setState({ size: newSize }); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
changeSize
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertClass = (comp, expectedClassName) => { expect(findDOMNode(comp).className).to.contain( expectedClassName, 'Incorrect className' ); return this; }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertClass
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertClass = (comp, expectedClassName) => { expect(findDOMNode(comp).className).to.contain( expectedClassName, 'Incorrect className' ); return this; }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertClass
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertOrientation(expectedOrientation) { expect(findDOMNode(component).className).to.contain( expectedOrientation, 'Incorrect orientation' ); return this; }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertOrientation
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertSplitPaneClass(expectedClassName) { assertClass(component, expectedClassName); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertSplitPaneClass
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertPaneClasses(expectedTopPaneClass, expectedBottomPaneClass) { assertClass(findTopPane(), expectedTopPaneClass); assertClass(findBottomPane(), expectedBottomPaneClass); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertPaneClasses
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertTopPaneClasses(expectedTopPaneClass) { assertClass(findTopPane(), expectedTopPaneClass); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertTopPaneClasses
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertBottomPaneClasses(expectedBottomPaneClass) { assertClass(findBottomPane(), expectedBottomPaneClass); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertBottomPaneClasses
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertPaneContents(expectedContents) { const panes = findPanes(); const values = panes.map(pane => findDOMNode(pane).textContent); expect(values).to.eql(expectedContents, 'Incorrect contents for Pane'); return this; }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertPaneContents
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertContainsResizer() { expect(findResizer().length).to.equal( 1, 'Expected the SplitPane to have a single Resizer' ); expect(findPanes().length).to.equal( 2, 'Expected the SplitPane to have 2 panes' ); return this; }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertContainsResizer
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertPaneWidth(expectedWidth, pane = 'first') { return assertPaneStyles({ width: expectedWidth }, pane); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertPaneWidth
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertPaneHeight(expectedHeight, pane = 'first') { return assertPaneStyles({ height: expectedHeight }, pane); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertPaneHeight
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertResizeByDragging(mousePositionDifference, expectedStyle) { simulateDragAndDrop(mousePositionDifference); return assertPaneStyles(expectedStyle, component.props.primary); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertResizeByDragging
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertResizeCallbacks( expectedDragStartedCallback, expectedDragFinishedCallback ) { simulateDragAndDrop(200); return assertCallbacks( expectedDragStartedCallback, expectedDragFinishedCallback ); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertResizeCallbacks
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertSizePersists(comp) { const pane = 'first'; changeSize(100, comp); assertPaneStyles({ width: '100px' }, pane); changeSize(undefined, comp); assertPaneStyles({ width: '100px' }, pane); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertSizePersists
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertResizerClasses(expectedClass) { assertClass(findResizer()[0], expectedClass); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertResizerClasses
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertPrimaryPanelChange(newJsx, primaryPane, secondaryPane) { const primary = findPaneByOrder(primaryPane); const secondary = findPaneByOrder(secondaryPane); expect(primary.props.size).to.equal(50); expect(secondary.props.size).to.equal(undefined); updateComponent(newJsx); expect(primary.props.size).to.equal(undefined); expect(secondary.props.size).to.equal(50); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertPrimaryPanelChange
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
assertPaneWidthChange(newJsx, expectedWidth, pane = 'first') { updateComponent(newJsx); return assertPaneStyles({ width: expectedWidth }, pane); }
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument(). So for testing resizing we need ReactDOM.render()
assertPaneWidthChange
javascript
tomkp/react-split-pane
test/assertions/Asserter.js
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
MIT
renderChunk(code, chunk, opts) { if (opts.format === 'umd') { // Can swap this out with MagicString.replace() when we bump it: // https://github.com/developit/microbundle/blob/f815a01cb63d90b9f847a4dcad2a64e6b2f8596f/src/index.js#L657-L671 const s = new MagicString(code); const minified = code.match( /([a-zA-Z$_]+)="undefined"!=typeof globalThis\?globalThis:(\1\|\|self)/, ); if (minified) { s.overwrite( minified.index, minified.index + minified[0].length, minified[2], ); } const unminified = code.match( /(global *= *)typeof +globalThis *!== *['"]undefined['"] *\? *globalThis *: *(global *\|\| *self)/, ); if (unminified) { s.overwrite( unminified.index, unminified.index + unminified[0].length, unminified[1] + unminified[2], ); } return { code: s.toString(), map: s.generateMap({ hires: true }), }; } }
', plugins: [ [ require.resolve('babel-plugin-transform-replace-expressions'), { replace: defines }, ], ], }), customBabel()({ babelHelpers: 'bundled', extensions: EXTENSIONS, // use a regex to make sure to exclude eventual hoisted packages exclude: /\/node_modules\//, passPerPreset: true, // @see https://babeljs.io/docs/en/options#passperpreset custom: { defines, modern, compress: options.compress !== false, targets: options.target === 'node' ? { node: '12' } : undefined, pragma: options.jsx, pragmaFrag: options.jsxFragment, typescript: !!useTypescript, jsxImportSource: options.jsxImportSource || false, }, }), options.compress !== false && [ terser({ compress: Object.assign( { keep_infinity: true, pure_getters: true, // Ideally we'd just get Terser to respect existing Arrow functions... // unsafe_arrows: true, passes: 10, }, typeof minifyOptions.compress === 'boolean' ? minifyOptions.compress : minifyOptions.compress || {}, ), format: { // By default, Terser wraps function arguments in extra parens to trigger eager parsing. // Whether this is a good idea is way too specific to guess, so we optimize for size by default: wrap_func_args: false, comments: /^\s*([@#]__[A-Z]+__\s*$|@cc_on)/, preserve_annotations: true, }, module: modern, ecma: modern ? 2017 : 5, toplevel: modern || format === 'cjs' || format === 'es', mangle: typeof minifyOptions.mangle === 'boolean' ? minifyOptions.mangle : Object.assign({}, minifyOptions.mangle || {}), nameCache, }), nameCache && { // before hook options: loadNameCache, // after hook writeBundle() { if (writeMeta && nameCache) { let filename = getNameCachePath(); let json = JSON.stringify( nameCache, null, nameCacheIndentTabs ? '\t' : 2, ); if (endsWithNewLine) json += EOL; fs.writeFile(filename, json, () => {}); } }, }, ], options.visualize && visualizer(), // NOTE: OMT only works with amd and esm // Source: https://github.com/surma/rollup-plugin-off-main-thread#config useWorkerLoader && (format === 'es' || modern) && OMT(), /** @type {import('rollup').Plugin}
renderChunk
javascript
developit/microbundle
src/index.js
https://github.com/developit/microbundle/blob/master/src/index.js
MIT
writeBundle(_, bundle) { config._sizeInfo = Promise.all( Object.values(bundle).map(({ code, fileName }) => { if (code) { return getSizeInfo(code, fileName, options.raw); } }), ).then(results => results.filter(Boolean).join('\n')); }
', plugins: [ [ require.resolve('babel-plugin-transform-replace-expressions'), { replace: defines }, ], ], }), customBabel()({ babelHelpers: 'bundled', extensions: EXTENSIONS, // use a regex to make sure to exclude eventual hoisted packages exclude: /\/node_modules\//, passPerPreset: true, // @see https://babeljs.io/docs/en/options#passperpreset custom: { defines, modern, compress: options.compress !== false, targets: options.target === 'node' ? { node: '12' } : undefined, pragma: options.jsx, pragmaFrag: options.jsxFragment, typescript: !!useTypescript, jsxImportSource: options.jsxImportSource || false, }, }), options.compress !== false && [ terser({ compress: Object.assign( { keep_infinity: true, pure_getters: true, // Ideally we'd just get Terser to respect existing Arrow functions... // unsafe_arrows: true, passes: 10, }, typeof minifyOptions.compress === 'boolean' ? minifyOptions.compress : minifyOptions.compress || {}, ), format: { // By default, Terser wraps function arguments in extra parens to trigger eager parsing. // Whether this is a good idea is way too specific to guess, so we optimize for size by default: wrap_func_args: false, comments: /^\s*([@#]__[A-Z]+__\s*$|@cc_on)/, preserve_annotations: true, }, module: modern, ecma: modern ? 2017 : 5, toplevel: modern || format === 'cjs' || format === 'es', mangle: typeof minifyOptions.mangle === 'boolean' ? minifyOptions.mangle : Object.assign({}, minifyOptions.mangle || {}), nameCache, }), nameCache && { // before hook options: loadNameCache, // after hook writeBundle() { if (writeMeta && nameCache) { let filename = getNameCachePath(); let json = JSON.stringify( nameCache, null, nameCacheIndentTabs ? '\t' : 2, ); if (endsWithNewLine) json += EOL; fs.writeFile(filename, json, () => {}); } }, }, ], options.visualize && visualizer(), // NOTE: OMT only works with amd and esm // Source: https://github.com/surma/rollup-plugin-off-main-thread#config useWorkerLoader && (format === 'es' || modern) && OMT(), /** @type {import('rollup').Plugin}
writeBundle
javascript
developit/microbundle
src/index.js
https://github.com/developit/microbundle/blob/master/src/index.js
MIT
function safeVariableName(name) { const normalized = removeScope(name).toLowerCase(); const identifier = normalized.replace(INVALID_ES3_IDENT, ''); return camelCase(identifier); }
Turn a package name into a valid reasonably-unique variable name @param {string} name
safeVariableName
javascript
developit/microbundle
src/utils.js
https://github.com/developit/microbundle/blob/master/src/utils.js
MIT
function toReplacementExpression(value, name) { // --define A="1",B='true' produces string: const matches = value.match(/^(['"])(.+)\1$/); if (matches) { return [JSON.stringify(matches[2]), name]; } // --define @assign=Object.assign replaces expressions with expressions: if (name[0] === '@') { return [value, name.substring(1)]; } // --define A=1,B=true produces int/boolean literal: if (/^(true|false|\d+)$/i.test(value)) { return [value, name]; } // default: string literal return [JSON.stringify(value), name]; }
Convert booleans and int define= values to literals. This is more intuitive than `microbundle --define A=1` producing A="1".
toReplacementExpression
javascript
developit/microbundle
src/lib/option-normalization.js
https://github.com/developit/microbundle/blob/master/src/lib/option-normalization.js
MIT
function parseMappingArgument(globalStrings, processValue) { const globals = {}; globalStrings.split(',').forEach(globalString => { let [key, value] = globalString.split('='); if (processValue) { const r = processValue(value, key); if (r !== undefined) { if (Array.isArray(r)) { [value, key] = r; } else { value = r; } } } globals[key] = value; }); return globals; }
Parses values of the form "$=jQuery,React=react" into key-value object pairs.
parseMappingArgument
javascript
developit/microbundle
src/lib/option-normalization.js
https://github.com/developit/microbundle/blob/master/src/lib/option-normalization.js
MIT
function parseAliasArgument(aliasStrings) { return aliasStrings.split(',').map(str => { let [key, value] = str.split('='); return { find: key, replacement: value }; }); }
Parses values of the form "$=jQuery,React=react" into key-value object pairs.
parseAliasArgument
javascript
developit/microbundle
src/lib/option-normalization.js
https://github.com/developit/microbundle/blob/master/src/lib/option-normalization.js
MIT
function fastRestTransform({ template, types: t }) { const slice = template`var IDENT = Array.prototype.slice;`; const VISITOR = { RestElement(path, state) { if (path.parentKey !== 'params') return; // Create a global _slice alias let slice = state.get('slice'); if (!slice) { slice = path.scope.generateUidIdentifier('slice'); state.set('slice', slice); } // _slice.call(arguments) or _slice.call(arguments, 1) const args = [t.identifier('arguments')]; if (path.key) args.push(t.numericLiteral(path.key)); const sliced = t.callExpression( t.memberExpression(t.clone(slice), t.identifier('call')), args, ); const ident = path.node.argument; const binding = path.scope.getBinding(ident.name); if (binding.referencePaths.length !== 0) { // arguments access requires a non-Arrow function: const func = path.parentPath; if (t.isArrowFunctionExpression(func)) { func.arrowFunctionToExpression(); } if ( binding.constant && binding.referencePaths.length === 1 && sameArgumentsObject(binding.referencePaths[0], func, t) ) { // one usage, never assigned - replace usage inline binding.referencePaths[0].replaceWith(sliced); } else { // unknown usage, create a binding const decl = t.variableDeclaration('var', [ t.variableDeclarator(t.clone(ident), sliced), ]); func.get('body').unshiftContainer('body', decl); } } path.remove(); }, }; return { name: 'transform-fast-rest', visitor: { Program(path, state) { const childState = new Map(); const useHelper = state.opts.helper === true; // defaults to false if (!useHelper) { let inlineHelper; if (state.opts.literal === false) { inlineHelper = template.expression.ast`Array.prototype.slice`; } else { inlineHelper = template.expression.ast`[].slice`; } childState.set('slice', inlineHelper); } path.traverse(VISITOR, childState); const name = childState.get('slice'); if (name && useHelper) { const helper = slice({ IDENT: name }); t.addComment(helper.declarations[0].init, 'leading', '#__PURE__'); path.unshiftContainer('body', helper); } }, }, }; }
Transform ...rest parameters to [].slice.call(arguments,offset). Demo: https://astexplorer.net/#/gist/70aaa0306db9a642171ef3e2f35df2e0/576c150f647e4936fa6960e0453a11cdc5d81f21 Benchmark: https://jsperf.com/rest-arguments-babel-pr-9152/4 @param {object} opts @param {babel.template} opts.template @param {babel.types} opts.types @returns {babel.PluginObj}
fastRestTransform
javascript
developit/microbundle
src/lib/transform-fast-rest.js
https://github.com/developit/microbundle/blob/master/src/lib/transform-fast-rest.js
MIT
RestElement(path, state) { if (path.parentKey !== 'params') return; // Create a global _slice alias let slice = state.get('slice'); if (!slice) { slice = path.scope.generateUidIdentifier('slice'); state.set('slice', slice); } // _slice.call(arguments) or _slice.call(arguments, 1) const args = [t.identifier('arguments')]; if (path.key) args.push(t.numericLiteral(path.key)); const sliced = t.callExpression( t.memberExpression(t.clone(slice), t.identifier('call')), args, ); const ident = path.node.argument; const binding = path.scope.getBinding(ident.name); if (binding.referencePaths.length !== 0) { // arguments access requires a non-Arrow function: const func = path.parentPath; if (t.isArrowFunctionExpression(func)) { func.arrowFunctionToExpression(); } if ( binding.constant && binding.referencePaths.length === 1 && sameArgumentsObject(binding.referencePaths[0], func, t) ) { // one usage, never assigned - replace usage inline binding.referencePaths[0].replaceWith(sliced); } else { // unknown usage, create a binding const decl = t.variableDeclaration('var', [ t.variableDeclarator(t.clone(ident), sliced), ]); func.get('body').unshiftContainer('body', decl); } } path.remove(); }
Transform ...rest parameters to [].slice.call(arguments,offset). Demo: https://astexplorer.net/#/gist/70aaa0306db9a642171ef3e2f35df2e0/576c150f647e4936fa6960e0453a11cdc5d81f21 Benchmark: https://jsperf.com/rest-arguments-babel-pr-9152/4 @param {object} opts @param {babel.template} opts.template @param {babel.types} opts.types @returns {babel.PluginObj}
RestElement
javascript
developit/microbundle
src/lib/transform-fast-rest.js
https://github.com/developit/microbundle/blob/master/src/lib/transform-fast-rest.js
MIT
Program(path, state) { const childState = new Map(); const useHelper = state.opts.helper === true; // defaults to false if (!useHelper) { let inlineHelper; if (state.opts.literal === false) { inlineHelper = template.expression.ast`Array.prototype.slice`; } else { inlineHelper = template.expression.ast`[].slice`; } childState.set('slice', inlineHelper); } path.traverse(VISITOR, childState); const name = childState.get('slice'); if (name && useHelper) { const helper = slice({ IDENT: name }); t.addComment(helper.declarations[0].init, 'leading', '#__PURE__'); path.unshiftContainer('body', helper); } }
Transform ...rest parameters to [].slice.call(arguments,offset). Demo: https://astexplorer.net/#/gist/70aaa0306db9a642171ef3e2f35df2e0/576c150f647e4936fa6960e0453a11cdc5d81f21 Benchmark: https://jsperf.com/rest-arguments-babel-pr-9152/4 @param {object} opts @param {babel.template} opts.template @param {babel.types} opts.types @returns {babel.PluginObj}
Program
javascript
developit/microbundle
src/lib/transform-fast-rest.js
https://github.com/developit/microbundle/blob/master/src/lib/transform-fast-rest.js
MIT
function sameArgumentsObject(node, func, t) { while ((node = node.parentPath)) { if (node === func) { return true; } if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) { return false; } } return false; }
Transform ...rest parameters to [].slice.call(arguments,offset). Demo: https://astexplorer.net/#/gist/70aaa0306db9a642171ef3e2f35df2e0/576c150f647e4936fa6960e0453a11cdc5d81f21 Benchmark: https://jsperf.com/rest-arguments-babel-pr-9152/4 @param {object} opts @param {babel.template} opts.template @param {babel.types} opts.types @returns {babel.PluginObj}
sameArgumentsObject
javascript
developit/microbundle
src/lib/transform-fast-rest.js
https://github.com/developit/microbundle/blob/master/src/lib/transform-fast-rest.js
MIT
function Assertion (obj, msg, stack) { flag(this, 'ssfi', stack || arguments.callee); flag(this, 'object', obj); flag(this, 'message', msg); }
# .use(function) Provides a way to extend the internals of Chai @param {Function} @returns {this} for chaining @api public
Assertion
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function an (type, msg) { if (msg) flag(this, 'message', msg); type = type.toLowerCase(); var obj = flag(this, 'object') , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; this.assert( type === _.type(obj) , 'expected #{this} to be ' + article + type , 'expected #{this} not to be ' + article + type ); }
### .a(type) The `a` and `an` assertions are aliases that can be used either as language chains or to assert a value's type. // typeof expect('test').to.be.a('string'); expect({ foo: 'bar' }).to.be.an('object'); expect(null).to.be.a('null'); expect(undefined).to.be.an('undefined'); // language chain expect(foo).to.be.an.instanceof(Foo); @name a @alias an @param {String} type @param {String} message _optional_ @api public
an
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function includeChainingBehavior () { flag(this, 'contains', true); }
### .include(value) The `include` and `contain` assertions can be used as either property based language chains or as methods to assert the inclusion of an object in an array or a substring in a string. When used as language chains, they toggle the `contain` flag for the `keys` assertion. expect([1,2,3]).to.include(2); expect('foobar').to.contain('foo'); expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); @name include @alias contain @param {Object|String|Number} obj @param {String} message _optional_ @api public
includeChainingBehavior
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function include (val, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object') this.assert( ~obj.indexOf(val) , 'expected #{this} to include ' + _.inspect(val) , 'expected #{this} to not include ' + _.inspect(val)); }
### .include(value) The `include` and `contain` assertions can be used as either property based language chains or as methods to assert the inclusion of an object in an array or a substring in a string. When used as language chains, they toggle the `contain` flag for the `keys` assertion. expect([1,2,3]).to.include(2); expect('foobar').to.contain('foo'); expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); @name include @alias contain @param {Object|String|Number} obj @param {String} message _optional_ @api public
include
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function checkArguments () { var obj = flag(this, 'object') , type = Object.prototype.toString.call(obj); this.assert( '[object Arguments]' === type , 'expected #{this} to be arguments but got ' + type , 'expected #{this} to not be arguments' ); }
### .arguments Asserts that the target is an arguments object. function test () { expect(arguments).to.be.arguments; } @name arguments @alias Arguments @api public
checkArguments
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertEqual (val, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'deep')) { return this.eql(val); } else { this.assert( val === obj , 'expected #{this} to equal #{exp}' , 'expected #{this} to not equal #{exp}' , val , this._obj , true ); } }
### .equal(value) Asserts that the target is strictly equal (`===`) to `value`. Alternately, if the `deep` flag is set, asserts that the target is deeply equal to `value`. expect('hello').to.equal('hello'); expect(42).to.equal(42); expect(1).to.not.equal(true); expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' }); expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); @name equal @alias equals @alias eq @alias deep.equal @param {Mixed} value @param {String} message _optional_ @api public
assertEqual
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertEql(obj, msg) { if (msg) flag(this, 'message', msg); this.assert( _.eql(obj, flag(this, 'object')) , 'expected #{this} to deeply equal #{exp}' , 'expected #{this} to not deeply equal #{exp}' , obj , this._obj , true ); }
### .eql(value) Asserts that the target is deeply equal to `value`. expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]); @name eql @alias eqls @param {Mixed} value @param {String} message _optional_ @api public
assertEql
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertAbove (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len > n , 'expected #{this} to have a length above #{exp} but got #{act}' , 'expected #{this} to not have a length above #{exp}' , n , len ); } else { this.assert( obj > n , 'expected #{this} to be above ' + n , 'expected #{this} to be at most ' + n ); } }
### .above(value) Asserts that the target is greater than `value`. expect(10).to.be.above(5); Can also be used in conjunction with `length` to assert a minimum length. The benefit being a more informative error message than if the length was supplied directly. expect('foo').to.have.length.above(2); expect([ 1, 2, 3 ]).to.have.length.above(2); @name above @alias gt @alias greaterThan @param {Number} value @param {String} message _optional_ @api public
assertAbove
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertLeast (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len >= n , 'expected #{this} to have a length at least #{exp} but got #{act}' , 'expected #{this} to have a length below #{exp}' , n , len ); } else { this.assert( obj >= n , 'expected #{this} to be at least ' + n , 'expected #{this} to be below ' + n ); } }
### .least(value) Asserts that the target is greater than or equal to `value`. expect(10).to.be.at.least(10); Can also be used in conjunction with `length` to assert a minimum length. The benefit being a more informative error message than if the length was supplied directly. expect('foo').to.have.length.of.at.least(2); expect([ 1, 2, 3 ]).to.have.length.of.at.least(3); @name least @alias gte @param {Number} value @param {String} message _optional_ @api public
assertLeast
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertBelow (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len < n , 'expected #{this} to have a length below #{exp} but got #{act}' , 'expected #{this} to not have a length below #{exp}' , n , len ); } else { this.assert( obj < n , 'expected #{this} to be below ' + n , 'expected #{this} to be at least ' + n ); } }
### .below(value) Asserts that the target is less than `value`. expect(5).to.be.below(10); Can also be used in conjunction with `length` to assert a maximum length. The benefit being a more informative error message than if the length was supplied directly. expect('foo').to.have.length.below(4); expect([ 1, 2, 3 ]).to.have.length.below(4); @name below @alias lt @alias lessThan @param {Number} value @param {String} message _optional_ @api public
assertBelow
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertMost (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len <= n , 'expected #{this} to have a length at most #{exp} but got #{act}' , 'expected #{this} to have a length above #{exp}' , n , len ); } else { this.assert( obj <= n , 'expected #{this} to be at most ' + n , 'expected #{this} to be above ' + n ); } }
### .most(value) Asserts that the target is less than or equal to `value`. expect(5).to.be.at.most(5); Can also be used in conjunction with `length` to assert a maximum length. The benefit being a more informative error message than if the length was supplied directly. expect('foo').to.have.length.of.at.most(4); expect([ 1, 2, 3 ]).to.have.length.of.at.most(3); @name most @alias lte @param {Number} value @param {String} message _optional_ @api public
assertMost
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertInstanceOf (constructor, msg) { if (msg) flag(this, 'message', msg); var name = _.getName(constructor); this.assert( flag(this, 'object') instanceof constructor , 'expected #{this} to be an instance of ' + name , 'expected #{this} to not be an instance of ' + name ); }
### .instanceof(constructor) Asserts that the target is an instance of `constructor`. var Tea = function (name) { this.name = name; } , Chai = new Tea('chai'); expect(Chai).to.be.an.instanceof(Tea); expect([ 1, 2, 3 ]).to.be.instanceof(Array); @name instanceof @param {Constructor} constructor @param {String} message _optional_ @alias instanceOf @api public
assertInstanceOf
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertOwnProperty (name, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); this.assert( obj.hasOwnProperty(name) , 'expected #{this} to have own property ' + _.inspect(name) , 'expected #{this} to not have own property ' + _.inspect(name) ); }
### .ownProperty(name) Asserts that the target has an own property `name`. expect('test').to.have.ownProperty('length'); @name ownProperty @alias haveOwnProperty @param {String} name @param {String} message _optional_ @api public
assertOwnProperty
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertLengthChain () { flag(this, 'doLength', true); }
### .length(value) Asserts that the target's `length` property has the expected value. expect([ 1, 2, 3]).to.have.length(3); expect('foobar').to.have.length(6); Can also be used as a chain precursor to a value comparison for the length property. expect('foo').to.have.length.above(2); expect([ 1, 2, 3 ]).to.have.length.above(2); expect('foo').to.have.length.below(4); expect([ 1, 2, 3 ]).to.have.length.below(4); expect('foo').to.have.length.within(2,4); expect([ 1, 2, 3 ]).to.have.length.within(2,4); @name length @alias lengthOf @param {Number} length @param {String} message _optional_ @api public
assertLengthChain
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertLength (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len == n , 'expected #{this} to have a length of #{exp} but got #{act}' , 'expected #{this} to not have a length of #{act}' , n , len ); }
### .length(value) Asserts that the target's `length` property has the expected value. expect([ 1, 2, 3]).to.have.length(3); expect('foobar').to.have.length(6); Can also be used as a chain precursor to a value comparison for the length property. expect('foo').to.have.length.above(2); expect([ 1, 2, 3 ]).to.have.length.above(2); expect('foo').to.have.length.below(4); expect([ 1, 2, 3 ]).to.have.length.below(4); expect('foo').to.have.length.within(2,4); expect([ 1, 2, 3 ]).to.have.length.within(2,4); @name length @alias lengthOf @param {Number} length @param {String} message _optional_ @api public
assertLength
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function assertKeys (keys) { var obj = flag(this, 'object') , str , ok = true; keys = keys instanceof Array ? keys : Array.prototype.slice.call(arguments); if (!keys.length) throw new Error('keys required'); var actual = Object.keys(obj) , len = keys.length; // Inclusion ok = keys.every(function(key){ return ~actual.indexOf(key); }); // Strict if (!flag(this, 'negate') && !flag(this, 'contains')) { ok = ok && keys.length == actual.length; } // Key string if (len > 1) { keys = keys.map(function(key){ return _.inspect(key); }); var last = keys.pop(); str = keys.join(', ') + ', and ' + last; } else { str = _.inspect(keys[0]); } // Form str = (len > 1 ? 'keys ' : 'key ') + str; // Have / include str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; // Assertion this.assert( ok , 'expected #{this} to ' + str , 'expected #{this} to not ' + str ); }
### .keys(key1, [key2], [...]) Asserts that the target has exactly the given keys, or asserts the inclusion of some keys when using the `include` or `contain` modifiers. expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']); expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar'); @name keys @alias key @param {String...|Array} keys @api public
assertKeys
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function AssertionError (options) { options = options || {}; this.message = options.message; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; this.showDiff = options.showDiff; if (options.stackStartFunction && Error.captureStackTrace) { var stackStartFunction = options.stackStartFunction; Error.captureStackTrace(this, stackStartFunction); } }
# AssertionError (constructor) Create a new assertion error based on the Javascript `Error` prototype. **Options** - message - actual - expected - operator - startStackFunction @param {Object} options @api public
AssertionError
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function loadShould () { // modify Object.prototype to have `should` Object.defineProperty(Object.prototype, 'should', { set: function (value) { // See https://github.com/chaijs/chai/issues/86: this makes // `whatever.should = someValue` actually set `someValue`, which is // especially useful for `global.should = require('chai').should()`. // // Note that we have to use [[DefineProperty]] instead of [[Put]] // since otherwise we would trigger this very setter! Object.defineProperty(this, 'should', { value: value, enumerable: true, configurable: true, writable: true }); } , get: function(){ if (this instanceof String || this instanceof Number) { return new Assertion(this.constructor(this)); } else if (this instanceof Boolean) { return new Assertion(this == true); } return new Assertion(this); } , configurable: true }); var should = {}; should.equal = function (val1, val2, msg) { new Assertion(val1, msg).to.equal(val2); }; should.Throw = function (fn, errt, errs, msg) { new Assertion(fn, msg).to.Throw(errt, errs); }; should.exist = function (val, msg) { new Assertion(val, msg).to.exist; } // negation should.not = {} should.not.equal = function (val1, val2, msg) { new Assertion(val1, msg).to.not.equal(val2); }; should.not.Throw = function (fn, errt, errs, msg) { new Assertion(fn, msg).to.not.Throw(errt, errs); }; should.not.exist = function (val, msg) { new Assertion(val, msg).to.not.exist; } should['throw'] = should['Throw']; should.not['throw'] = should.not['Throw']; return should; }
### .closeTo(actual, expected, delta, [message]) Asserts that the target is equal `expected`, to within a +/- `delta` range. assert.closeTo(1.5, 1, 0.5, 'numbers are close'); @name closeTo @param {Number} actual @param {Number} expected @param {Number} delta @param {String} message @api public
loadShould
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
assert = function () { var result = method.apply(this, arguments); return result === undefined ? this : result; }
### addChainableMethod (ctx, name, method, chainingBehavior) Adds a method to an object, such that the method can also be chained. utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { var obj = utils.flag(this, 'object'); new chai.Assertion(obj).to.be.equal(str); }); Can also be accessed directly from `chai.Assertion`. chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); The result can then be used as both a method assertion, executing both `method` and `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. expect(fooStr).to.be.foo('bar'); expect(fooStr).to.be.foo.equal('foo'); @param {Object} ctx object to which the method is added @param {String} name of method to add @param {Function} method function to be used for `name`, when called @param {Function} chainingBehavior function to be called every time the property is accessed @name addChainableMethod @api public
assert
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function _deepEqual(actual, expected, memos) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (actual instanceof Date && expected instanceof Date) { return actual.getTime() === expected.getTime(); // 7.3. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (typeof actual != 'object' && typeof expected != 'object') { return actual === expected; // 7.4. For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected, memos); } }
### addProperty (ctx, name, getter) Adds a property to the prototype of an object. utils.addProperty(chai.Assertion.prototype, 'foo', function () { var obj = utils.flag(this, 'object'); new chai.Assertion(obj).to.be.instanceof(Foo); }); Can also be accessed directly from `chai.Assertion`. chai.Assertion.addProperty('foo', fn); Then can be used as any other assertion. expect(myFoo).to.be.foo; @param {Object} ctx object to which the property is added @param {String} name of property to add @param {Function} getter function to be used for name @name addProperty @api public
_deepEqual
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function isUndefinedOrNull(value) { return value === null || value === undefined; }
### addProperty (ctx, name, getter) Adds a property to the prototype of an object. utils.addProperty(chai.Assertion.prototype, 'foo', function () { var obj = utils.flag(this, 'object'); new chai.Assertion(obj).to.be.instanceof(Foo); }); Can also be accessed directly from `chai.Assertion`. chai.Assertion.addProperty('foo', fn); Then can be used as any other assertion. expect(myFoo).to.be.foo; @param {Object} ctx object to which the property is added @param {String} name of property to add @param {Function} getter function to be used for name @name addProperty @api public
isUndefinedOrNull
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; }
### addProperty (ctx, name, getter) Adds a property to the prototype of an object. utils.addProperty(chai.Assertion.prototype, 'foo', function () { var obj = utils.flag(this, 'object'); new chai.Assertion(obj).to.be.instanceof(Foo); }); Can also be accessed directly from `chai.Assertion`. chai.Assertion.addProperty('foo', fn); Then can be used as any other assertion. expect(myFoo).to.be.foo; @param {Object} ctx object to which the property is added @param {String} name of property to add @param {Function} getter function to be used for name @name addProperty @api public
isArguments
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function objEquiv(a, b, memos) { if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; // check if we have already compared a and b var i; if (memos) { for(i = 0; i < memos.length; i++) { if ((memos[i][0] === a && memos[i][1] === b) || (memos[i][0] === b && memos[i][1] === a)) return true; } } else { memos = []; } //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b, memos); } try { var ka = getEnumerableProperties(a), kb = getEnumerableProperties(b), key; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } // remember objects we have compared to guard against circular references memos.push([ a, b ]); //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], memos)) return false; } return true; }
### addProperty (ctx, name, getter) Adds a property to the prototype of an object. utils.addProperty(chai.Assertion.prototype, 'foo', function () { var obj = utils.flag(this, 'object'); new chai.Assertion(obj).to.be.instanceof(Foo); }); Can also be accessed directly from `chai.Assertion`. chai.Assertion.addProperty('foo', fn); Then can be used as any other assertion. expect(myFoo).to.be.foo; @param {Object} ctx object to which the property is added @param {String} name of property to add @param {Function} getter function to be used for name @name addProperty @api public
objEquiv
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function parsePath (path) { var str = path.replace(/\[/g, '.[') , parts = str.match(/(\\\.|[^.]+?)+/g); return parts.map(function (value) { var re = /\[(\d+)\]$/ , mArr = re.exec(value) if (mArr) return { i: parseFloat(mArr[1]) }; else return { p: value }; }); }
### .getPathValue(path, object) This allows the retrieval of values in an object given a string path. var obj = { prop1: { arr: ['a', 'b', 'c'] , str: 'Hello' } , prop2: { arr: [ { nested: 'Universe' } ] , str: 'Hello again!' } } The following would be the results. getPathValue('prop1.str', obj); // Hello getPathValue('prop1.att[2]', obj); // b getPathValue('prop2.arr[0].nested', obj); // Universe @param {String} path @param {Object} object @returns {Object} value or `undefined` @name getPathValue @api public
parsePath
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function _getPathValue (parsed, obj) { var tmp = obj , res; for (var i = 0, l = parsed.length; i < l; i++) { var part = parsed[i]; if (tmp) { if ('undefined' !== typeof part.p) tmp = tmp[part.p]; else if ('undefined' !== typeof part.i) tmp = tmp[part.i]; if (i == (l - 1)) res = tmp; } else { res = undefined; } } return res; }
### .getPathValue(path, object) This allows the retrieval of values in an object given a string path. var obj = { prop1: { arr: ['a', 'b', 'c'] , str: 'Hello' } , prop2: { arr: [ { nested: 'Universe' } ] , str: 'Hello again!' } } The following would be the results. getPathValue('prop1.str', obj); // Hello getPathValue('prop1.att[2]', obj); // b getPathValue('prop2.arr[0].nested', obj); // Universe @param {String} path @param {Object} object @returns {Object} value or `undefined` @name getPathValue @api public
_getPathValue
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function addProperty(property) { if (result.indexOf(property) === -1) { result.push(property); } }
### .getProperties(object) This allows the retrieval of property names of an object, enumerable or not, inherited or not. @param {Object} object @returns {Array} @name getProperties @api public
addProperty
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function inspect(obj, showHidden, depth, colors) { var ctx = { showHidden: showHidden, seen: [], stylize: function (str) { return str; } }; return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
inspect
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
getOuterHTML = function(element) { if ('outerHTML' in element) return element.outerHTML; var ns = "http://www.w3.org/1999/xhtml"; var container = document.createElementNS(ns, '_'); var elemProto = (window.HTMLElement || window.Element).prototype; var xmlSerializer = new XMLSerializer(); var html; if (document.xmlVersion) { return xmlSerializer.serializeToString(element); } else { container.appendChild(element.cloneNode(false)); html = container.innerHTML.replace('><', '>' + element.innerHTML + '<'); container.innerHTML = ''; return html; } }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
getOuterHTML
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
isDOMElement = function (object) { if (typeof HTMLElement === 'object') { return object instanceof HTMLElement; } else { return object && typeof object === 'object' && object.nodeType === 1 && typeof object.nodeName === 'string'; } }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
isDOMElement
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (value && typeof value.inspect === 'function' && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { return value.inspect(recurseTimes); } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // If it's DOM elem, get outer HTML. if (isDOMElement(value)) { return getOuterHTML(value); } // Look up the keys of the object. var visibleKeys = getEnumerableProperties(value); var keys = ctx.showHidden ? getProperties(value) : visibleKeys; // Some type of object without properties can be shortcutted. // In IE, errors have a single `stack` property, or if they are vanilla `Error`, // a `stack` plus `description` property; ignore those for consistency. if (keys.length === 0 || (isError(value) && ( (keys.length === 1 && keys[0] === 'stack') || (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') ))) { if (typeof value === 'function') { var name = getName(value); var nameSuffix = name ? ': ' + name : ''; return ctx.stylize('[Function' + nameSuffix + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (typeof value === 'function') { var name = getName(value); var nameSuffix = name ? ': ' + name : ''; base = ' [Function' + nameSuffix + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { return formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
formatValue
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function formatPrimitive(ctx, value) { switch (typeof value) { case 'undefined': return ctx.stylize('undefined', 'undefined'); case 'string': var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); case 'number': return ctx.stylize('' + value, 'number'); case 'boolean': return ctx.stylize('' + value, 'boolean'); } // For some reason typeof null is "object", so special case here. if (value === null) { return ctx.stylize('null', 'null'); } }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
formatPrimitive
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
formatError
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (Object.prototype.hasOwnProperty.call(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
formatArray
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str; if (value.__lookupGetter__) { if (value.__lookupGetter__(key)) { if (value.__lookupSetter__(key)) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (value.__lookupSetter__(key)) { str = ctx.stylize('[Setter]', 'special'); } } } if (visibleKeys.indexOf(key) < 0) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(value[key]) < 0) { if (recurseTimes === null) { str = formatValue(ctx, value[key], null); } else { str = formatValue(ctx, value[key], recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (typeof name === 'undefined') { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
formatProperty
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
reduceToSingleString
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function isArray(ar) { return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]'); }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
isArray
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function isRegExp(re) { return typeof re === 'object' && objectToString(re) === '[object RegExp]'; }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
isRegExp
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function isDate(d) { return typeof d === 'object' && objectToString(d) === '[object Date]'; }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
isDate
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
function isError(e) { return typeof e === 'object' && objectToString(e) === '[object Error]'; }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. @param {Number} depth Depth in which to descend in object. Default is 2. @param {Boolean} colors Flag to turn on ANSI escape codes to color the output. Default is false (no coloring).
isError
javascript
dobtco/formbuilder
test/vendor/js/chai.js
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
MIT
End of preview. Expand in Data Studio

Javascript CodeSearch Dataset (Shuu12121/javascript-treesitter-filtered-datasetsV2)

Dataset Description

This dataset contains JavaScript functions and methods paired with their JSDoc comments, extracted from open-source JavaScript repositories on GitHub. It is formatted similarly to the CodeSearchNet challenge dataset.

Each entry includes:

  • code: The source code of a javascript function or method.
  • docstring: The docstring or Javadoc associated with the function/method.
  • func_name: The name of the function/method.
  • language: The programming language (always "javascript").
  • repo: The GitHub repository from which the code was sourced (e.g., "owner/repo").
  • path: The file path within the repository where the function/method is located.
  • url: A direct URL to the function/method's source file on GitHub (approximated to master/main branch).
  • license: The SPDX identifier of the license governing the source repository (e.g., "MIT", "Apache-2.0"). Additional metrics if available (from Lizard tool):
  • ccn: Cyclomatic Complexity Number.
  • params: Number of parameters of the function/method.
  • nloc: Non-commenting lines of code.
  • token_count: Number of tokens in the function/method.

Dataset Structure

The dataset is divided into the following splits:

  • train: 703,354 examples
  • validation: 41,899 examples
  • test: 17,138 examples

Data Collection

The data was collected by:

  1. Identifying popular and relevant Javascript repositories on GitHub.
  2. Cloning these repositories.
  3. Parsing Javascript files (.js) using tree-sitter to extract functions/methods and their docstrings/Javadoc.
  4. Filtering functions/methods based on code length and presence of a non-empty docstring/Javadoc.
  5. Using the lizard tool to calculate code metrics (CCN, NLOC, params).
  6. Storing the extracted data in JSONL format, including repository and license information.
  7. Splitting the data by repository to ensure no data leakage between train, validation, and test sets.

Intended Use

This dataset can be used for tasks such as:

  • Training and evaluating models for code search (natural language to code).
  • Code summarization / docstring generation (code to natural language).
  • Studies on Javascript code practices and documentation habits.

Licensing

The code examples within this dataset are sourced from repositories with permissive licenses (typically MIT, Apache-2.0, BSD). Each sample includes its original license information in the license field. The dataset compilation itself is provided under a permissive license (e.g., MIT or CC-BY-SA-4.0), but users should respect the original licenses of the underlying code.

Example Usage

from datasets import load_dataset

# Load the dataset
dataset = load_dataset("Shuu12121/javascript-treesitter-filtered-datasetsV2")

# Access a split (e.g., train)
train_data = dataset["train"]

# Print the first example
print(train_data[0])
Downloads last month
44

Models trained or fine-tuned on Shuu12121/javascript-treesitter-filtered-datasetsV2

Collection including Shuu12121/javascript-treesitter-filtered-datasetsV2