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
_wordRelativeTo(char, options) { let textChars = this.replica.getTextRange(BASE_CHAR) let charIndex = textChars.findIndex(e => charEq(e, char)) + 1 let tokenRanges = tokenizer(textChars.map(c => c.char), options) for(let i = 0; i < tokenRanges.length; i++) { if(charIndex >= tokenRanges[i].start && charIndex < tokenRanges[i].end) { return { start: tokenRanges[i].start === 0 ? BASE_CHAR : textChars[tokenRanges[i].start - 1], end: textChars[tokenRanges[i].end - 1] } } } // if charIndex == last token range end let last = tokenRanges.length - 1 return { start: tokenRanges[last].start === 0 ? BASE_CHAR : textChars[tokenRanges[last].start - 1], end: textChars[tokenRanges[last].end - 1] } }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_wordRelativeTo
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_wordStartRelativeTo(char, options) { let textChars = this.replica.getTextRange(BASE_CHAR, char) let tokenRanges = tokenizer(textChars.map(c => c.char), options) if(tokenRanges.length > 0) { let start = tokenRanges[tokenRanges.length - 1].start return start < 1 ? BASE_CHAR : textChars[start - 1] } else { return BASE_CHAR } }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_wordStartRelativeTo
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_wordEndRelativeTo(char, options) { let textChars = this.replica.getTextRange(char) let tokenRanges = tokenizer(textChars.map(c => c.char), options) if(tokenRanges.length > 0) { let end = tokenRanges[0].end return textChars[end - 1] } else { return this._cursorAtEnd() ? EOF : this._relativeChar(BASE_CHAR, -1) } }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_wordEndRelativeTo
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_eraseSelection() { invariant(this.state.selectionActive, 'Selection must be active to erase it.') let position = this.state.selectionLeftChar let selectionChars = this.replica.getTextRange(this.state.selectionLeftChar, this.state.selectionRightChar) this.replica.rmChars(selectionChars) this._flow({ start: this.state.selectionLeftChar, end: this.state.selectionRightChar, action: ACTION_DELETE}) if(this.config.eventEmitter.hasListeners('text-delete')) { this.config.eventEmitter.emit('text-delete', this.state.selectionLeftChar, this.state.selectionRightChar, position) } let endOfLine = lineContainingChar(this.state.lines, position).endOfLine this._setPosition(position, endOfLine) this._updateRemoteCursorSelectionsLocally() }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_eraseSelection
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_navigateLeftRight(charCount) { let position if(this._emptyEditor()) { this._resetPosition() return } if(this.state.selectionActive && charCount < 0) { // left from left char position = this.state.selectionLeftChar } else if(this.state.selectionActive) { // right from right char position = this.state.selectionRightChar } else { position = this._relativeChar(this.state.position, charCount, 'limit') } let endOfLine = lineContainingChar(this.state.lines, position).endOfLine this._setPosition(position, endOfLine) }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_navigateLeftRight
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_navigateUpDown(lineCount) { if(this._emptyEditor()) { this._resetPosition() return } if(this.state.selectionActive) { // collapse the selection and position the cursor relative to the left (if up) or right (if down) let position let positionEolStart if(lineCount < 0) { position = this.state.selectionLeftChar positionEolStart = true } else if(this.state.selectionActive) { position = this.state.selectionRightChar positionEolStart = false } this._setPosition(position, positionEolStart) } let upDownAdvanceX = this.upDownAdvanceX let positionEolStart = this.upDownPositionEolStart let currentLineAndAdvance = this._lineAndAdvanceAtPosition(this.state.position, this.state.positionEolStart) let index = currentLineAndAdvance.index if(this.upDownAdvanceX == null || this.upDownPositionEolStart == null) { upDownAdvanceX = currentLineAndAdvance.advanceX positionEolStart = this.state.positionEolStart // save the advance and positionEolStart in case the user navigates up or down again this.upDownAdvanceX = upDownAdvanceX this.upDownPositionEolStart = positionEolStart } let targetIndex = index + lineCount let targetLine if(targetIndex < 0 || targetIndex > this.state.lines.length - 1) { if(targetIndex < 0 && index !== 0) { targetLine = this.state.lines[0] } else if(targetIndex > this.state.lines.length - 1 && index !== this.state.lines.length - 1) { targetLine = this.state.lines[this.state.lines.length - 1] } else { // nowhere to go, just unblink for a second to indicate to the user input was received this._delayedCursorBlink() } } else { targetLine = this.state.lines[targetIndex] } if(targetLine) { let newPosition if(targetLine.isEof()) { newPosition = targetLine.start positionEolStart = true } else { let chars = targetLine.chars let indexAndCursor = TextFontMetrics.indexAndCursorForXValue(this.config.fontSize, upDownAdvanceX, chars) newPosition = this._charPositionRelativeToIndex(indexAndCursor.index, chars) // if the new position is the start of the line, position the cursor at the start of the line positionEolStart = charEq(newPosition, targetLine.start) } this._setPosition(newPosition, positionEolStart, false) } }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_navigateUpDown
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_navigateWordLeftRight(wordCount) { let position if(this._emptyEditor()) { this._resetPosition() return } if(this.state.selectionActive && wordCount < 0) { // start from one character into the selection left char so that relative to the left selected word position = this._relativeChar(this.state.selectionLeftChar, 1, 'limit') } else if(this.state.selectionActive) { // start from one character before the selection right char so that relative to the right selected word position = this._relativeChar(this.state.selectionRightChar, -1, 'limit') } else { position = this.state.position } let relativeTo = _.bind(wordCount < 0 ? this._wordStartRelativeTo : this._wordEndRelativeTo, this) position = relativeTo(position) let endOfLine = lineContainingChar(this.state.lines, position).endOfLine this._setPosition(position, endOfLine) }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_navigateWordLeftRight
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_selectionLeftRight(charCount) { let endOfLine = lineContainingChar(this.state.lines, this.state.position).endOfLine let toChar = this._relativeChar(this.state.position, charCount, 'eof') if(toChar === EOF && this._lastLine() && !this._lastLine().isEof()) { toChar = this._lastLine().end } this._modifySelection(toChar, (this.state.position === EOF && charCount === -1) || !endOfLine) this.setActiveAttributes() }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_selectionLeftRight
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_selectionUpDown(lineCount) { let upDownAdvanceX = this.upDownAdvanceX let positionEolStart = this.upDownPositionEolStart let currentLineAndAdvance = this._lineAndAdvanceAtPosition(this.state.position, this.state.positionEolStart) let line = currentLineAndAdvance.line let index = currentLineAndAdvance.index if(this.upDownAdvanceX == null || this.upDownPositionEolStart == null) { upDownAdvanceX = currentLineAndAdvance.advanceX positionEolStart = this.state.positionEolStart // save the advance and positionEolStart in case the user navigates up or down again this.upDownAdvanceX = upDownAdvanceX this.upDownPositionEolStart = positionEolStart } let targetIndex = index + lineCount if(targetIndex < 0) { this._modifySelection(BASE_CHAR, true) // at start of first line, reset the advanceX, and positionEolStart is now true this.upDownAdvanceX = 0 this.upDownPositionEolStart = true } else if(targetIndex > this.state.lines.length - 1 && !this._lastLine().isEof()) { // trying to navigate past the last line (and last line does not have an EOF), position at end of line let toChar = this._relativeChar(BASE_CHAR, -1) this._modifySelection(toChar, false) // at end of last line, reset the advanceX to the end of the line, and positionEolStart is now false let chars = line.chars this.upDownAdvanceX = TextFontMetrics.advanceXForChars(this.config.fontSize, chars) this.upDownPositionEolStart = false } else if(targetIndex >= this.state.lines.length - 1 && this._lastLine().isEof()) { this._modifySelection(EOF, true, false) } else if(this._emptyEditor()) { this._resetPosition() } else { let targetLine = this.state.lines[targetIndex] let newPosition if(targetLine.isEof()) { newPosition = targetLine.start positionEolStart = true } else { let chars = targetLine.chars let indexAndCursor = TextFontMetrics.indexAndCursorForXValue(this.config.fontSize, upDownAdvanceX, chars) newPosition = this._charPositionRelativeToIndex(indexAndCursor.index, chars) // if the new position is the start of the line, position the cursor at the start of the line positionEolStart = charEq(newPosition, targetLine.start) } this._modifySelection(newPosition, positionEolStart, false) } this.setActiveAttributes() }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_selectionUpDown
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_toggleAttribute(attribute, exclusiveWith) { if(this.state.selectionActive) { let selectionChars = this.replica.getTextRange(this.state.selectionLeftChar, this.state.selectionRightChar) let charsWithAttrNotSet = selectionChars.filter(c => !c.attributes || !c.attributes[attribute]) let setAttr = {} if(charsWithAttrNotSet && charsWithAttrNotSet.length > 0) { let attr = {} attr[attribute] = true for(let i = 0; i < charsWithAttrNotSet.length; i++) { let currentAttrs = charsWithAttrNotSet[i].copyOfAttributes() if(exclusiveWith && currentAttrs && currentAttrs[exclusiveWith]) delete currentAttrs[exclusiveWith] setAttr[charsWithAttrNotSet[i].id] = currentAttrs ? _.merge(currentAttrs, attr) : attr } } else { for(let i = 0; i < selectionChars.length; i++) { let currentAttrs = selectionChars[i].copyOfAttributes() delete currentAttrs[attribute] if(_.isEmpty(currentAttrs)) { currentAttrs = null } setAttr[selectionChars[i].id] = currentAttrs } } this.replica.setAttributes(setAttr) this.setActiveAttributes() this._flow({ start: this.state.selectionLeftChar, end: this.state.selectionRightChar, action: ACTION_ATTRIBUTES}) } else { // no selection so we are either toggling the explicitly set state, or setting the state explicitly let activeAttributes = this.state.activeAttributes ? _.clone(this.state.activeAttributes) : {} if(activeAttributes[attribute]) { delete activeAttributes[attribute] } else { activeAttributes[attribute] = true } if(activeAttributes && activeAttributes[attribute] && exclusiveWith && activeAttributes[exclusiveWith]) { delete activeAttributes[exclusiveWith] } this.setState({activeAttributes: activeAttributes}) } }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_toggleAttribute
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_lineAndAdvanceAtPosition(position, positionEolStart) { let {line, index, endOfLine} = lineContainingChar(this.state.lines, position, positionEolStart) let advanceX if(charEq(BASE_CHAR, position) || (endOfLine && positionEolStart)) { advanceX = 0 } else { let chars = line.charsTo(position) advanceX = TextFontMetrics.advanceXForChars(this.config.fontSize, chars) } return { advanceX: advanceX, line: line, index: index, endOfLine: endOfLine } }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_lineAndAdvanceAtPosition
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
_coordinatesToPosition({x, y}) { // TODO this works for now since all line heights are the same, but get the heights of each line dynamically let lineHeight = TextFontMetrics.lineHeight(this.config.fontSize) let lineIndex = Math.floor(y / lineHeight) if(lineIndex < 0) { // clicked before the first line, set cursor on the first line lineIndex = 0 } else if (lineIndex > this.state.lines.length - 1) { // clicked after the last line, set cursor on the last line lineIndex = this.state.lines.length - 1 } let line = this.state.lines[lineIndex] let position let positionEolStart if(!line) { position = BASE_CHAR positionEolStart = false } else if(line.isEof()) { position = line.start positionEolStart = true } else { let indexAndCursor = TextFontMetrics.indexAndCursorForXValue(this.config.fontSize, x, line.chars) position = this._charPositionRelativeToIndex(indexAndCursor.index, line.chars) // if clicked a line beginning (char position is end of last line) then position beginning of clicked line // note that the cursorX is relative to the beginning of the line let cursorX = indexAndCursor.cursorX positionEolStart = cursorX === 0 || line.isEof() } return { position: position, positionEolStart: positionEolStart } }
Sets the character and cursor position within the text. The position is relative to an existing character given by its replica id. The cursor position is calculated based on the character position. This is generally straightforward except when the character position is the last character of a line. In this situation, there are two possible cursor positions: at the end of the line, or at the beginning of the next line. The desired cursor location depends on how one got there e.g. hitting "end" on a line should keep you on the same line, hitting "home" on the next line takes you to the same character position, except at the beginning of that line. @param {object} position The character position to set. @param {boolean} [positionEolStart = true] positionEolStart When rendering the cursor, this state determines the cursor position when the character position is at a line end: whether to place the cursor at the start of the next line (positionEolStart = true), or at the end of the current one (positionEolStart = false). If the cursor position is not at a line end, this state is ignored by the renderer. Since this state is often "left over" from previous calls to _setPosition it should not be trusted other than for rendering. @param {boolean} [resetUpDown = true] resetUpDown Whether to reset the up/down advance and position values.
_coordinatesToPosition
javascript
ritzyed/ritzy
src/flux/EditorStore.js
https://github.com/ritzyed/ritzy/blob/master/src/flux/EditorStore.js
Apache-2.0
function RedisStorage (options) { Storage.call(this); this.options = options; this._host = null; // will be set by the Host this.redis = options.redis; this.redisConnectParams = options.redisConnectParams || { unixSocket: undefined, port: 6379, host: '127.0.0.1', options: {} }; this.db = null; this.logtails = {}; }
Adaptor for Redis @param {{redis:object, redisConnectParams:{unixSocket:string?, port:number?, host:string?, options:object}}} options <code> var storage = new Swarm.RedisStorage('dummy', { redis: require('redis'), redisConnectParams: { port: 6379, host: '127.0.0.1', options: {} } }); storage.open(callback); </code> @TODO storage opening by host
RedisStorage
javascript
ritzyed/ritzy
src/vendor/swarm/RedisStorage.js
https://github.com/ritzyed/ritzy/blob/master/src/vendor/swarm/RedisStorage.js
Apache-2.0
function reducer(state, action) { /* istanbul ignore next */ switch (action.type) { case "focus": return { ...state, isFocused: true, }; case "blur": return { ...state, isFocused: false, }; case "openDialog": return { ...initialState, isFileDialogActive: true, }; case "closeDialog": return { ...state, isFileDialogActive: false, }; case "setDraggedFiles": return { ...state, isDragActive: action.isDragActive, isDragAccept: action.isDragAccept, isDragReject: action.isDragReject, }; case "setFiles": return { ...state, acceptedFiles: action.acceptedFiles, fileRejections: action.fileRejections, isDragReject: action.isDragReject, }; case "reset": return { ...initialState, }; default: return state; } }
@param {DropzoneState} state @param {{type: string} & DropzoneState} action @returns {DropzoneState}
reducer
javascript
react-dropzone/react-dropzone
src/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/index.js
MIT
function drainPendingTimers() { return act(() => jest.runOnlyPendingTimers()); }
drainPendingTimers just runs pending timers wrapped in act() to avoid getting warnings from react about side effects that happen async. This can be used whenever a setTimeout(), setInterval() or async operation is used which triggers a state update.
drainPendingTimers
javascript
react-dropzone/react-dropzone
src/index.spec.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/index.spec.js
MIT
function focusWindow() { return fireEvent.focus(document.body, { bubbles: true }); }
focusWindow triggers focus on the window
focusWindow
javascript
react-dropzone/react-dropzone
src/index.spec.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/index.spec.js
MIT
function createDtWithFiles(files = []) { return { dataTransfer: { files, items: files.map((file) => ({ kind: "file", size: file.size, type: file.type, getAsFile: () => file, })), types: ["Files"], }, }; }
createDtWithFiles creates a mock data transfer object that can be used for drop events @param {File[]} files
createDtWithFiles
javascript
react-dropzone/react-dropzone
src/index.spec.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/index.spec.js
MIT
function createFile(name, size, type) { const file = new File([], name, { type }); Object.defineProperty(file, "size", { get() { return size; }, }); return file; }
createFile creates a mock File object @param {string} name @param {number} size @param {string} type
createFile
javascript
react-dropzone/react-dropzone
src/index.spec.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/index.spec.js
MIT
get() { return size; }
createFile creates a mock File object @param {string} name @param {number} size @param {string} type
get
javascript
react-dropzone/react-dropzone
src/index.spec.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/index.spec.js
MIT
function createThenable() { let done, cancel; const promise = new Promise((resolve, reject) => { done = resolve; cancel = reject; }); return { promise, done, cancel, }; }
createThenable creates a Promise that can be controlled from outside its inner scope
createThenable
javascript
react-dropzone/react-dropzone
src/index.spec.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/index.spec.js
MIT
function fileAccepted(file, accept) { const isAcceptable = file.type === "application/x-moz-file" || accepts(file, accept); return [ isAcceptable, isAcceptable ? null : getInvalidTypeRejectionErr(accept), ]; }
Check if file is accepted. Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with that MIME type will always be accepted. @param {File} file @param {string} accept @returns
fileAccepted
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function fileMatchSize(file, minSize, maxSize) { if (isDefined(file.size)) { if (isDefined(minSize) && isDefined(maxSize)) { if (file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)]; if (file.size < minSize) return [false, getTooSmallRejectionErr(minSize)]; } else if (isDefined(minSize) && file.size < minSize) return [false, getTooSmallRejectionErr(minSize)]; else if (isDefined(maxSize) && file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)]; } return [true, null]; }
Check if file is accepted. Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with that MIME type will always be accepted. @param {File} file @param {string} accept @returns
fileMatchSize
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function isDefined(value) { return value !== undefined && value !== null; }
Check if file is accepted. Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with that MIME type will always be accepted. @param {File} file @param {string} accept @returns
isDefined
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function allFilesAccepted({ files, accept, minSize, maxSize, multiple, maxFiles, validator, }) { if ( (!multiple && files.length > 1) || (multiple && maxFiles >= 1 && files.length > maxFiles) ) { return false; } return files.every((file) => { const [accepted] = fileAccepted(file, accept); const [sizeMatch] = fileMatchSize(file, minSize, maxSize); const customErrors = validator ? validator(file) : null; return accepted && sizeMatch && !customErrors; }); }
@param {object} options @param {File[]} options.files @param {string} [options.accept] @param {number} [options.minSize] @param {number} [options.maxSize] @param {boolean} [options.multiple] @param {number} [options.maxFiles] @param {(f: File) => FileError|FileError[]|null} [options.validator] @returns
allFilesAccepted
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function isPropagationStopped(event) { if (typeof event.isPropagationStopped === "function") { return event.isPropagationStopped(); } else if (typeof event.cancelBubble !== "undefined") { return event.cancelBubble; } return false; }
@param {object} options @param {File[]} options.files @param {string} [options.accept] @param {number} [options.minSize] @param {number} [options.maxSize] @param {boolean} [options.multiple] @param {number} [options.maxFiles] @param {(f: File) => FileError|FileError[]|null} [options.validator] @returns
isPropagationStopped
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function isEvtWithFiles(event) { if (!event.dataTransfer) { return !!event.target && !!event.target.files; } // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file return Array.prototype.some.call( event.dataTransfer.types, (type) => type === "Files" || type === "application/x-moz-file" ); }
@param {object} options @param {File[]} options.files @param {string} [options.accept] @param {number} [options.minSize] @param {number} [options.maxSize] @param {boolean} [options.multiple] @param {number} [options.maxFiles] @param {(f: File) => FileError|FileError[]|null} [options.validator] @returns
isEvtWithFiles
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function isKindFile(item) { return typeof item === "object" && item !== null && item.kind === "file"; }
@param {object} options @param {File[]} options.files @param {string} [options.accept] @param {number} [options.minSize] @param {number} [options.maxSize] @param {boolean} [options.multiple] @param {number} [options.maxFiles] @param {(f: File) => FileError|FileError[]|null} [options.validator] @returns
isKindFile
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function isIe(userAgent) { return ( userAgent.indexOf("MSIE") !== -1 || userAgent.indexOf("Trident/") !== -1 ); }
@param {object} options @param {File[]} options.files @param {string} [options.accept] @param {number} [options.minSize] @param {number} [options.maxSize] @param {boolean} [options.multiple] @param {number} [options.maxFiles] @param {(f: File) => FileError|FileError[]|null} [options.validator] @returns
isIe
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function isEdge(userAgent) { return userAgent.indexOf("Edge/") !== -1; }
@param {object} options @param {File[]} options.files @param {string} [options.accept] @param {number} [options.minSize] @param {number} [options.maxSize] @param {boolean} [options.multiple] @param {number} [options.maxFiles] @param {(f: File) => FileError|FileError[]|null} [options.validator] @returns
isEdge
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function isIeOrEdge(userAgent = window.navigator.userAgent) { return isIe(userAgent) || isEdge(userAgent); }
@param {object} options @param {File[]} options.files @param {string} [options.accept] @param {number} [options.minSize] @param {number} [options.maxSize] @param {boolean} [options.multiple] @param {number} [options.maxFiles] @param {(f: File) => FileError|FileError[]|null} [options.validator] @returns
isIeOrEdge
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function composeEventHandlers(...fns) { return (event, ...args) => fns.some((fn) => { if (!isPropagationStopped(event) && fn) { fn(event, ...args); } return isPropagationStopped(event); }); }
This is intended to be used to compose event handlers They are executed in order until one of them calls `event.isPropagationStopped()`. Note that the check is done on the first invoke too, meaning that if propagation was stopped before invoking the fns, no handlers will be executed. @param {Function} fns the event hanlder functions @return {Function} the event handler to add to an element
composeEventHandlers
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function acceptPropAsAcceptAttr(accept) { if (isDefined(accept)) { return ( Object.entries(accept) .reduce((a, [mimeType, ext]) => [...a, mimeType, ...ext], []) // Silently discard invalid entries as pickerOptionsFromAccept warns about these .filter((v) => isMIMEType(v) || isExt(v)) .join(",") ); } return undefined; }
Convert the `{accept}` dropzone prop to an array of MIME types/extensions. @param {AcceptProp} accept @returns {string}
acceptPropAsAcceptAttr
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function isExt(v) { return /^.*\.[\w]+$/.test(v); }
Check if v is a file extension. @param {string} v
isExt
javascript
react-dropzone/react-dropzone
src/utils/index.js
https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
MIT
function Fast (value) { if (!(this instanceof Fast)) { return new Fast(value); } this.value = value || []; }
# Constructor Provided as a convenient wrapper around Fast functions. ```js var arr = fast([1,2,3,4,5,6]); var result = arr.filter(function (item) { return item % 2 === 0; }); result instanceof Fast; // true result.length; // 3 ``` @param {Array} value The value to wrap.
Fast
javascript
codemix/fast.js
index.js
https://github.com/codemix/fast.js/blob/master/index.js
MIT
function modObj (obj) { obj['wat' + Math.floor(Math.random() * 10000)] = Math.random(); return obj; }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
modObj
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function modObj (obj) { obj['wat' + Math.floor(Math.random() * 10000)] = Math.random(); return obj; }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
modObj
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function modObj (obj) { obj['wat' + Math.floor(Math.random() * 10000)] = Math.random(); return obj; }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
modObj
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
input = function (a, b, c) { return a + b + c * Math.random(); }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
input
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function run (benchmarks) { var index = -1, length = benchmarks.length, startTime = Date.now(); console.log(' \033[0;37mRunning ' + length + ' benchmarks, please wait...\033[0m\n'); function continuation () { index++; if (index < length) { benchmarks[index](continuation); } else { var endTime = Date.now(), total = Math.ceil((endTime - startTime) / 1000); console.log(' \n\033[0;37mFinished in ' + total + ' seconds\033[0m\n'); } } continuation(); }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
run
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function continuation () { index++; if (index < length) { benchmarks[index](continuation); } else { var endTime = Date.now(), total = Math.ceil((endTime - startTime) / 1000); console.log(' \n\033[0;37mFinished in ' + total + ' seconds\033[0m\n'); } }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
continuation
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
input = function (a, b, c) { return a + b + c * Math.random(); }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
input
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
input = function (a, b, c) { return a + b + c * Math.random(); }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
input
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function factorial(op) { // Lanczos Approximation of the Gamma Function // As described in Numerical Recipes in C (2nd ed. Cambridge University Press, 1992) var z = op + 1; var p = [1.000000000190015, 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 1.208650973866179E-3, -5.395239384953E-6]; var d1 = Math.sqrt(2 * Math.PI) / z; var d2 = p[0]; for (var i = 1; i <= 6; ++i) { d2 += p[i] / (z + i); } var d3 = Math.pow((z + 5.5), (z + 0.5)); var d4 = Math.exp(-(z + 5.5)); d = d1 * d2 * d3 * d4; return d; }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
factorial
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function doSomeWork () { var d = 0; d += factorial(10 * Math.random()); d += factorial(2 * Math.random()); return d; }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
doSomeWork
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function factorial(op) { // Lanczos Approximation of the Gamma Function // As described in Numerical Recipes in C (2nd ed. Cambridge University Press, 1992) var z = op + 1; var p = [1.000000000190015, 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 1.208650973866179E-3, -5.395239384953E-6]; var d1 = Math.sqrt(2 * Math.PI) / z; var d2 = p[0]; for (var i = 1; i <= 6; ++i) { d2 += p[i] / (z + i); } var d3 = Math.pow((z + 5.5), (z + 0.5)); var d4 = Math.exp(-(z + 5.5)); d = d1 * d2 * d3 * d4; return d; }
# Some A fast `.some()` implementation. @param {Array} subject The array (or array-like) to iterate over. @param {Function} fn The visitor function. @param {Object} thisContext The context for the visitor. @return {Boolean} true if at least one item in the array passes the truth test.
factorial
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function Fast (value) { if (!(this instanceof Fast)) { return new Fast(value); } this.value = value || []; }
# Constructor Provided as a convenient wrapper around Fast functions. ```js var arr = fast([1,2,3,4,5,6]); var result = arr.filter(function (item) { return item % 2 === 0; }); result instanceof Fast; // true result.length; // 3 ``` @param {Array} value The value to wrap.
Fast
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function Benchmark(name, fn, options) { var me = this; // allow instance creation without the `new` operator if (me == null || me.constructor != Benchmark) { return new Benchmark(name, fn, options); } // juggle arguments if (isClassOf(name, 'Object')) { // 1 argument (options) options = name; } else if (isClassOf(name, 'Function')) { // 2 arguments (fn, options) options = fn; fn = name; } else if (isClassOf(fn, 'Object')) { // 2 arguments (name, options) options = fn; fn = null; me.name = name; } else { // 3 arguments (name, fn [, options]) me.name = name; } setOptions(me, options); me.id || (me.id = ++counter); me.fn == null && (me.fn = fn); me.stats = deepClone(me.stats); me.times = deepClone(me.times); }
The Benchmark constructor. @constructor @param {String} name A name to identify the benchmark. @param {Function|String} fn The test to benchmark. @param {Object} [options={}] Options object. @example // basic usage (the `new` operator is optional) var bench = new Benchmark(fn); // or using a name first var bench = new Benchmark('foo', fn); // or with options var bench = new Benchmark('foo', fn, { // displayed by Benchmark#toString if `name` is not available 'id': 'xyz', // called when the benchmark starts running 'onStart': onStart, // called after each run cycle 'onCycle': onCycle, // called when aborted 'onAbort': onAbort, // called when a test errors 'onError': onError, // called when reset 'onReset': onReset, // called when the benchmark completes running 'onComplete': onComplete, // compiled/called before the test loop 'setup': setup, // compiled/called after the test loop 'teardown': teardown }); // or name and options var bench = new Benchmark('foo', { // a flag to indicate the benchmark is deferred 'defer': true, // benchmark test function 'fn': function(deferred) { // call resolve() when the deferred test is finished deferred.resolve(); } }); // or options only var bench = new Benchmark({ // benchmark name 'name': 'foo', // benchmark test as a string 'fn': '[1,2,3,4].sort()' }); // a test's `this` binding is set to the benchmark instance var bench = new Benchmark('foo', function() { 'My name is '.concat(this.name); // My name is foo });
Benchmark
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function Deferred(clone) { var me = this; if (me == null || me.constructor != Deferred) { return new Deferred(clone); } me.benchmark = clone; clock(me); }
The Deferred constructor. @constructor @memberOf Benchmark @param {Object} clone The cloned benchmark instance.
Deferred
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function Event(type) { var me = this; return (me == null || me.constructor != Event) ? new Event(type) : (type instanceof Event) ? type : extend(me, { 'timeStamp': +new Date }, typeof type == 'string' ? { 'type': type } : type); }
The Event constructor. @constructor @memberOf Benchmark @param {String|Object} type The event type.
Event
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function Suite(name, options) { var me = this; // allow instance creation without the `new` operator if (me == null || me.constructor != Suite) { return new Suite(name, options); } // juggle arguments if (isClassOf(name, 'Object')) { // 1 argument (options) options = name; } else { // 2 arguments (name [, options]) me.name = name; } setOptions(me, options); }
The Suite constructor. @constructor @memberOf Benchmark @param {String} name A name to identify the suite. @param {Object} [options={}] Options object. @example // basic usage (the `new` operator is optional) var suite = new Benchmark.Suite; // or using a name first var suite = new Benchmark.Suite('foo'); // or with options var suite = new Benchmark.Suite('foo', { // called when the suite starts running 'onStart': onStart, // called between running benchmarks 'onCycle': onCycle, // called when aborted 'onAbort': onAbort, // called when a test errors 'onError': onError, // called when reset 'onReset': onReset, // called when the suite completes running 'onComplete': onComplete });
Suite
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function concat() { var value, j = -1, length = arguments.length, result = slice.call(this), index = result.length; while (++j < length) { value = arguments[j]; if (isClassOf(value, 'Array')) { for (var k = 0, l = value.length; k < l; k++, index++) { if (k in value) { result[index] = value[k]; } } } else { result[index++] = value; } } return result; }
Creates an array containing the elements of the host array followed by the elements of each argument in order. @memberOf Benchmark.Suite @returns {Array} The new array.
concat
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function insert(start, deleteCount, elements) { // `result` should have its length set to the `deleteCount` // see https://bugs.ecmascript.org/show_bug.cgi?id=332 var deleteEnd = start + deleteCount, elementCount = elements ? elements.length : 0, index = start - 1, length = start + elementCount, object = this, result = Array(deleteCount), tail = slice.call(object, deleteEnd); // delete elements from the array while (++index < deleteEnd) { if (index in object) { result[index - start] = object[index]; delete object[index]; } } // insert elements index = start - 1; while (++index < length) { object[index] = elements[index - start]; } // append tail elements start = index--; length = max(0, (object.length >>> 0) - deleteCount + elementCount); while (++index < length) { if ((index - start) in tail) { object[index] = tail[index - start]; } else if (index in object) { delete object[index]; } } // delete excess elements deleteCount = deleteCount > elementCount ? deleteCount - elementCount : 0; while (deleteCount--) { index = length + deleteCount; if (index in object) { delete object[index]; } } object.length = length; return result; }
Utility function used by `shift()`, `splice()`, and `unshift()`. @private @param {Number} start The index to start inserting elements. @param {Number} deleteCount The number of elements to delete from the insert point. @param {Array} elements The elements to insert. @returns {Array} An array of deleted elements.
insert
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function reverse() { var upperIndex, value, index = -1, object = Object(this), length = object.length >>> 0, middle = floor(length / 2); if (length > 1) { while (++index < middle) { upperIndex = length - index - 1; value = upperIndex in object ? object[upperIndex] : uid; if (index in object) { object[upperIndex] = object[index]; } else { delete object[upperIndex]; } if (value != uid) { object[index] = value; } else { delete object[index]; } } } return object; }
Rearrange the host array's elements in reverse order. @memberOf Benchmark.Suite @returns {Array} The reversed array.
reverse
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function shift() { return insert.call(this, 0, 1)[0]; }
Removes the first element of the host array and returns it. @memberOf Benchmark.Suite @returns {Mixed} The first element of the array.
shift
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function slice(start, end) { var index = -1, object = Object(this), length = object.length >>> 0, result = []; start = toInteger(start); start = start < 0 ? max(length + start, 0) : min(start, length); start--; end = end == null ? length : toInteger(end); end = end < 0 ? max(length + end, 0) : min(end, length); while ((++index, ++start) < end) { if (start in object) { result[index] = object[start]; } } return result; }
Creates an array of the host array's elements from the start index up to, but not including, the end index. @memberOf Benchmark.Suite @param {Number} start The starting index. @param {Number} end The end index. @returns {Array} The new array.
slice
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function splice(start, deleteCount) { var object = Object(this), length = object.length >>> 0; start = toInteger(start); start = start < 0 ? max(length + start, 0) : min(start, length); // support the de-facto SpiderMonkey extension // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice#Parameters // https://bugs.ecmascript.org/show_bug.cgi?id=429 deleteCount = arguments.length == 1 ? length - start : min(max(toInteger(deleteCount), 0), length - start); return insert.call(object, start, deleteCount, slice.call(arguments, 2)); }
Allows removing a range of elements and/or inserting elements into the host array. @memberOf Benchmark.Suite @param {Number} start The start index. @param {Number} deleteCount The number of elements to delete. @param {Mixed} [val1, val2, ...] values to insert at the `start` index. @returns {Array} An array of removed elements.
splice
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function toInteger(value) { value = +value; return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1); }
Converts the specified `value` to an integer. @private @param {Mixed} value The value to convert. @returns {Number} The resulting integer.
toInteger
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function unshift() { var object = Object(this); insert.call(object, 0, 0, arguments); return object.length; }
Appends arguments to the host array. @memberOf Benchmark.Suite @returns {Number} The new length.
unshift
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function bind(fn, thisArg) { return function() { fn.apply(thisArg, arguments); }; }
A generic `Function#bind` like method. @private @param {Function} fn The function to be bound to `thisArg`. @param {Mixed} thisArg The `this` binding for the given function. @returns {Function} The bound function.
bind
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function createFunction() { // lazy define createFunction = function(args, body) { var result, anchor = freeDefine ? define.amd : Benchmark, prop = uid + 'createFunction'; runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}'); result = anchor[prop]; delete anchor[prop]; return result; }; // fix JaegerMonkey bug // http://bugzil.la/639720 createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || noop)() == uid ? createFunction : Function; return createFunction.apply(null, arguments); }
Creates a function from the given arguments string and body. @private @param {String} args The comma separated function arguments. @param {String} body The function body. @returns {Function} The new function.
createFunction
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function delay(bench, fn) { bench._timerId = setTimeout(fn, bench.delay * 1e3); }
Delay the execution of a function based on the benchmark's `delay` property. @private @param {Object} bench The benchmark instance. @param {Object} fn The function to execute.
delay
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function destroyElement(element) { trash.appendChild(element); trash.innerHTML = ''; }
Destroys the given element. @private @param {Element} element The element to destroy.
destroyElement
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function forProps() { var forShadowed, skipSeen, forArgs = true, shadowed = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf']; (function(enumFlag, key) { // must use a non-native constructor to catch the Safari 2 issue function Klass() { this.valueOf = 0; }; Klass.prototype.valueOf = 0; // check various for-in bugs for (key in new Klass) { enumFlag += key == 'valueOf' ? 1 : 0; } // check if `arguments` objects have non-enumerable indexes for (key in arguments) { key == '0' && (forArgs = false); } // Safari 2 iterates over shadowed properties twice // http://replay.waybackmachine.org/20090428222941/http://tobielangel.com/2007/1/29/for-in-loop-broken-in-safari/ skipSeen = enumFlag == 2; // IE < 9 incorrectly makes an object's properties non-enumerable if they have // the same name as other non-enumerable properties in its prototype chain. forShadowed = !enumFlag; }(0)); // lazy define forProps = function(object, callback, options) { options || (options = {}); var result = object; object = Object(object); var ctor, key, keys, skipCtor, done = !result, which = options.which, allFlag = which == 'all', index = -1, iteratee = object, length = object.length, ownFlag = allFlag || which == 'own', seen = {}, skipProto = isClassOf(object, 'Function'), thisArg = options.bind; if (thisArg !== undefined) { callback = bind(callback, thisArg); } // iterate all properties if (allFlag && support.getAllKeys) { for (index = 0, keys = getAllKeys(object), length = keys.length; index < length; index++) { key = keys[index]; if (callback(object[key], key, object) === false) { break; } } } // else iterate only enumerable properties else { for (key in object) { // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 // (if the prototype or a property on the prototype has been set) // incorrectly set a function's `prototype` property [[Enumerable]] value // to `true`. Because of this we standardize on skipping the `prototype` // property of functions regardless of their [[Enumerable]] value. if ((done = !(skipProto && key == 'prototype') && !(skipSeen && (hasKey(seen, key) || !(seen[key] = true))) && (!ownFlag || ownFlag && hasKey(object, key)) && callback(object[key], key, object) === false)) { break; } } // in IE < 9 strings don't support accessing characters by index if (!done && (forArgs && isArguments(object) || ((noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String') && (iteratee = noCharByIndex ? object.split('') : object)))) { while (++index < length) { if ((done = callback(iteratee[index], String(index), object) === false)) { break; } } } if (!done && forShadowed) { // Because IE < 9 can't set the `[[Enumerable]]` attribute of an existing // property and the `constructor` property of a prototype defaults to // non-enumerable, we manually skip the `constructor` property when we // think we are iterating over a `prototype` object. ctor = object.constructor; skipCtor = ctor && ctor.prototype && ctor.prototype.constructor === ctor; for (index = 0; index < 7; index++) { key = shadowed[index]; if (!(skipCtor && key == 'constructor') && hasKey(object, key) && callback(object[key], key, object) === false) { break; } } } } return result; }; return forProps.apply(null, arguments); }
Iterates over an object's properties, executing the `callback` for each. Callbacks may terminate the loop by explicitly returning `false`. @private @param {Object} object The object to iterate over. @param {Function} callback The function executed per own property. @param {Object} options The options object. @returns {Object} Returns the object iterated over.
forProps
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function getFirstArgument(fn) { return (!hasKey(fn, 'toString') && (/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || ''; }
Gets the name of the first argument from a function's source. @private @param {Function} fn The function. @returns {String} The argument name.
getFirstArgument
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function getMean(sample) { return reduce(sample, function(sum, x) { return sum + x; }) / sample.length || 0; }
Computes the arithmetic mean of a sample. @private @param {Array} sample The sample. @returns {Number} The mean.
getMean
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function getSource(fn, altSource) { var result = altSource; if (isStringable(fn)) { result = String(fn); } else if (support.decompilation) { // escape the `{` for Firefox 1 result = (/^[^{]+\{([\s\S]*)}\s*$/.exec(fn) || 0)[1]; } // trim string result = (result || '').replace(/^\s+|\s+$/g, ''); // detect strings containing only the "use strict" directive return /^(?:\/\*+[\w|\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use strict\1;?$/.test(result) ? '' : result; }
Gets the source code of a function. @private @param {Function} fn The function. @param {String} altSource A string used when a function's source code is unretrievable. @returns {String} The function's source code.
getSource
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function isArguments() { // lazy define isArguments = function(value) { return toString.call(value) == '[object Arguments]'; }; if (noArgumentsClass) { isArguments = function(value) { return hasKey(value, 'callee') && !(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee')); }; } return isArguments(arguments[0]); }
Checks if a value is an `arguments` object. @private @param {Mixed} value The value to check. @returns {Boolean} Returns `true` if the value is an `arguments` object, else `false`.
isArguments
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function isClassOf(value, name) { return value != null && toString.call(value) == '[object ' + name + ']'; }
Checks if an object is of the specified class. @private @param {Mixed} value The value to check. @param {String} name The name of the class. @returns {Boolean} Returns `true` if the value is of the specified class, else `false`.
isClassOf
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function isPlainObject(value) { // avoid non-objects and false positives for `arguments` objects in IE < 9 var result = false; if (!(value && typeof value == 'object') || (noArgumentsClass && isArguments(value))) { return result; } // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings. // Also check that the constructor is `Object` (i.e. `Object instanceof Object`) var ctor = value.constructor; if ((support.nodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) && (!isClassOf(ctor, 'Function') || ctor instanceof ctor)) { // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. if (support.iteratesOwnFirst) { forProps(value, function(subValue, subKey) { result = subKey; }); return result === false || hasKey(value, result); } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. forProps(value, function(subValue, subKey) { result = !hasKey(value, subKey); return false; }); return result === false; } return result; }
Checks if a given `value` is an object created by the `Object` constructor assuming objects created by the `Object` constructor have no inherited enumerable properties and that there are no `Object.prototype` extensions. @private @param {Mixed} value The value to check. @returns {Boolean} Returns `true` if the `value` is a plain `Object` object, else `false`.
isPlainObject
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function isStringable(value) { return hasKey(value, 'toString') || isClassOf(value, 'String'); }
Checks if a value can be safely coerced to a string. @private @param {Mixed} value The value to check. @returns {Boolean} Returns `true` if the value can be coerced, else `false`.
isStringable
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function methodize(fn) { return function() { var args = [this]; args.push.apply(args, arguments); return fn.apply(null, args); }; }
Wraps a function and passes `this` to the original function as the first argument. @private @param {Function} fn The function to be wrapped. @returns {Function} The new function.
methodize
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function req(id) { try { var result = freeExports && freeRequire(id); } catch(e) { } return result || null; }
A wrapper around require() to suppress `module missing` errors. @private @param {String} id The module id. @returns {Mixed} The exported module or `null`.
req
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function runScript(code) { var anchor = freeDefine ? define.amd : Benchmark, script = doc.createElement('script'), sibling = doc.getElementsByTagName('script')[0], parent = sibling.parentNode, prop = uid + 'runScript', prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();'; // Firefox 2.0.0.2 cannot use script injection as intended because it executes // asynchronously, but that's OK because script injection is only used to avoid // the previously commented JaegerMonkey bug. try { // remove the inserted script *before* running the code to avoid differences // in the expected script element count/order of the document. script.appendChild(doc.createTextNode(prefix + code)); anchor[prop] = function() { destroyElement(script); }; } catch(e) { parent = parent.cloneNode(false); sibling = null; script.text = code; } parent.insertBefore(script, sibling); delete anchor[prop]; }
Runs a snippet of JavaScript via script injection. @private @param {String} code The code to run.
runScript
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function setOptions(bench, options) { options = extend({}, bench.constructor.options, options); bench.options = forOwn(options, function(value, key) { if (value != null) { // add event listeners if (/^on[A-Z]/.test(key)) { forEach(key.split(' '), function(key) { bench.on(key.slice(2).toLowerCase(), value); }); } else if (!hasKey(bench, key)) { bench[key] = deepClone(value); } } }); }
A helper function for setting options/event handlers. @private @param {Object} bench The benchmark instance. @param {Object} [options={}] Options object.
setOptions
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function resolve() { var me = this, clone = me.benchmark, bench = clone._original; if (bench.aborted) { // cycle() -> clone cycle/complete event -> compute()'s invoked bench.run() cycle/complete me.teardown(); clone.running = false; cycle(me); } else if (++me.cycles < clone.count) { // continue the test loop if (support.timeout) { // use setTimeout to avoid a call stack overflow if called recursively setTimeout(function() { clone.compiled.call(me, timer); }, 0); } else { clone.compiled.call(me, timer); } } else { timer.stop(me); me.teardown(); delay(clone, function() { cycle(me); }); } }
Handles cycling/completing the deferred benchmark. @memberOf Benchmark.Deferred
resolve
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function deepClone(value) { var accessor, circular, clone, ctor, descriptor, extensible, key, length, markerKey, parent, result, source, subIndex, data = { 'value': value }, index = 0, marked = [], queue = { 'length': 0 }, unmarked = []; /** * An easily detectable decorator for cloned values. */ function Marker(object) { this.raw = object; } /** * The callback used by `forProps()`. */ function forPropsCallback(subValue, subKey) { // exit early to avoid cloning the marker if (subValue && subValue.constructor == Marker) { return; } // add objects to the queue if (subValue === Object(subValue)) { queue[queue.length++] = { 'key': subKey, 'parent': clone, 'source': value }; } // assign non-objects else { try { // will throw an error in strict mode if the property is read-only clone[subKey] = subValue; } catch(e) { } } } /** * Gets an available marker key for the given object. */ function getMarkerKey(object) { // avoid collisions with existing keys var result = uid; while (object[result] && object[result].constructor != Marker) { result += 1; } return result; } do { key = data.key; parent = data.parent; source = data.source; clone = value = source ? source[key] : data.value; accessor = circular = descriptor = false; // create a basic clone to filter out functions, DOM elements, and // other non `Object` objects if (value === Object(value)) { // use custom deep clone function if available if (isClassOf(value.deepClone, 'Function')) { clone = value.deepClone(); } else { ctor = value.constructor; switch (toString.call(value)) { case '[object Array]': clone = new ctor(value.length); break; case '[object Boolean]': clone = new ctor(value == true); break; case '[object Date]': clone = new ctor(+value); break; case '[object Object]': isPlainObject(value) && (clone = {}); break; case '[object Number]': case '[object String]': clone = new ctor(value); break; case '[object RegExp]': clone = ctor(value.source, (value.global ? 'g' : '') + (value.ignoreCase ? 'i' : '') + (value.multiline ? 'm' : '')); } } // continue clone if `value` doesn't have an accessor descriptor // http://es5.github.com/#x8.10.1 if (clone && clone != value && !(descriptor = source && support.descriptors && getDescriptor(source, key), accessor = descriptor && (descriptor.get || descriptor.set))) { // use an existing clone (circular reference) if ((extensible = isExtensible(value))) { markerKey = getMarkerKey(value); if (value[markerKey]) { circular = clone = value[markerKey].raw; } } else { // for frozen/sealed objects for (subIndex = 0, length = unmarked.length; subIndex < length; subIndex++) { data = unmarked[subIndex]; if (data.object === value) { circular = clone = data.clone; break; } } } if (!circular) { // mark object to allow quickly detecting circular references and tie it to its clone if (extensible) { value[markerKey] = new Marker(clone); marked.push({ 'key': markerKey, 'object': value }); } else { // for frozen/sealed objects unmarked.push({ 'clone': clone, 'object': value }); } // iterate over object properties forProps(value, forPropsCallback, { 'which': 'all' }); } } } if (parent) { // for custom property descriptors if (accessor || (descriptor && !(descriptor.configurable && descriptor.enumerable && descriptor.writable))) { if ('value' in descriptor) { descriptor.value = clone; } setDescriptor(parent, key, descriptor); } // for default property descriptors else { parent[key] = clone; } } else { result = clone; } } while ((data = queue[index++])); // remove markers for (index = 0, length = marked.length; index < length; index++) { data = marked[index]; delete data.object[data.key]; } return result; }
A deep clone utility. @static @memberOf Benchmark @param {Mixed} value The value to clone. @returns {Mixed} The cloned value.
deepClone
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function Marker(object) { this.raw = object; }
An easily detectable decorator for cloned values.
Marker
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function getMarkerKey(object) { // avoid collisions with existing keys var result = uid; while (object[result] && object[result].constructor != Marker) { result += 1; } return result; }
Gets an available marker key for the given object.
getMarkerKey
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function each(object, callback, thisArg) { var result = object; object = Object(object); var fn = callback, index = -1, length = object.length, isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)), isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'), isConvertable = isSnapshot || isSplittable || 'item' in object, origObject = object; // in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists if (length === length >>> 0) { if (isConvertable) { // the third argument of the callback is the original non-array object callback = function(value, index) { return fn.call(this, value, index, origObject); }; // in IE < 9 strings don't support accessing characters by index if (isSplittable) { object = object.split(''); } else { object = []; while (++index < length) { // in Safari 2 `index in object` is always `false` for NodeLists object[index] = isSnapshot ? result.snapshotItem(index) : result[index]; } } } forEach(object, callback, thisArg); } else { forOwn(object, callback, thisArg); } return result; }
An iteration utility for arrays and objects. Callbacks may terminate the loop by explicitly returning `false`. @static @memberOf Benchmark @param {Array|Object} object The object to iterate over. @param {Function} callback The function called per iteration. @param {Mixed} thisArg The `this` binding for the callback. @returns {Array|Object} Returns the object iterated over.
each
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function extend(destination, source) { // Chrome < 14 incorrectly sets `destination` to `undefined` when we `delete arguments[0]` // http://code.google.com/p/v8/issues/detail?id=839 var result = destination; delete arguments[0]; forEach(arguments, function(source) { forProps(source, function(value, key) { result[key] = value; }); }); return result; }
Copies enumerable properties from the source(s) object to the destination object. @static @memberOf Benchmark @param {Object} destination The destination object. @param {Object} [source={}] The source object. @returns {Object} The destination object.
extend
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function filter(array, callback, thisArg) { var result; if (callback == 'successful') { // callback to exclude those that are errored, unrun, or have hz of Infinity callback = function(bench) { return bench.cycles && isFinite(bench.hz); }; } else if (callback == 'fastest' || callback == 'slowest') { // get successful, sort by period + margin of error, and filter fastest/slowest result = filter(array, 'successful').sort(function(a, b) { a = a.stats; b = b.stats; return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback == 'fastest' ? 1 : -1); }); result = filter(result, function(bench) { return result[0].compare(bench) == 0; }); } return result || reduce(array, function(result, value, index) { return callback.call(thisArg, value, index, array) ? (result.push(value), result) : result; }, []); }
A generic `Array#filter` like method. @static @memberOf Benchmark @param {Array} array The array to iterate over. @param {Function|String} callback The function/alias called per iteration. @param {Mixed} thisArg The `this` binding for the callback. @returns {Array} A new array of values that passed callback filter. @example // get odd numbers Benchmark.filter([1, 2, 3, 4, 5], function(n) { return n % 2; }); // -> [1, 3, 5]; // get fastest benchmarks Benchmark.filter(benches, 'fastest'); // get slowest benchmarks Benchmark.filter(benches, 'slowest'); // get benchmarks that completed without erroring Benchmark.filter(benches, 'successful');
filter
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function forEach(array, callback, thisArg) { var index = -1, length = (array = Object(array)).length >>> 0; if (thisArg !== undefined) { callback = bind(callback, thisArg); } while (++index < length) { if (index in array && callback(array[index], index, array) === false) { break; } } return array; }
A generic `Array#forEach` like method. Callbacks may terminate the loop by explicitly returning `false`. @static @memberOf Benchmark @param {Array} array The array to iterate over. @param {Function} callback The function called per iteration. @param {Mixed} thisArg The `this` binding for the callback. @returns {Array} Returns the array iterated over.
forEach
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function forOwn(object, callback, thisArg) { return forProps(object, callback, { 'bind': thisArg, 'which': 'own' }); }
Iterates over an object's own properties, executing the `callback` for each. Callbacks may terminate the loop by explicitly returning `false`. @static @memberOf Benchmark @param {Object} object The object to iterate over. @param {Function} callback The function executed per own property. @param {Mixed} thisArg The `this` binding for the callback. @returns {Object} Returns the object iterated over.
forOwn
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function formatNumber(number) { number = String(number).split('.'); return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') + (number[1] ? '.' + number[1] : ''); }
Converts a number to a more readable comma-separated string representation. @static @memberOf Benchmark @param {Number} number The number to convert. @returns {String} The more readable string representation.
formatNumber
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function hasKey() { // lazy define for worst case fallback (not as accurate) hasKey = function(object, key) { var parent = object != null && (object.constructor || Object).prototype; return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); }; // for modern browsers if (isClassOf(hasOwnProperty, 'Function')) { hasKey = function(object, key) { return object != null && hasOwnProperty.call(object, key); }; } // for Safari 2 else if ({}.__proto__ == Object.prototype) { hasKey = function(object, key) { var result = false; if (object != null) { object = Object(object); object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; } return result; }; } return hasKey.apply(this, arguments); }
Checks if an object has the specified key as a direct property. @static @memberOf Benchmark @param {Object} object The object to check. @param {String} key The key to check for. @returns {Boolean} Returns `true` if key is a direct property, else `false`.
hasKey
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function indexOf(array, value, fromIndex) { var index = toInteger(fromIndex), length = (array = Object(array)).length >>> 0; index = (index < 0 ? max(0, length + index) : index) - 1; while (++index < length) { if (index in array && value === array[index]) { return index; } } return -1; }
A generic `Array#indexOf` like method. @static @memberOf Benchmark @param {Array} array The array to iterate over. @param {Mixed} value The value to search for. @param {Number} [fromIndex=0] The index to start searching from. @returns {Number} The index of the matched value or `-1`.
indexOf
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function interpolate(string, object) { forOwn(object, function(value, key) { // escape regexp special characters in `key` string = string.replace(RegExp('#\\{' + key.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + '\\}', 'g'), value); }); return string; }
Modify a string by replacing named tokens with matching object property values. @static @memberOf Benchmark @param {String} string The string to modify. @param {Object} object The template object. @returns {String} The modified string.
interpolate
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function execute() { var listeners, async = isAsync(bench); if (async) { // use `getNext` as the first listener bench.on('complete', getNext); listeners = bench.events.complete; listeners.splice(0, 0, listeners.pop()); } // execute method result[index] = isClassOf(bench && bench[name], 'Function') ? bench[name].apply(bench, args) : undefined; // if synchronous return true until finished return !async && getNext(); }
Invokes the method of the current object and if synchronous, fetches the next.
execute
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function getNext(event) { var cycleEvent, last = bench, async = isAsync(last); if (async) { last.off('complete', getNext); last.emit('complete'); } // emit "cycle" event eventProps.type = 'cycle'; eventProps.target = last; cycleEvent = Event(eventProps); options.onCycle.call(benches, cycleEvent); // choose next benchmark if not exiting early if (!cycleEvent.aborted && raiseIndex() !== false) { bench = queued ? benches[0] : result[index]; if (isAsync(bench)) { delay(bench, execute); } else if (async) { // resume execution if previously asynchronous but now synchronous while (execute()) { } } else { // continue synchronous execution return true; } } else { // emit "complete" event eventProps.type = 'complete'; options.onComplete.call(benches, Event(eventProps)); } // When used as a listener `event.aborted = true` will cancel the rest of // the "complete" listeners because they were already called above and when // used as part of `getNext` the `return false` will exit the execution while-loop. if (event) { event.aborted = true; } else { return false; } }
Fetches the next bench or executes `onComplete` callback.
getNext
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function isAsync(object) { // avoid using `instanceof` here because of IE memory leak issues with host objects var async = args[0] && args[0].async; return Object(object).constructor == Benchmark && name == 'run' && ((async == null ? object.options.async : async) && support.timeout || object.defer); }
Checks if invoking `Benchmark#run` with asynchronous cycles.
isAsync
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function raiseIndex() { var length = result.length; if (queued) { // if queued remove the previous bench and subsequent skipped non-entries do { ++index > 0 && shift.call(benches); } while ((length = benches.length) && !('0' in benches)); } else { while (++index < length && !(index in result)) { } } // if we reached the last index then return `false` return (queued ? length : index < length) ? index : (index = false); }
Raises `index` to the next defined index or returns `false`.
raiseIndex
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function join(object, separator1, separator2) { var result = [], length = (object = Object(object)).length, arrayLike = length === length >>> 0; separator2 || (separator2 = ': '); each(object, function(value, key) { result.push(arrayLike ? value : key + separator2 + value); }); return result.join(separator1 || ','); }
Creates a string of joined array values or object key-value pairs. @static @memberOf Benchmark @param {Array|Object} object The object to operate on. @param {String} [separator1=','] The separator used between key-value pairs. @param {String} [separator2=': '] The separator used between keys and values. @returns {String} The joined result.
join
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function map(array, callback, thisArg) { return reduce(array, function(result, value, index) { result[index] = callback.call(thisArg, value, index, array); return result; }, Array(Object(array).length >>> 0)); }
A generic `Array#map` like method. @static @memberOf Benchmark @param {Array} array The array to iterate over. @param {Function} callback The function called per iteration. @param {Mixed} thisArg The `this` binding for the callback. @returns {Array} A new array of values returned by the callback.
map
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function pluck(array, property) { return map(array, function(object) { return object == null ? undefined : object[property]; }); }
Retrieves the value of a specified property from all items in an array. @static @memberOf Benchmark @param {Array} array The array to iterate over. @param {String} property The property to pluck. @returns {Array} A new array of property values.
pluck
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function reduce(array, callback, accumulator) { var noaccum = arguments.length < 3; forEach(array, function(value, index) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, array); }); return accumulator; }
A generic `Array#reduce` like method. @static @memberOf Benchmark @param {Array} array The array to iterate over. @param {Function} callback The function called per iteration. @param {Mixed} accumulator Initial value of the accumulator. @returns {Mixed} The accumulator.
reduce
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function abortSuite() { var event, me = this, resetting = calledBy.resetSuite; if (me.running) { event = Event('abort'); me.emit(event); if (!event.cancelled || resetting) { // avoid infinite recursion calledBy.abortSuite = true; me.reset(); delete calledBy.abortSuite; if (!resetting) { me.aborted = true; invoke(me, 'abort'); } } } return me; }
Aborts all benchmarks in the suite. @name abort @memberOf Benchmark.Suite @returns {Object} The suite instance.
abortSuite
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function add(name, fn, options) { var me = this, bench = Benchmark(name, fn, options), event = Event({ 'type': 'add', 'target': bench }); if (me.emit(event), !event.cancelled) { me.push(bench); } return me; }
Adds a test to the benchmark suite. @memberOf Benchmark.Suite @param {String} name A name to identify the benchmark. @param {Function|String} fn The test to benchmark. @param {Object} [options={}] Options object. @returns {Object} The benchmark instance. @example // basic usage suite.add(fn); // or using a name first suite.add('foo', fn); // or with options suite.add('foo', fn, { 'onCycle': onCycle, 'onComplete': onComplete }); // or name and options suite.add('foo', { 'fn': fn, 'onCycle': onCycle, 'onComplete': onComplete }); // or options only suite.add({ 'name': 'foo', 'fn': fn, 'onCycle': onCycle, 'onComplete': onComplete });
add
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function cloneSuite(options) { var me = this, result = new me.constructor(extend({}, me.options, options)); // copy own properties forOwn(me, function(value, key) { if (!hasKey(result, key)) { result[key] = value && isClassOf(value.clone, 'Function') ? value.clone() : deepClone(value); } }); return result; }
Creates a new suite with cloned benchmarks. @name clone @memberOf Benchmark.Suite @param {Object} options Options object to overwrite cloned options. @returns {Object} The new suite instance.
cloneSuite
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function filterSuite(callback) { var me = this, result = new me.constructor; result.push.apply(result, filter(me, callback)); return result; }
An `Array#filter` like method. @name filter @memberOf Benchmark.Suite @param {Function|String} callback The function/alias called per iteration. @returns {Object} A new suite of benchmarks that passed callback filter.
filterSuite
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT
function resetSuite() { var event, me = this, aborting = calledBy.abortSuite; if (me.running && !aborting) { // no worries, `resetSuite()` is called within `abortSuite()` calledBy.resetSuite = true; me.abort(); delete calledBy.resetSuite; } // reset if the state has changed else if ((me.aborted || me.running) && (me.emit(event = Event('reset')), !event.cancelled)) { me.running = false; if (!aborting) { invoke(me, 'reset'); } } return me; }
Resets all benchmarks in the suite. @name reset @memberOf Benchmark.Suite @returns {Object} The suite instance.
resetSuite
javascript
codemix/fast.js
dist/bench.js
https://github.com/codemix/fast.js/blob/master/dist/bench.js
MIT