code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
function trim(subject, whitespace) {
var subjectString = coerceToString(subject);
if (whitespace === '' || subjectString === '') {
return subjectString;
}
var whitespaceString = toString(whitespace);
if (isNil(whitespaceString)) {
return subjectString.trim();
}
return trimRight(trimLeft(subjectString, whitespaceString), whitespaceString);
} | Removes whitespaces from left and right sides of the `subject`.
@function trim
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to trim.
@param {string} [whitespace=whitespace] The whitespace characters to trim. List all characters that you want to be stripped.
@return {string} Returns the trimmed string.
@example
v.trim(' Mother nature ');
// => 'Mother nature'
v.trim('--Earth--', '-');
// => 'Earth' | trim ( subject , whitespace ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function wordWrap(subject) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var subjectString = coerceToString(subject);
var _determineOptions = determineOptions(options),
width = _determineOptions.width,
newLine = _determineOptions.newLine,
indent = _determineOptions.indent,
cut = _determineOptions.cut;
if (subjectString === '' || width <= 0) {
return indent;
}
var subjectLength = subjectString.length;
var substring = subjectString.substring.bind(subjectString);
var offset = 0;
var wrappedLine = '';
while (subjectLength - offset > width) {
if (subjectString[offset] === ' ') {
offset++;
continue;
}
var spaceToWrapAt = subjectString.lastIndexOf(' ', width + offset);
if (spaceToWrapAt >= offset) {
wrappedLine += indent + substring(offset, spaceToWrapAt) + newLine;
offset = spaceToWrapAt + 1;
} else {
if (cut) {
wrappedLine += indent + substring(offset, width + offset) + newLine;
offset += width;
} else {
spaceToWrapAt = subjectString.indexOf(' ', width + offset);
if (spaceToWrapAt >= 0) {
wrappedLine += indent + substring(offset, spaceToWrapAt) + newLine;
offset = spaceToWrapAt + 1;
} else {
wrappedLine += indent + substring(offset);
offset = subjectLength;
}
}
}
}
if (offset < subjectLength) {
wrappedLine += indent + substring(offset);
}
return wrappedLine;
} | Wraps `subject` to a given number of characters using a string break character.
@function wordWrap
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to wrap.
@param {Object} [options={}] The wrap options.
@param {number} [options.width=75] The number of characters at which to wrap.
@param {string} [options.newLine='\n'] The string to add at the end of line.
@param {string} [options.indent=''] The string to intend the line.
@param {boolean} [options.cut=false] When `false` (default) does not split the word even if word length is bigger than `width`. <br/>
When `true` breaks the word that has length bigger than `width`.
@return {string} Returns wrapped string.
@example
v.wordWrap('Hello world', {
width: 5
});
// => 'Hello\nworld'
v.wordWrap('Hello world', {
width: 5,
newLine: '<br/>',
indent: '__'
});
// => '__Hello<br/>__world'
v.wordWrap('Wonderful world', {
width: 5,
cut: true
});
// => 'Wonde\nrful\nworld' | wordWrap ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function endsWith(subject, end, position) {
if (isNil(end)) {
return false;
}
var subjectString = coerceToString(subject);
var endString = coerceToString(end);
if (endString === '') {
return true;
}
position = isNil(position) ? subjectString.length : clipNumber(toInteger(position), 0, subjectString.length);
position -= endString.length;
var lastIndex = subjectString.indexOf(endString, position);
return lastIndex !== -1 && lastIndex === position;
} | Checks whether `subject` ends with `end`.
@function endsWith
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@param {string} end The ending string.
@param {number} [position=subject.length] Search within `subject` as if the string were only `position` long.
@return {boolean} Returns `true` if `subject` ends with `end` or `false` otherwise.
@example
v.endsWith('red alert', 'alert');
// => true
v.endsWith('metro south', 'metro');
// => false
v.endsWith('Murphy', 'ph', 5);
// => true | endsWith ( subject , end , position ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isAlpha(subject) {
var subjectString = coerceToString(subject);
return REGEXP_ALPHA.test(subjectString);
} | Checks whether `subject` contains only alpha characters.
@function isAlpha
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@return {boolean} Returns `true` if `subject` contains only alpha characters or `false` otherwise.
@example
v.isAlpha('bart');
// => true
v.isAlpha('lisa!');
// => false
v.isAlpha('lisa and bart');
// => false | isAlpha ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isAlphaDigit(subject) {
var subjectString = coerceToString(subject);
return REGEXP_ALPHA_DIGIT.test(subjectString);
} | Checks whether `subject` contains only alpha and digit characters.
@function isAlphaDigit
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@return {boolean} Returns `true` if `subject` contains only alpha and digit characters or `false` otherwise.
@example
v.isAlphaDigit('year2020');
// => true
v.isAlphaDigit('1448');
// => true
v.isAlphaDigit('40-20');
// => false | isAlphaDigit ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isBlank(subject) {
var subjectString = coerceToString(subject);
return subjectString.trim().length === 0;
} | Checks whether `subject` is empty or contains only whitespaces.
@function isBlank
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@return {boolean} Returns `true` if `subject` is empty or contains only whitespaces or `false` otherwise.
@example
v.isBlank('');
// => true
v.isBlank(' ');
// => true
v.isBlank('World');
// => false | isBlank ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isDigit(subject) {
var subjectString = coerceToString(subject);
return REGEXP_DIGIT.test(subjectString);
} | Checks whether `subject` contains only digit characters.
@function isDigit
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@return {boolean} Returns `true` if `subject` contains only digit characters or `false` otherwise.
@example
v.isDigit('35');
// => true
v.isDigit('1.5');
// => false
v.isDigit('ten');
// => false | isDigit ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isEmpty(subject) {
var subjectString = coerceToString(subject);
return subjectString.length === 0;
} | Checks whether `subject` is empty.
@function isEmpty
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@return {boolean} Returns `true` if `subject` is empty or `false` otherwise
@example
v.isEmpty('');
// => true
v.isEmpty(' ');
// => false
v.isEmpty('sun');
// => false | isEmpty ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isLowerCase(subject) {
var valueString = coerceToString(subject);
return isAlpha(valueString) && valueString.toLowerCase() === valueString;
} | Checks whether `subject` has only lower case characters.
@function isLowerCase
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@return {boolean} Returns `true` if `subject` is lower case or `false` otherwise.
@example
v.isLowerCase('motorcycle');
// => true
v.isLowerCase('John');
// => false
v.isLowerCase('T1000');
// => false | isLowerCase ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isNumeric(subject) {
var valueNumeric = typeof subject === 'object' && !isNil(subject) ? Number(subject) : subject;
return (
(typeof valueNumeric === 'number' || typeof valueNumeric === 'string') &&
!isNaN(valueNumeric - parseFloat(valueNumeric))
);
} | Checks whether `subject` is numeric.
@function isNumeric
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@return {boolean} Returns `true` if `subject` is numeric or `false` otherwise.
@example
v.isNumeric('350');
// => true
v.isNumeric('-20.5');
// => true
v.isNumeric('1.5E+2');
// => true
v.isNumeric('five');
// => false | isNumeric ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isUpperCase(subject) {
var subjectString = coerceToString(subject);
return isAlpha(subjectString) && subjectString.toUpperCase() === subjectString;
} | Checks whether `subject` contains only upper case characters.
@function isUpperCase
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@return {boolean} Returns `true` if `subject` is upper case or `false` otherwise.
@example
v.isUpperCase('ACDC');
// => true
v.isUpperCase('Morning');
// => false | isUpperCase ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function matches(subject, pattern, flags) {
var subjectString = coerceToString(subject);
var flagsString = coerceToString(flags);
var patternString;
if (!(pattern instanceof RegExp)) {
patternString = toString(pattern);
if (patternString === null) {
return false;
}
pattern = new RegExp(patternString, flagsString);
}
return pattern.test(subjectString);
} | Checks whether `subject` matches the regular expression `pattern`.
@function matches
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@param {RegExp|string} pattern The pattern to match. If `pattern` is not RegExp, it is transformed to `new RegExp(pattern, flags)`.
@param {string} [flags=''] The regular expression flags. Applies when `pattern` is string type.
@return {boolean} Returns `true` if `subject` matches `pattern` or `false` otherwise.
@example
v.matches('pluto', /plu.{2}/);
// => true
v.matches('sun', 'S', 'i');
// => true
v.matches('apollo 11', '\\d{3}');
// => false | matches ( subject , pattern , flags ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function startsWith(subject, start, position) {
var subjectString = coerceToString(subject);
var startString = toString(start);
if (startString === null) {
return false;
}
if (startString === '') {
return true;
}
position = isNil(position) ? 0 : clipNumber(toInteger(position), 0, subjectString.length);
return subjectString.substr(position, startString.length) === startString;
} | Checks whether `subject` starts with `start`.
@function startsWith
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string to verify.
@param {string} start The starting string.
@param {number} [position=0] The position to start searching.
@return {boolean} Returns `true` if `subject` starts with `start` or `false` otherwise.
@example
v.startsWith('say hello to my little friend', 'say hello');
// => true
v.startsWith('tony', 'on', 1);
// => true
v.startsWith('the world is yours', 'world');
// => false | startsWith ( subject , start , position ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function chars(subject) {
var subjectString = coerceToString(subject);
return subjectString.split('');
} | Splits `subject` into an array of characters.
@function chars
@static
@since 1.0.0
@memberOf Split
@param {string} [subject=''] The string to split into characters.
@return {Array} Returns the array of characters.
@example
v.chars('cloud');
// => ['c', 'l', 'o', 'u', 'd'] | chars ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function codePoints(subject) {
var subjectString = coerceToString(subject);
var subjectStringLength = subjectString.length;
var codePointArray = [];
var index = 0;
var codePointNumber;
while (index < subjectStringLength) {
codePointNumber = codePointAt(subjectString, index);
codePointArray.push(codePointNumber);
index += codePointNumber > 0xffff ? 2 : 1;
}
return codePointArray;
} | Returns an array of Unicode code point values from characters of `subject`.
@function codePoints
@static
@since 1.0.0
@memberOf Split
@param {string} [subject=''] The string to extract from.
@return {Array} Returns an array of non-negative numbers less than or equal to `0x10FFFF`.
@example
v.codePoints('rain');
// => [114, 97, 105, 110], or
// [0x72, 0x61, 0x69, 0x6E]
v.codePoints('\uD83D\uDE00 smile'); // or '😀 smile'
// => [128512, 32, 115, 109, 105, 108, 101], or
// [0x1F600, 0x20, 0x73, 0x6D, 0x69, 0x6C, 0x65] | codePoints ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function graphemes(subject) {
var subjectString = coerceToString(subject);
return nilDefault(subjectString.match(REGEXP_UNICODE_CHARACTER), []);
} | Splits `subject` into an array of graphemes taking care of
<a href="https://rainsoft.io/what-every-javascript-developer-should-know-about-unicode/#24surrogatepairs">surrogate pairs</a> and
<a href="https://rainsoft.io/what-every-javascript-developer-should-know-about-unicode/#25combiningmarks">combining marks</a>.
@function graphemes
@static
@since 1.0.0
@memberOf Split
@param {string} [subject=''] The string to split into characters.
@return {Array} Returns the array of graphemes.
@example
v.graphemes('\uD835\uDC00\uD835\uDC01'); // or '𝐀𝐁'
// => ['\uD835\uDC00', '\uD835\uDC01'], or
// ['𝐀', '𝐁']
v.graphemes('cafe\u0301'); // or 'café'
// => ['c', 'a', 'f', 'e\u0301'], or
// ['c', 'a', 'f', 'é'] | graphemes ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function split(subject, separator, limit) {
var subjectString = coerceToString(subject);
return subjectString.split(separator, limit);
} | Splits `subject` into an array of chunks by `separator`.
@function split
@static
@since 1.0.0
@memberOf Split
@param {string} [subject=''] The string to split into characters.
@param {string|RegExp} [separator] The pattern to match the separator.
@param {number} [limit] Limit the number of chunks to be found.
@return {Array} Returns the array of chunks.
@example
v.split('rage against the dying of the light', ' ');
// => ['rage', 'against', 'the', 'dying', 'of', 'the', 'light']
v.split('the dying of the light', /\s/, 3);
// => ['the', 'dying', 'of'] | split ( subject , separator , limit ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function trim$1(subject) {
var subjectString = coerceToString(subject);
if (subjectString === '') {
return '';
}
if (subjectString[0] === BYRE_ORDER_MARK) {
return subjectString.substring(1);
}
return subjectString;
} | Strips the byte order mark (BOM) from the beginning of `subject`.
@function stripBom
@static
@since 1.2.0
@memberOf Strip
@param {string} [subject=''] The string to strip from.
@return {string} Returns the stripped string.
@example
v.stripBom('\uFEFFsummertime sadness');
// => 'summertime sadness'
v.stripBom('summertime happiness');
// => 'summertime happiness' | $1 ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function hasSubstringAtIndex(subject, substring, index) {
var lookBehind = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var indexOffset = 0;
if (lookBehind) {
indexOffset = -substring.length + 1;
}
var extractedSubstring = subject.substr(index + indexOffset, substring.length);
return extractedSubstring.toLowerCase() === substring;
} | Checks whether `subject` contains substring at specific `index`.
@ignore
@param {string} subject The subject to search in.
@param {string} substring The substring to search/
@param {number} index The index to search substring.
@param {boolean} lookBehind Whether to look behind (true) or ahead (false).
@return {boolean} Returns a boolean whether the substring exists. | hasSubstringAtIndex ( subject , substring , index ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function parseTagList(tags) {
var tagsList = [];
var match;
while ((match = REGEXP_TAG_LIST.exec(tags)) !== null) {
tagsList.push(match[1]);
}
return tagsList;
} | Parses the tags from the string '<tag1><tag2>...<tagN>'.
@ignore
@param {string} tags The string that contains the tags.
@return {string[]} Returns the array of tag names. | parseTagList ( tags ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function parseTagName(tagContent) {
var state = STATE_START_TAG;
var tagName = '';
var index = 0;
while (state !== STATE_DONE) {
var char = tagContent[index++].toLowerCase();
switch (char) {
case '<':
break;
case '>':
state = STATE_DONE;
break;
default:
if (REGEXP_WHITESPACE.test(char)) {
if (state === STATE_NON_WHITESPACE) {
state = STATE_DONE;
}
} else {
if (state === STATE_START_TAG) {
state = STATE_NON_WHITESPACE;
}
if (char !== '/') {
tagName += char;
}
}
break;
}
}
return tagName;
} | Parses the tag name from html content.
@ignore
@param {string} tagContent The tag content.
@return {string} Returns the tag name. | parseTagName ( tagContent ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function trim$2(subject, allowableTags, replacement) {
subject = coerceToString(subject);
if (subject === '') {
return '';
}
if (!Array.isArray(allowableTags)) {
var allowableTagsString = coerceToString(allowableTags);
allowableTags = allowableTagsString === '' ? [] : parseTagList(allowableTagsString);
}
var replacementString = coerceToString(replacement);
var length = subject.length;
var hasAllowableTags = allowableTags.length > 0;
var hasSubstring = hasSubstringAtIndex.bind(null, subject);
var state = STATE_OUTPUT;
var depth = 0;
var output = '';
var tagContent = '';
var quote = null;
for (var index = 0; index < length; index++) {
var char = subject[index];
var advance = false;
switch (char) {
case '<':
if (quote) {
break;
}
if (hasSubstring('< ', index, false)) {
advance = true;
break;
}
if (state === STATE_OUTPUT) {
advance = true;
state = STATE_HTML;
break;
}
if (state === STATE_HTML) {
depth++;
break;
}
advance = true;
break;
case '!':
if (state === STATE_HTML && hasSubstring('<!', index)) {
state = STATE_EXCLAMATION;
break;
}
advance = true;
break;
case '-':
if (state === STATE_EXCLAMATION && hasSubstring('!--', index)) {
state = STATE_COMMENT;
break;
}
advance = true;
break;
case '"':
case "'":
if (state === STATE_HTML) {
if (quote === char) {
quote = null;
} else if (!quote) {
quote = char;
}
}
advance = true;
break;
case 'E':
case 'e':
if (state === STATE_EXCLAMATION && hasSubstring('doctype', index)) {
state = STATE_HTML;
break;
}
advance = true;
break;
case '>':
if (depth > 0) {
depth--;
break;
}
if (quote) {
break;
}
if (state === STATE_HTML) {
quote = null;
state = STATE_OUTPUT;
if (hasAllowableTags) {
tagContent += '>';
var tagName = parseTagName(tagContent);
if (allowableTags.indexOf(tagName.toLowerCase()) !== -1) {
output += tagContent;
} else {
output += replacementString;
}
tagContent = '';
} else {
output += replacementString;
}
break;
}
if (state === STATE_EXCLAMATION || (state === STATE_COMMENT && hasSubstring('-->', index))) {
quote = null;
state = STATE_OUTPUT;
tagContent = '';
break;
}
advance = true;
break;
default:
advance = true;
}
if (advance) {
switch (state) {
case STATE_OUTPUT:
output += char;
break;
case STATE_HTML:
if (hasAllowableTags) {
tagContent += char;
}
break;
}
}
}
return output;
} | Strips HTML tags from `subject`.
@function stripTags
@static
@since 1.1.0
@memberOf Strip
@param {string} [subject=''] The string to strip from.
@param {string|Array} [allowableTags] The string `'<tag1><tag2>'` or array `['tag1', 'tag2']` of tags that should not be stripped.
@param {string} [replacement=''] The string to replace the stripped tag.
@return {string} Returns the stripped string.
@example
v.stripTags('<span><a href="#">Summer</a> is nice</span>');
// => 'Summer is nice'
v.stripTags('<span><i>Winter</i> is <b>cold</b></span>', ['b', 'i']);
// => '<i>Winter</i> is <b>cold</b>'
v.stripTags('Sun<br/>set', '', '-');
// => 'Sun-set' | $2 ( subject , allowableTags , replacement ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function noConflict() {
if (this === globalObject$1.v) {
globalObject$1.v = previousV;
}
return this;
} | Restores `v` variable to previous value and returns Voca library instance.
@function noConflict
@static
@since 1.0.0
@memberOf Util
@return {Object} Returns Voca library instance.
@example
var voca = v.noConflict();
voca.isAlpha('Hello');
// => true | noConflict ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function ChainWrapper(subject, explicitChain) {
this._wrappedValue = subject;
this._explicitChain = explicitChain;
} | The chain wrapper constructor.
@ignore
@param {string} subject The string to be wrapped.
@param {boolean} [explicitChain=false] A boolean that indicates if the chain sequence is explicit or implicit.
@return {ChainWrapper} Returns a new instance of `ChainWrapper`
@constructor | ChainWrapper ( subject , explicitChain ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ChainWrapper.prototype.value = function() {
return this._wrappedValue;
}; | Unwraps the chain sequence wrapped value.
@memberof Chain
@since 1.0.0
@function __proto__value
@return {*} Returns the unwrapped value.
@example
v
.chain('Hello world')
.replace('Hello', 'Hi')
.lowerCase()
.slugify()
.value()
// => 'hi-world'
v(' Space travel ')
.trim()
.truncate(8)
.value()
// => 'Space...' | ChainWrapper.prototype.value ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ChainWrapper.prototype.valueOf = function() {
return this.value();
}; | Override the default object valueOf().
@ignore
@return {*} Returns the wrapped value. | ChainWrapper.prototype.valueOf ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ChainWrapper.prototype.toJSON = function() {
return this.value();
}; | Returns the wrapped value to be used in JSON.stringify().
@ignore
@return {*} Returns the wrapped value. | ChainWrapper.prototype.toJSON ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ChainWrapper.prototype.toString = function() {
return String(this.value());
}; | Returns the string representation of the wrapped value.
@ignore
@return {string} Returns the string representation. | ChainWrapper.prototype.toString ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ChainWrapper.prototype.chain = function() {
return new ChainWrapper(this._wrappedValue, true);
}; | Creates a new chain object that enables <i>explicit</i> chain sequences.
Use `v.prototype.value()` to unwrap the result. <br/>
Does not modify the wrapped value.
@memberof Chain
@since 1.0.0
@function __proto__chain
@return {Object} Returns the wrapper in <i>explicit</i> mode.
@example
v('Back to School')
.chain()
.lowerCase()
.words()
.value()
// => ['back', 'to', 'school']
v(" Back to School ")
.chain()
.trim()
.truncate(7)
.value()
// => 'Back...' | ChainWrapper.prototype.chain ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ChainWrapper.prototype.thru = function(changer) {
if (typeof changer === 'function') {
return new ChainWrapper(changer(this._wrappedValue), this._explicitChain);
}
return this;
}; | Modifies the wrapped value with the invocation result of `changer` function. The current wrapped value is the
argument of `changer` invocation.
@memberof Chain
@since 1.0.0
@function __proto__thru
@param {Function} changer The function to invoke.
@return {Object} Returns the new wrapper that wraps the invocation result of `changer`.
@example
v
.chain('sun is shining')
.words()
.thru(function(words) {
return words[0];
})
.value()
// => 'sun' | ChainWrapper.prototype.thru ( changer ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function makeFunctionChainable(functionInstance) {
return function() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var result = functionInstance.apply(void 0, [this._wrappedValue].concat(args));
if (this._explicitChain || typeof result === 'string') {
return new ChainWrapper(result, this._explicitChain);
} else {
return result;
}
};
} | Make a voca function chainable.
@ignore
@param {Function} functionInstance The function to make chainable
@return {Function} Returns the chainable function | makeFunctionChainable ( functionInstance ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function chain(subject) {
return new ChainWrapper(subject, true);
} | Creates a chain object that wraps `subject`, enabling <i>explicit</i> chain sequences. <br/>
Use `v.prototype.value()` to unwrap the result.
@memberOf Chain
@since 1.0.0
@function chain
@param {string} subject The string to wrap.
@return {Object} Returns the new wrapper object.
@example
v
.chain('Back to School')
.lowerCase()
.words()
.value()
// => ['back', 'to', 'school'] | chain ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function Voca(subject) {
return new ChainWrapper(subject, false);
} | Creates a chain object that wraps `subject`, enabling <i>implicit</i> chain sequences.<br/>
A function that returns `number`, `boolean` or `array` type <i>terminates</i> the chain sequence and returns the unwrapped value.
Otherwise use `v.prototype.value()` to unwrap the result.
@memberOf Chain
@since 1.0.0
@function v
@param {string} subject The string to wrap.
@return {Object} Returns the new wrapper object.
@example
v('Back to School')
.lowerCase()
.words()
// => ['back', 'to', 'school']
v(" Back to School ")
.trim()
.truncate(7)
.value()
// => 'Back...' | Voca ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
export default function sprintf(format, ...replacements) {
const formatString = coerceToString(format);
if (formatString === '') {
return formatString;
}
const boundReplacementMatch = replacementMatch.bind(undefined, new ReplacementIndex(), replacements);
return formatString.replace(REGEXP_CONVERSION_SPECIFICATION, boundReplacementMatch);
} | Produces a string according to `format`.
<div id="sprintf-format" class="smaller">
`format` string is composed of zero or more directives: ordinary characters (not <code>%</code>), which are copied unchanged
to the output string and <i>conversion specifications</i>, each of which results in fetching zero or more subsequent
arguments. <br/> <br/>
Each <b>conversion specification</b> is introduced by the character <code>%</code>, and ends with a <b>conversion
specifier</b>. In between there may be (in this order) zero or more <b>flags</b>, an optional <b>minimum field width</b>
and an optional <b>precision</b>.<br/>
The syntax is: <b>ConversionSpecification</b> = <b>"%"</b> { <b>Flags</b> }
[ <b>MinimumFieldWidth</b> ] [ <b>Precision</b> ] <b>ConversionSpecifier</b>, where curly braces { } denote repetition
and square brackets [ ] optionality. <br/><br/>
By default, the arguments are used in the given order.<br/>
For argument numbering and swapping, `%m$` (where `m` is a number indicating the argument order)
is used instead of `%` to specify explicitly which argument is taken. For instance `%1$s` fetches the 1st argument,
`%2$s` the 2nd and so on, no matter what position the conversion specification has in `format`.
<br/><br/>
<b>The flags</b><br/>
The character <code>%</code> is followed by zero or more of the following flags:<br/>
<table class="light-params">
<tr>
<td><code>+</code></td>
<td>
A sign (<code>+</code> or <code>-</code>) should always be placed before a number produced by a
signed conversion. By default a sign is used only for negative numbers.
</td>
</tr>
<tr>
<td><code>0</code></td>
<td>The value should be zero padded.</td>
</tr>
<tr>
<td><code>␣</code></td>
<td>(a space) The value should be space padded.</td>
</tr>
<tr>
<td><code>'</code></td>
<td>Indicates alternate padding character, specified by prefixing it with a single quote <code>'</code>.</td>
</tr>
<tr>
<td><code>-</code></td>
<td>The converted value is to be left adjusted on the field boundary (the default is right justification).</td>
</tr>
</table>
<b>The minimum field width</b><br/>
An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted
value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the
left-adjustment flag has been given).<br/><br/>
<b>The precision</b><br/>
An optional precision, in the form of a period `.` followed by an optional decimal digit string.<br/>
This gives the number of digits to appear after the radix character for `e`, `E`, `f` and `F` conversions, the
maximum number of significant digits for `g` and `G` conversions or the maximum number of characters to be printed
from a string for `s` conversion.<br/><br/>
<b>The conversion specifier</b><br/>
A specifier that mentions what type the argument should be treated as:
<table class="light-params">
<tr>
<td>`s`</td>
<td>The string argument is treated as and presented as a string.</td>
</tr>
<tr>
<td>`d` `i`</td>
<td>The integer argument is converted to signed decimal notation.</td>
</tr>
<tr>
<td>`b`</td>
<td>The unsigned integer argument is converted to unsigned binary.</td>
</tr>
<tr>
<td>`c`</td>
<td>The unsigned integer argument is converted to an ASCII character with that number.</td>
</tr>
<tr>
<td>`o`</td>
<td>The unsigned integer argument is converted to unsigned octal.</td>
</tr>
<tr>
<td>`u`</td>
<td>The unsigned integer argument is converted to unsigned decimal.</td>
</tr>
<tr>
<td>`x` `X`</td>
<td>The unsigned integer argument is converted to unsigned hexadecimal. The letters `abcdef` are used for `x`
conversions; the letters `ABCDEF` are used for `X` conversions.</td>
</tr>
<tr>
<td>`f`</td>
<td>
The float argument is rounded and converted to decimal notation in the style `[-]ddd.ddd`, where the number of
digits after the decimal-point character is equal to the precision specification. If the precision is missing,
it is taken as 6; if the precision is explicitly zero, no decimal-point character appears.
If a decimal point appears, at least one digit appears before it.
</td>
</tr>
<tr>
<td>`e` `E`</td>
<td>
The float argument is rounded and converted in the style `[-]d.ddde±dd`, where there is one digit
before the decimal-point character and the number of digits after it is equal to the precision. If
the precision is missing, it is taken as `6`; if the precision is zero, no decimal-point character
appears. An `E` conversion uses the letter `E` (rather than `e`) to introduce the exponent.
</td>
</tr>
<tr>
<td>`g` `G`</td>
<td>
The float argument is converted in style `f` or `e` (or `F` or `E` for `G` conversions). The precision specifies
the number of significant digits. If the precision is missing, `6` digits are given; if the
precision is zero, it is treated as `1`. Style `e` is used if the exponent from its conversion is less
than `-6` or greater than or equal to the precision. Trailing zeros are removed from the fractional
part of the result; a decimal point appears only if it is followed by at least one digit.
</td>
</tr>
<tr>
<td>`%`</td>
<td>A literal `%` is written. No argument is converted. The complete conversion specification is `%%`.</td>
</tr>
</table>
</div>
@function sprintf
@static
@since 1.0.0
@memberOf Format
@param {string} [format=''] The format string.
@param {...*} replacements The replacements to produce the string.
@return {string} Returns the produced string.
@example
v.sprintf('%s, %s!', 'Hello', 'World');
// => 'Hello World!'
v.sprintf('%s costs $%d', 'coffee', 2);
// => 'coffee costs $2'
v.sprintf('%1$s %2$s %1$s %2$s, watcha gonna %3$s', 'bad', 'boys', 'do')
// => 'bad boys bad boys, watcha gonna do'
v.sprintf('% 6s', 'bird');
// => ' bird'
v.sprintf('% -6s', 'crab');
// => 'crab '
v.sprintf("%'*5s", 'cat');
// => '**cat'
v.sprintf("%'*-6s", 'duck');
// => 'duck**'
v.sprintf('%d %i %+d', 15, -2, 25);
// => '15 -2 +25'
v.sprintf("%06d", 15);
// => '000015'
v.sprintf('0b%b 0o%o 0x%X', 12, 9, 155);
// => '0b1100 0o11 0x9B'
v.sprintf('%.2f', 10.469);
// => '10.47'
v.sprintf('%.2e %g', 100.5, 0.455);
// => '1.01e+2 0.455' | sprintf ( format , ... replacements ) | javascript | panzerdp/voca | src/format/sprintf.js | https://github.com/panzerdp/voca/blob/master/src/format/sprintf.js | MIT |
export default function replaceAll(subject, search, replace) {
const subjectString = coerceToString(subject);
if (search instanceof RegExp) {
if (search.flags.indexOf('g') === -1) {
throw new TypeError('search argument is a non-global regular expression');
}
return subjectString.replace(search, replace);
}
const searchString = coerceToString(search);
const isFunctionalReplace = typeof replace === 'function';
if (!isFunctionalReplace) {
replace = coerceToString(replace);
}
const searchLength = searchString.length;
if (searchLength === 0) {
return replaceAll(subject, /(?:)/g, replace);
}
const advanceBy = searchLength > 1 ? searchLength : 1;
const matchPositions = [];
let position = subjectString.indexOf(searchString, 0);
while (position !== -1) {
matchPositions.push(position);
position = subjectString.indexOf(searchString, position + advanceBy);
}
let endOfLastMatch = 0;
let result = '';
for (let i = 0; i < matchPositions.length; i++) {
const position = matchPositions[i];
let replacement = replace;
if (isFunctionalReplace) {
replacement = coerceToString(replace.call(undefined, searchString, position, subjectString));
}
result += subjectString.slice(endOfLastMatch, position) + replacement;
endOfLastMatch = position + searchLength;
}
if (endOfLastMatch < subjectString.length) {
result += subjectString.slice(endOfLastMatch);
}
return result;
} | Replaces all occurrences of `search` with `replace`. <br/>
@function replaceAll
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to verify.
@param {string|RegExp} search The search pattern to replace. If `search` is a string, a simple string match is evaluated.
All matches are replaced.
@param {string|Function} replace The string or function which invocation result replaces all `search` matches.
@return {string} Returns the replacement result.
@example
v.replaceAll('good morning', 'o', '*');
// => 'g**d m*rning'
v.replaceAll('evening', /n/g, 's');
// => 'evesisg' | replaceAll ( subject , search , replace ) | javascript | panzerdp/voca | src/manipulate/replace_all.js | https://github.com/panzerdp/voca/blob/master/src/manipulate/replace_all.js | MIT |
export default function words(subject, pattern, flags) {
const subjectString = coerceToString(subject);
let patternRegExp;
if (isNil(pattern)) {
patternRegExp = REGEXP_EXTENDED_ASCII.test(subjectString) ? REGEXP_LATIN_WORD : REGEXP_WORD;
} else if (pattern instanceof RegExp) {
patternRegExp = pattern;
} else {
const flagsString = toString(nilDefault(flags, ''));
patternRegExp = new RegExp(toString(pattern), flagsString);
}
return nilDefault(subjectString.match(patternRegExp), []);
} | Splits `subject` into an array of words.
@function words
@static
@since 1.0.0
@memberOf Split
@param {string} [subject=''] The string to split into words.
@param {string|RegExp} [pattern] The pattern to watch words. If `pattern` is not RegExp, it is transformed to `new RegExp(pattern, flags)`.
@param {string} [flags=''] The regular expression flags. Applies when `pattern` is string type.
@return {Array} Returns the array of words.
@example
v.words('gravity can cross dimensions');
// => ['gravity', 'can', 'cross', 'dimensions']
v.words('GravityCanCrossDimensions');
// => ['Gravity', 'Can', 'Cross', 'Dimensions']
v.words('Gravity - can cross dimensions!');
// => ['Gravity', 'can', 'cross', 'dimensions']
v.words('Earth gravity', /[^\s]+/g);
// => ['Earth', 'gravity'] | words ( subject , pattern , flags ) | javascript | panzerdp/voca | src/split/words.js | https://github.com/panzerdp/voca/blob/master/src/split/words.js | MIT |
function wordToCamel(word, index) {
return index === 0 ? lowerCase(word) : capitalize(word, true);
} | Transforms the `word` into camel case chunk.
@param {string} word The word string
@param {number} index The index of the word in phrase.
@return {string} The transformed word.
@ignore | wordToCamel ( word , index ) | javascript | panzerdp/voca | src/case/camel_case.js | https://github.com/panzerdp/voca/blob/master/src/case/camel_case.js | MIT |
export default function appendFlagToRegExp(pattern, appendFlag) {
const regularExpressionFlags = getRegExpFlags(pattern);
if (!includes(regularExpressionFlags, appendFlag)) {
return new RegExp(pattern.source, regularExpressionFlags + appendFlag);
}
return pattern;
} | Append flag to a regular expression.
@ignore
@param {RegExp} pattern The pattern to coerce.
@param {string} appendFlag The flag to append to regular expression.
@return {RegExp} The regular expression with added flag. | appendFlagToRegExp ( pattern , appendFlag ) | javascript | panzerdp/voca | src/helper/reg_exp/append_flag_to_reg_exp.js | https://github.com/panzerdp/voca/blob/master/src/helper/reg_exp/append_flag_to_reg_exp.js | MIT |
export default function getRegExpFlags(regExp) {
return regExp.toString().match(REGEXP_FLAGS)[0];
} | Get the flags string from a regular expression object.
@ignore
@param {RegExp} regExp The regular expression object.
@return {string} Returns the string with flags chars. | getRegExpFlags ( regExp ) | javascript | panzerdp/voca | src/helper/reg_exp/get_reg_exp_flags.js | https://github.com/panzerdp/voca/blob/master/src/helper/reg_exp/get_reg_exp_flags.js | MIT |
export default function toString(value) {
if (isNil(value)) {
return null;
}
if (isString(value)) {
return value;
}
return String(value);
} | Get the string representation of the `value`.
Converts the `value` to string.
@ignore
@function toString
@param {*} value The value to convert.
@return {string|null} Returns the string representation of `value`. | toString ( value ) | javascript | panzerdp/voca | src/helper/string/to_string.js | https://github.com/panzerdp/voca/blob/master/src/helper/string/to_string.js | MIT |
export default function toNumber(value) {
if (isNil(value)) {
return null;
}
return Number(value);
} | Get the number representation of the `value`.
Converts the `value` to a number.
If `value` is `null` or `undefined`, return `null`.
@ignore
@function toNumber
@param {*} value The value to convert.
@return {number|null} Returns the number representation of `value` or `null` if `value` is `null` or `undefined`. | toNumber ( value ) | javascript | panzerdp/voca | src/helper/number/to_number.js | https://github.com/panzerdp/voca/blob/master/src/helper/number/to_number.js | MIT |
export default function nilDefault(value, defaultValue) {
return value == null ? defaultValue : value;
} | Verifies if `value` is `undefined` or `null` and returns `defaultValue`. In other case returns `value`.
@ignore
@function nilDefault
@param {*} value The value to verify.
@param {*} defaultValue The default value.
@return {*} Returns `defaultValue` if `value` is `undefined` or `null`, otherwise `defaultValue`. | nilDefault ( value , defaultValue ) | javascript | panzerdp/voca | src/helper/undefined/nil_default.js | https://github.com/panzerdp/voca/blob/master/src/helper/undefined/nil_default.js | MIT |
const onMouseMove = useCallback(({ clientX, clientY }) => {
setCoords({ x: clientX, y: clientY })
cursorInnerRef.current.style.top = `${clientY}px`
cursorInnerRef.current.style.left = `${clientX}px`
endX.current = clientX
endY.current = clientY
}, []) | Primary Mouse move event
@param {number} clientX - MouseEvent.clientx
@param {number} clientY - MouseEvent.clienty | (anonymous) | javascript | ubaimutl/react-portfolio | src/hooks/AnimatedCursor.js | https://github.com/ubaimutl/react-portfolio/blob/master/src/hooks/AnimatedCursor.js | MIT |
function AnimatedCursor({
outerStyle,
innerStyle,
color,
outerAlpha,
innerSize,
innerScale,
outerSize,
outerScale,
trailingSpeed,
clickables
}) {
if (typeof navigator !== 'undefined' && IsDevice.any()) {
return <React.Fragment></React.Fragment>
}
return (
<CursorCore
outerStyle={outerStyle}
innerStyle={innerStyle}
color={color}
outerAlpha={outerAlpha}
innerSize={innerSize}
innerScale={innerScale}
outerSize={outerSize}
outerScale={outerScale}
trailingSpeed={trailingSpeed}
clickables={clickables}
/>
)
} | AnimatedCursor
Calls and passes props to CursorCore if not a touch/mobile device. | AnimatedCursor ( { outerStyle , innerStyle , color , outerAlpha , innerSize , innerScale , outerSize , outerScale , trailingSpeed , clickables } ) | javascript | ubaimutl/react-portfolio | src/hooks/AnimatedCursor.js | https://github.com/ubaimutl/react-portfolio/blob/master/src/hooks/AnimatedCursor.js | MIT |
function getExchangeRate() {
return new Promise((resolve, reject) => {
let data = '';
const key = process.env.API_KEY;
if (!key) {
return reject('API key is missing!');
}
const req = http.get(
`http://apilayer.net/api/live?access_key=${key}`,
function(res) {
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
const rate = JSON.parse(data);
resolve(convertRate(rate));
});
}
);
req.on('error', e => {
reject(e);
});
});
} | Fetch exchange rate from API for all available currencies.
@returns {
timestamp: number;
quotes: {
USDJPY: 140.01
}
} | getExchangeRate ( ) | javascript | ayastreb/money-tracker | lambda-exchange/handler.js | https://github.com/ayastreb/money-tracker/blob/master/lambda-exchange/handler.js | MIT |
function convertRate(rate) {
return Object.keys(rate.quotes).reduce(
(acc, pair) => {
const code = pair.substr(3, 3);
acc[code] = rate.quotes[pair];
return acc;
},
{ [BASE]: 1 }
);
} | Convert response from API service to internal rate object.
@param {object} dict { ..., quotes: { USDUSD: 1, USDEUR: 0.834499, ... } }
@return {object} dict { USD: 1, EUR: 0.834499, ... } | convertRate ( rate ) | javascript | ayastreb/money-tracker | lambda-exchange/handler.js | https://github.com/ayastreb/money-tracker/blob/master/lambda-exchange/handler.js | MIT |
fromArray(entities, keyPropName = 'id') {
return EntityMap.merge({ byKey: {}, keys: [] }, entities, keyPropName);
}, | Create new entity map from given array.
@param {array} entities
@param {string} keyPropName
@return {object} | fromArray ( entities , keyPropName = 'id' ) | javascript | ayastreb/money-tracker | src/entities/EntityMap.js | https://github.com/ayastreb/money-tracker/blob/master/src/entities/EntityMap.js | MIT |
export default function difference(left, right) {
const diff = new Set();
for (const item of left) {
if (!right.has(item)) diff.add(item);
}
return diff;
} | Return new set containing set difference of given left and right sets.
@param {Set} left
@param {Set} right
@return {Set} | difference ( left , right ) | javascript | ayastreb/money-tracker | src/util/SetDifference.js | https://github.com/ayastreb/money-tracker/blob/master/src/util/SetDifference.js | MIT |
function filterByAccount(docs, accounts) {
if (Array.isArray(accounts)) accounts = new Set(accounts);
if (!accounts || !accounts.size) return docs;
return docs.filter(
tx => accounts.has(tx.accountId) || accounts.has(tx.linkedAccountId)
);
} | Filter transactions by account.
@param {array} docs
@param {Set} accounts
@return {array} | filterByAccount ( docs , accounts ) | javascript | ayastreb/money-tracker | src/util/storage/transactions.js | https://github.com/ayastreb/money-tracker/blob/master/src/util/storage/transactions.js | MIT |
function filterByTags(docs, tags) {
return tags && tags.length > 0
? docs.filter(tx => intersection(tx.tags, tags).length > 0)
: docs;
} | Filter transactions by tag.
@param {array} docs
@param {array} tags
@return {array} | filterByTags ( docs , tags ) | javascript | ayastreb/money-tracker | src/util/storage/transactions.js | https://github.com/ayastreb/money-tracker/blob/master/src/util/storage/transactions.js | MIT |
function fetchCachedRate() {
return new Promise((resolve, reject) => {
context.storage.get((error, rate) => {
if (error) return reject(error);
if (rate === undefined) return reject();
resolve(rate);
});
});
} | Read cached rate from webtask storage.
@see https://webtask.io/docs/storage
@return {Promise} | fetchCachedRate ( ) | javascript | ayastreb/money-tracker | src/webtasks/CurrencyExchange.js | https://github.com/ayastreb/money-tracker/blob/master/src/webtasks/CurrencyExchange.js | MIT |
function fetchLiveRate() {
return new Promise(resolve => {
const apiKey = context.secrets.apiKey;
request(
{
method: 'GET',
uri: `http://apilayer.net/api/live?access_key=${apiKey}`,
json: true
},
(error, response, body) => {
if (error || !body.success) {
fetchCachedRate().then(rate => resolve(rate));
} else {
writeCachedRate(body).then(() => resolve(body));
}
}
);
});
} | Fetch base exchange rate from CurrencyLayer live API.
Fallback to cached rate if API is not available.
@see https://currencylayer.com/documentation
@see https://webtask.io/docs/editor/secrets
@return {Promise} | fetchLiveRate ( ) | javascript | ayastreb/money-tracker | src/webtasks/CurrencyExchange.js | https://github.com/ayastreb/money-tracker/blob/master/src/webtasks/CurrencyExchange.js | MIT |
function writeCachedRate(rate) {
return new Promise((resolve, reject) => {
context.storage.set(rate, { force: 1 }, error =>
error ? reject(error) : resolve()
);
});
} | Write given rate to webtask cache.
@see https://webtask.io/docs/storage
@param {object} rate
@return {Promise} | writeCachedRate ( rate ) | javascript | ayastreb/money-tracker | src/webtasks/CurrencyExchange.js | https://github.com/ayastreb/money-tracker/blob/master/src/webtasks/CurrencyExchange.js | MIT |
function checkCachedRateAge(rate) {
const expiryDate = Math.floor(Date.now() / 1000) - 3600;
return rate.timestamp < expiryDate ? fetchLiveRate() : rate;
} | Validate cached rate expiry date.
@param {object} rate | checkCachedRateAge ( rate ) | javascript | ayastreb/money-tracker | src/webtasks/CurrencyExchange.js | https://github.com/ayastreb/money-tracker/blob/master/src/webtasks/CurrencyExchange.js | MIT |
export function* mapAccountsId(accounts) {
const idByName = new Map();
for (const [name, currency] of accounts.entries()) {
let account = yield select(getAccountByName(name));
if (!account) account = yield createNewAccount(name, [...currency]);
idByName.set(name, account.id);
}
return idByName;
} | Map account name to account ID.
If no account found in local accounts, create new one.
@param {Map} accounts name => set of currencies map
@return {Map} account name => account id map | mapAccountsId ( accounts ) | javascript | ayastreb/money-tracker | src/sagas/dataImport.js | https://github.com/ayastreb/money-tracker/blob/master/src/sagas/dataImport.js | MIT |
stringSimilarity: function (str1, str2, substringLength=2, caseSensitive=false) {
if (!caseSensitive) {
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
}
if (str1.length < substringLength || str2.length < substringLength)
return 0;
var map = new Map();
for (var i = 0; i < str1.length - (substringLength - 1); i++) {
var substr1 = str1.substr(i, substringLength);
map.set(substr1, map.has(substr1) ? map.get(substr1) + 1 : 1);
}
var match = 0;
for (var j = 0; j < str2.length - (substringLength - 1); j++) {
var substr2 = str2.substr(j, substringLength);
var count = map.has(substr2) ? map.get(substr2) : 0;
if (count > 0) {
map.set(substr2, count - 1);
match++;
}
}
return (match * 2) / (str1.length + str2.length - ((substringLength - 1) * 2));
}
}; | Calculate similarity between two strings
@param {string} str1 First string to match
@param {string} str2 Second string to match
@param {number} [substringLength=2] Optional. Length of substring to be used in calculating similarity. Default 2.
@param {boolean} [caseSensitive=false] Optional. Whether you want to consider case in string matching. Default false;
@returns Number between 0 and 1, with 0 being a low match score. | stringSimilarity ( str1 , str2 , substringLength = 2 , caseSensitive = false ) | javascript | mleoking/PromptAppGPT | js/prompt-app-gpt-app-executor.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/prompt-app-gpt-app-executor.js | MIT |
function stringifyURL(stringifyQuery, location) {
const query = location.query ? stringifyQuery(location.query) : '';
return location.path + (query && '?') + query + (location.hash || '');
} | Stringifies a URL object
@param stringifyQuery
@param location | stringifyURL ( stringifyQuery , location ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function stripBase(pathname, base) {
// no base or base is not found at the beginning
if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase()))
return pathname;
return pathname.slice(base.length) || '/';
} | Strips off the base from the beginning of a location.pathname in a non-case-sensitive way.
@param pathname - location.pathname
@param base - base to strip off | stripBase ( pathname , base ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function isSameRouteLocation(stringifyQuery, a, b) {
const aLastIndex = a.matched.length - 1;
const bLastIndex = b.matched.length - 1;
return (aLastIndex > -1 &&
aLastIndex === bLastIndex &&
isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) &&
isSameRouteLocationParams(a.params, b.params) &&
stringifyQuery(a.query) === stringifyQuery(b.query) &&
a.hash === b.hash);
} | Checks if two RouteLocation are equal. This means that both locations are
pointing towards the same {@link RouteRecord} and that all `params`, `query`
parameters and `hash` are the same
@param stringifyQuery - A function that takes a query object of type LocationQueryRaw and returns a string representation of it.
@param a - first {@link RouteLocation}
@param b - second {@link RouteLocation} | isSameRouteLocation ( stringifyQuery , a , b ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function isSameRouteRecord(a, b) {
// since the original record has an undefined value for aliasOf
// but all aliases point to the original record, this will always compare
// the original record
return (a.aliasOf || a) === (b.aliasOf || b);
} | Check if two `RouteRecords` are equal. Takes into account aliases: they are
considered equal to the `RouteRecord` they are aliasing.
@param a - first {@link RouteRecord}
@param b - second {@link RouteRecord} | isSameRouteRecord ( a , b ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function isEquivalentArray(a, b) {
return isArray(b)
? a.length === b.length && a.every((value, i) => value === b[i])
: a.length === 1 && a[0] === b;
} | Check if two arrays are the same or if an array with one single entry is the
same as another primitive value. Used to check query and parameters
@param a - array of values
@param b - array of values or a single value | isEquivalentArray ( a , b ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function createCurrentLocation(base, location) {
const { pathname, search, hash } = location;
// allows hash bases like #, /#, #/, #!, #!/, /#!/, or even /folder#end
const hashPos = base.indexOf('#');
if (hashPos > -1) {
let slicePos = hash.includes(base.slice(hashPos))
? base.slice(hashPos).length
: 1;
let pathFromHash = hash.slice(slicePos);
// prepend the starting slash to hash so the url starts with /#
if (pathFromHash[0] !== '/')
pathFromHash = '/' + pathFromHash;
return stripBase(pathFromHash, '');
}
const path = stripBase(pathname, base);
return path + search + hash;
} | Creates a normalized history location from a window.location object
@param base - The base path
@param location - The window.location object | createCurrentLocation ( base , location ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function createWebHashHistory(base) {
// Make sure this implementation is fine in terms of encoding, specially for IE11
// for `file://`, directly use the pathname and ignore the base
// location.pathname contains an initial `/` even at the root: `https://example.com`
base = location.host ? base || location.pathname + location.search : '';
// allow the user to provide a `#` in the middle: `/base/#/app`
if (!base.includes('#'))
base += '#';
if (!base.endsWith('#/') && !base.endsWith('#')) {
warn(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, '#')}".`);
}
return createWebHistory(base);
} | Creates a hash history. Useful for web applications with no host (e.g. `file://`) or when configuring a server to
handle any URL is not possible.
@param base - optional base to provide. Defaults to `location.pathname + location.search` If there is a `<base>` tag
in the `head`, its value will be ignored in favor of this parameter **but note it affects all the history.pushState()
calls**, meaning that if you use a `<base>` tag, it's `href` value **has to match this parameter** (ignoring anything
after the `#`).
@example
```js
// at https://example.com/folder
createWebHashHistory() // gives a url of `https://example.com/folder#`
createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#`
// if the `#` is provided in the base, it won't be added by `createWebHashHistory`
createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/`
// you should avoid doing this because it changes the original url and breaks copying urls
createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#`
// at file:///usr/etc/folder/index.html
// for locations with no `host`, the base is ignored
createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`
``` | createWebHashHistory ( base ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function compareScoreArray(a, b) {
let i = 0;
while (i < a.length && i < b.length) {
const diff = b[i] - a[i];
// only keep going if diff === 0
if (diff)
return diff;
i++;
}
// if the last subsegment was Static, the shorter segments should be sorted first
// otherwise sort the longest segment first
if (a.length < b.length) {
return a.length === 1 && a[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */
? -1
: 1;
}
else if (a.length > b.length) {
return b.length === 1 && b[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */
? 1
: -1;
}
return 0;
} | Compares an array of numbers as used in PathParser.score and returns a
number. This function can be used to `sort` an array
@param a - first array of numbers
@param b - second array of numbers
@returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
should be sorted first | compareScoreArray ( a , b ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function comparePathParserScore(a, b) {
let i = 0;
const aScore = a.score;
const bScore = b.score;
while (i < aScore.length && i < bScore.length) {
const comp = compareScoreArray(aScore[i], bScore[i]);
// do not return if both are equal
if (comp)
return comp;
i++;
}
if (Math.abs(bScore.length - aScore.length) === 1) {
if (isLastScoreNegative(aScore))
return 1;
if (isLastScoreNegative(bScore))
return -1;
}
// if a and b share the same score entries but b has more, sort b first
return bScore.length - aScore.length;
// this is the ternary version
// return aScore.length < bScore.length
// ? 1
// : aScore.length > bScore.length
// ? -1
// : 0
} | Compare function that can be used with `sort` to sort an array of PathParser
@param a - first PathParser
@param b - second PathParser
@returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b | comparePathParserScore ( a , b ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function isLastScoreNegative(score) {
const last = score[score.length - 1];
return score.length > 0 && last[last.length - 1] < 0;
} | This allows detecting splats at the end of a path: /home/:id(.*)*
@param score - score to check
@returns true if the last entry is negative | isLastScoreNegative ( score ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function normalizeRecordProps(record) {
const propsObject = {};
// props does not exist on redirect records, but we can set false directly
const props = record.props || false;
if ('component' in record) {
propsObject.default = props;
}
else {
// NOTE: we could also allow a function to be applied to every component.
// Would need user feedback for use cases
for (const name in record.components)
propsObject[name] = typeof props === 'boolean' ? props : props[name];
}
return propsObject;
} | Normalize the optional `props` in a record to always be an object similar to
components. Also accept a boolean for components.
@param record | normalizeRecordProps ( record ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function isAliasRecord(record) {
while (record) {
if (record.record.aliasOf)
return true;
record = record.parent;
}
return false;
} | Checks if a record or any of its parent is an alias
@param record | isAliasRecord ( record ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function mergeMetaFields(matched) {
return matched.reduce((meta, record) => assign(meta, record.meta), {});
} | Merge meta fields of an array of records
@param matched - array of matched records | mergeMetaFields ( matched ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function checkSameParams(a, b) {
for (const key of a.keys) {
if (!key.optional && !b.keys.find(isSameParam.bind(null, key)))
return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`);
}
for (const key of b.keys) {
if (!key.optional && !a.keys.find(isSameParam.bind(null, key)))
return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`);
}
} | Check if a path and its alias have the same required params
@param a - original record
@param b - alias record | checkSameParams ( a , b ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent) {
if (parent &&
parent.record.name &&
!mainNormalizedRecord.name &&
!mainNormalizedRecord.path) {
warn(`The route named "${String(parent.record.name)}" has a child without a name and an empty path. Using that name won't render the empty path child so you probably want to move the name to the child instead. If this is intentional, add a name to the child route to remove the warning.`);
}
} | A route with a name and a child with an empty path without a name should warn when adding the route
@param mainNormalizedRecord - RouteRecordNormalized
@param parent - RouteRecordMatcher | checkChildMissingNameWithEmptyPath ( mainNormalizedRecord , parent ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function commonEncode(text) {
return encodeURI('' + text)
.replace(ENC_PIPE_RE, '|')
.replace(ENC_BRACKET_OPEN_RE, '[')
.replace(ENC_BRACKET_CLOSE_RE, ']');
} | Encode characters that need to be encoded on the path, search and hash
sections of the URL.
@internal
@param text - string to encode
@returns encoded string | commonEncode ( text ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function encodeHash(text) {
return commonEncode(text)
.replace(ENC_CURLY_OPEN_RE, '{')
.replace(ENC_CURLY_CLOSE_RE, '}')
.replace(ENC_CARET_RE, '^');
} | Encode characters that need to be encoded on the hash section of the URL.
@param text - string to encode
@returns encoded string | encodeHash ( text ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function encodeQueryValue(text) {
return (commonEncode(text)
// Encode the space as +, encode the + to differentiate it from the space
.replace(PLUS_RE, '%2B')
.replace(ENC_SPACE_RE, '+')
.replace(HASH_RE, '%23')
.replace(AMPERSAND_RE, '%26')
.replace(ENC_BACKTICK_RE, '`')
.replace(ENC_CURLY_OPEN_RE, '{')
.replace(ENC_CURLY_CLOSE_RE, '}')
.replace(ENC_CARET_RE, '^'));
} | Encode characters that need to be encoded query values on the query
section of the URL.
@param text - string to encode
@returns encoded string | encodeQueryValue ( text ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function encodeQueryKey(text) {
return encodeQueryValue(text).replace(EQUAL_RE, '%3D');
} | Like `encodeQueryValue` but also encodes the `=` character.
@param text - string to encode | encodeQueryKey ( text ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function encodePath(text) {
return commonEncode(text).replace(HASH_RE, '%23').replace(IM_RE, '%3F');
} | Encode characters that need to be encoded on the path section of the URL.
@param text - string to encode
@returns encoded string | encodePath ( text ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function encodeParam(text) {
return text == null ? '' : encodePath(text).replace(SLASH_RE, '%2F');
} | Encode characters that need to be encoded on the path section of the URL as a
param. This function encodes everything {@link encodePath} does plus the
slash (`/`) character. If `text` is `null` or `undefined`, returns an empty
string instead.
@param text - string to encode
@returns encoded string | encodeParam ( text ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function decode(text) {
try {
return decodeURIComponent('' + text);
}
catch (err) {
warn(`Error decoding "${text}". Using original value`);
}
return '' + text;
} | Decode text using `decodeURIComponent`. Returns the original text if it
fails.
@param text - string to decode
@returns decoded string | decode ( text ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function onBeforeRouteLeave(leaveGuard) {
if (!vue.getCurrentInstance()) {
warn('getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function');
return;
}
const activeRecord = vue.inject(matchedRouteKey,
// to avoid warning
{}).value;
if (!activeRecord) {
warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside a component child of <router-view>. Maybe you called it inside of App.vue?');
return;
}
registerGuard(activeRecord, 'leaveGuards', leaveGuard);
} | Add a navigation guard that triggers whenever the component for the current
location is about to be left. Similar to {@link beforeRouteLeave} but can be
used in any component. The guard is removed when the component is unmounted.
@param leaveGuard - {@link NavigationGuard} | onBeforeRouteLeave ( leaveGuard ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function onBeforeRouteUpdate(updateGuard) {
if (!vue.getCurrentInstance()) {
warn('getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function');
return;
}
const activeRecord = vue.inject(matchedRouteKey,
// to avoid warning
{}).value;
if (!activeRecord) {
warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside a component child of <router-view>. Maybe you called it inside of App.vue?');
return;
}
registerGuard(activeRecord, 'updateGuards', updateGuard);
} | Add a navigation guard that triggers whenever the current location is about
to be updated. Similar to {@link beforeRouteUpdate} but can be used in any
component. The guard is removed when the component is unmounted.
@param updateGuard - {@link NavigationGuard} | onBeforeRouteUpdate ( updateGuard ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function isRouteComponent(component) {
return (typeof component === 'object' ||
'displayName' in component ||
'props' in component ||
'__vccOpts' in component);
} | Allows differentiating lazy components from functional components and vue-class-component
@internal
@param component | isRouteComponent ( component ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function loadRouteLocation(route) {
return route.matched.every(record => record.redirect)
? Promise.reject(new Error('Cannot load a route that redirects.'))
: Promise.all(route.matched.map(record => record.components &&
Promise.all(Object.keys(record.components).reduce((promises, name) => {
const rawComponent = record.components[name];
if (typeof rawComponent === 'function' &&
!('displayName' in rawComponent)) {
promises.push(rawComponent().then(resolved => {
if (!resolved)
return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}". Ensure you passed a function that returns a promise.`));
const resolvedComponent = isESModule(resolved)
? resolved.default
: resolved;
// replace the function with the resolved component
// cannot be null or undefined because we went into the for loop
record.components[name] = resolvedComponent;
return;
}));
}
return promises;
}, [])))).then(() => route);
} | Ensures a route is loaded, so it can be passed as o prop to `<RouterView>`.
@param route - resolved route to load | loadRouteLocation ( route ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null
? propClass | Utility class to get the active class based on defaults.
@param propClass
@param globalClass
@param defaultClass | getLinkClass | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
api.on.getInspectorState(payload => {
if (payload.app === app && payload.inspectorId === routerInspectorId) {
const routes = matcher.getRoutes();
const route = routes.find(route => route.record.__vd_id === payload.nodeId);
if (route) {
payload.state = {
options: formatRouteRecordMatcherForStateInspector(route),
};
}
}
});
api.sendInspectorTree(routerInspectorId);
api.sendInspectorState(routerInspectorId);
}); | Display information about the currently selected route record | (anonymous) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function checkCanceledNavigationAndReject(to, from) {
const error = checkCanceledNavigation(to, from);
return error ? Promise.reject(error) : Promise.resolve();
} | Helper to reject and skip all navigation guards if a new navigation happened
@param to
@param from | checkCanceledNavigationAndReject ( to , from ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function finalizeNavigation(toLocation, from, isPush, replace, data) {
// a more recent navigation took place
const error = checkCanceledNavigation(toLocation, from);
if (error)
return error;
// only consider as push if it's not the first navigation
const isFirstNavigation = from === START_LOCATION_NORMALIZED;
const state = !isBrowser ? {} : history.state;
// change URL only if the user did a push/replace and if it's not the initial navigation because
// it's just reflecting the url
if (isPush) {
// on the initial navigation, we want to reuse the scroll position from
// history state if it exists
if (replace || isFirstNavigation)
routerHistory.replace(toLocation.fullPath, assign({
scroll: isFirstNavigation && state && state.scroll,
}, data));
else
routerHistory.push(toLocation.fullPath, data);
}
// accept current navigation
currentRoute.value = toLocation;
handleScroll(toLocation, from, isPush, isFirstNavigation);
markAsReady();
} | - Cleans up any navigation guards
- Changes the url if necessary
- Calls the scrollBehavior | finalizeNavigation ( toLocation , from , isPush , replace , data ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function useRouter() {
return vue.inject(routerKey);
} | Returns the router instance. Equivalent to using `$router` inside
templates. | useRouter ( ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
function useRoute() {
return vue.inject(routeLocationKey);
} | Returns the current route location. Equivalent to using `$route` inside
templates. | useRoute ( ) | javascript | mleoking/PromptAppGPT | js/vue-router.global.js | https://github.com/mleoking/PromptAppGPT/blob/master/js/vue-router.global.js | MIT |
const createSqorn = ({ dialect, adapter }) => (config = {}) => {
const { query, expression, parameterize, escape } = dialect
// 1. Create default context properties passed through build tree
const mapKey = memoize(config.mapInputKeys || snakeCase)
const defaultContext = { parameterize, escape, mapKey, build }
// 2. Create Expression Builder
const e = createExpressionBuilder({ defaultContext, expression, config })
// 3. Create Query Builder
const sq = createQueryBuilder({ defaultContext, query, adapter, e, config })
// 4. TODO: Build Executor, Attach e and execute functions
// 5. TODO: Return { sq, e, transaction, db }
return sq
} | Creates a version of Sqorn for the given SQL dialect and database adapter.
A dialect is variant of the SQL language,
while an adapter is the driver that communicates with the database.
This design makes it easy to swap drivers, e.g. mysql vs mysql2 or
add new databases just by connecting a new adapter to an existing dialect. | createSqorn | javascript | sqorn/sqorn | packages/sqorn-lib-core/src/index.js | https://github.com/sqorn/sqorn/blob/master/packages/sqorn-lib-core/src/index.js | MIT |
function getDigest(data) {
return crypto.createHash('sha256').update(data).digest('base64');
} | Returns base-64 encoded SHA-256 digest of provided data
@param {string} data - UTF-8 string to be hashed
@returns {string} | getDigest ( data ) | javascript | ckolderup/postmarks | src/signature.js | https://github.com/ckolderup/postmarks/blob/master/src/signature.js | MIT |
function getSignature(privkey, data) {
const signer = crypto.createSign('sha256');
signer.update(data);
signer.end();
return signer.sign(privkey).toString('base64');
} | Returns base-64 encoded string signed with user's RSA private key
@param {string} privkey - Postmarks user's private key
@param {string} data - UTF-8 string to sign
@returns {string} | getSignature ( privkey , data ) | javascript | ckolderup/postmarks | src/signature.js | https://github.com/ckolderup/postmarks/blob/master/src/signature.js | MIT |
function getSignatureParams(body, method, url) {
const urlObj = new URL(url);
const path = `${urlObj.pathname}${urlObj.search}`;
const requestTarget = `${method.toLowerCase()} ${path}`;
const hostParam = urlObj.hostname;
const date = new Date();
const dateParam = date.toUTCString();
const params = {
'(request-target)': requestTarget,
host: hostParam,
date: dateParam,
};
// add digest param if request body is present
if (body) {
const digest = getDigest(body);
const digestParam = `SHA-256=${digest}`;
params.digest = digestParam;
}
return params;
} | Returns object of params to be used for HTTP signature
@param {BodyInit | null} [body] - Request body for signature digest (usually a JSON string, optional)
@param {string} method - Request HTTP method name
@param {string} url -
@returns {Object} | getSignatureParams ( body , method , url ) | javascript | ckolderup/postmarks | src/signature.js | https://github.com/ckolderup/postmarks/blob/master/src/signature.js | MIT |
function getSignatureHeader(signature, signatureKeys) {
return [
`keyId="https://${domain}/u/${account}"`,
`algorithm="rsa-sha256"`,
`headers="${signatureKeys.join(' ')}"`,
`signature="${signature}"`,
].join(',');
} | Returns the full "Signature" header to be included in the signed request
@param {string} signature - Base-64 encoded request signature
@param {string[]} signatureKeys - Array of param names used when generating the signature
@returns {string} | getSignatureHeader ( signature , signatureKeys ) | javascript | ckolderup/postmarks | src/signature.js | https://github.com/ckolderup/postmarks/blob/master/src/signature.js | MIT |
export async function signedFetch(url, init = {}) {
const privkey = await getPrivateKey(`${account}@${domain}`);
if (!privkey) {
throw new Error(`No private key found for ${account}.`);
}
const { headers = {}, body = null, method = 'GET', ...rest } = init;
const signatureParams = getSignatureParams(body, method, url);
const signatureKeys = Object.keys(signatureParams);
const stringToSign = Object.entries(signatureParams)
.map(([k, v]) => `${k}: ${v}`)
.join('\n');
const signature = getSignature(privkey, stringToSign);
const signatureHeader = getSignatureHeader(signature, signatureKeys);
return fetch(url, {
body,
method,
headers: {
...headers,
Host: signatureParams.host,
Date: signatureParams.date,
Digest: signatureParams.digest,
Signature: signatureHeader,
},
...rest,
});
} | Signs a fetch request with the account's RSA private key
@param {URL | RequestInfo} url - URL (passed to fetch)
@param {RequestInit} [init={}] - Optional fetch init object
@returns {Promise<Response>} | signedFetch ( url , init = { } ) | javascript | ckolderup/postmarks | src/signature.js | https://github.com/ckolderup/postmarks/blob/master/src/signature.js | MIT |
function _signedFetchJSON(url, method = 'GET', init = {}) {
const { body, headers = {}, ...rest } = init;
const contentTypeHeader = body ? { 'Content-Type': 'application/json' } : {};
return signedFetch(url, {
body,
headers: {
...headers,
Accept: 'application/json',
...contentTypeHeader,
},
...rest,
method, // no override
});
} | Private: Adds JSON headers before calling {@link signedFetch}
@private
@param {string} [method="GET"] - HTTP method
@param {URL | RequestInfo} url - URL
@param {RequestInit} [init={}] - Optional fetch init object
@returns {Promise<Response>} | _signedFetchJSON ( url , method = 'GET' , init = { } ) | javascript | ckolderup/postmarks | src/signature.js | https://github.com/ckolderup/postmarks/blob/master/src/signature.js | MIT |
export function signedGetJSON(url, init = {}) {
return _signedFetchJSON(url, 'GET', init);
} | Sends a signed GET request, expecting a JSON response, using {@link signedFetch}
@param {URL | RequestInfo} url - URL
@param {RequestInit} [init={}] - Optional fetch init object
@returns {Promise<Response>} | signedGetJSON ( url , init = { } ) | javascript | ckolderup/postmarks | src/signature.js | https://github.com/ckolderup/postmarks/blob/master/src/signature.js | MIT |
export function signedPostJSON(url, init = {}) {
return _signedFetchJSON(url, 'POST', init);
} | Sends a signed POST request, expecting a JSON response, using {@link signedFetch}
@param {URL | RequestInfo} url - URL
@param {RequestInit} [init={}] - Optional fetch init object
@returns {Promise<Response>} | signedPostJSON ( url , init = { } ) | javascript | ckolderup/postmarks | src/signature.js | https://github.com/ckolderup/postmarks/blob/master/src/signature.js | MIT |
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
} | Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
character of `string`.
@private
@param {string} string The string to inspect.
@returns {number} Returns the index of the last non-whitespace character. | trimmedEndIndex ( string ) | javascript | ractivejs/ractive | sandbox/playground/index.js | https://github.com/ractivejs/ractive/blob/master/sandbox/playground/index.js | MIT |
function baseTrim(string) {
return string
? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
} | The base implementation of `_.trim`.
@private
@param {string} string The string to trim.
@returns {string} Returns the trimmed string. | baseTrim ( string ) | javascript | ractivejs/ractive | sandbox/playground/index.js | https://github.com/ractivejs/ractive/blob/master/sandbox/playground/index.js | MIT |
DiffMatchPatch.prototype.DiffMain = function( text1, text2, optChecklines, optDeadline ) {
var deadline, checklines, commonlength,
commonprefix, commonsuffix, diffs;
// Set a deadline by which time the diff must be complete.
if ( typeof optDeadline === "undefined" ) {
if ( this.DiffTimeout <= 0 ) {
optDeadline = Number.MAX_VALUE;
} else {
optDeadline = ( new Date() ).getTime() + this.DiffTimeout * 1000;
}
}
deadline = optDeadline;
// Check for null inputs.
if ( text1 === null || text2 === null ) {
throw new Error( "Null input. (DiffMain)" );
}
// Check for equality (speedup).
if ( text1 === text2 ) {
if ( text1 ) {
return [
[ DIFF_EQUAL, text1 ]
];
}
return [];
}
if ( typeof optChecklines === "undefined" ) {
optChecklines = true;
}
checklines = optChecklines;
// Trim off common prefix (speedup).
commonlength = this.diffCommonPrefix( text1, text2 );
commonprefix = text1.substring( 0, commonlength );
text1 = text1.substring( commonlength );
text2 = text2.substring( commonlength );
// Trim off common suffix (speedup).
/////////
commonlength = this.diffCommonSuffix( text1, text2 );
commonsuffix = text1.substring( text1.length - commonlength );
text1 = text1.substring( 0, text1.length - commonlength );
text2 = text2.substring( 0, text2.length - commonlength );
// Compute the diff on the middle block.
diffs = this.diffCompute( text1, text2, checklines, deadline );
// Restore the prefix and suffix.
if ( commonprefix ) {
diffs.unshift( [ DIFF_EQUAL, commonprefix ] );
}
if ( commonsuffix ) {
diffs.push( [ DIFF_EQUAL, commonsuffix ] );
}
this.diffCleanupMerge( diffs );
return diffs;
}; | Find the differences between two texts. Simplifies the problem by stripping
any common prefix or suffix off the texts before diffing.
@param {string} text1 Old string to be diffed.
@param {string} text2 New string to be diffed.
@param {boolean=} optChecklines Optional speedup flag. If present and false,
then don't run a line-level diff first to identify the changed areas.
Defaults to true, which does a faster, slightly less optimal diff.
@param {number} optDeadline Optional time when the diff should be complete
by. Used internally for recursive calls. Users should set DiffTimeout
instead.
@return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. | DiffMatchPatch.prototype.DiffMain ( text1 , text2 , optChecklines , optDeadline ) | javascript | ractivejs/ractive | qunit/qunit.js | https://github.com/ractivejs/ractive/blob/master/qunit/qunit.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.