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 |
---|---|---|---|---|---|---|---|
async function resyncLink({ link }, response) {
if (!link) throw new Error('Invalid link provided');
try {
const { success, content = null } = await getLinkText(link);
if (!success) throw new Error(`Failed to sync link content. ${reason}`);
response.status(200).json({ success, content });
} catch (e) {
console.error(e);
response.status(200).json({
success: false,
content: null,
});
}
} | Fetches the content of a raw link. Returns the content as a text string of the link in question.
@param {object} data - metadata from document (eg: link)
@param {import("../../middleware/setDataSigner").ResponseWithSigner} response | resyncLink ( { link } , response ) | javascript | Mintplex-Labs/anything-llm | collector/extensions/resync/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/extensions/resync/index.js | MIT |
async function resyncYouTube({ link }, response) {
if (!link) throw new Error('Invalid link provided');
try {
const { fetchVideoTranscriptContent } = require("../../utils/extensions/YoutubeTranscript");
const { success, reason, content } = await fetchVideoTranscriptContent({ url: link });
if (!success) throw new Error(`Failed to sync YouTube video transcript. ${reason}`);
response.status(200).json({ success, content });
} catch (e) {
console.error(e);
response.status(200).json({
success: false,
content: null,
});
}
} | Fetches the content of a YouTube link. Returns the content as a text string of the video in question.
We offer this as there may be some videos where a transcription could be manually edited after initial scraping
but in general - transcriptions often never change.
@param {object} data - metadata from document (eg: link)
@param {import("../../middleware/setDataSigner").ResponseWithSigner} response | resyncYouTube ( { link } , response ) | javascript | Mintplex-Labs/anything-llm | collector/extensions/resync/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/extensions/resync/index.js | MIT |
constructor({ targetLanguages = "eng" } = {}) {
this.language = this.parseLanguages(targetLanguages);
this.cacheDir = path.resolve(
process.env.STORAGE_DIR
? path.resolve(process.env.STORAGE_DIR, `models`, `tesseract`)
: path.resolve(__dirname, `../../../server/storage/models/tesseract`)
);
// Ensure the cache directory exists or else Tesseract will persist the cache in the default location.
if (!fs.existsSync(this.cacheDir))
fs.mkdirSync(this.cacheDir, { recursive: true });
this.log(
`OCRLoader initialized with language support for:`,
this.language.map((lang) => VALID_LANGUAGE_CODES[lang]).join(", ")
);
} | The constructor for the OCRLoader.
@param {Object} options - The options for the OCRLoader.
@param {string} options.targetLanguages - The target languages to use for the OCR as a comma separated string. eg: "eng,deu,..." | constructor ( { targetLanguages = "eng" } = { } ) | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
async pageToBuffer({ page }) {
if (!this.sharp) await this.init();
try {
this.log(`Converting page ${page.pageNumber} to image...`);
const ops = await page.getOperatorList();
const pageImages = ops.fnArray.length;
for (let i = 0; i < pageImages; i++) {
try {
if (!this.validOps.includes(ops.fnArray[i])) continue;
const name = ops.argsArray[i][0];
const img = await page.objs.get(name);
const { width, height } = img;
const size = img.data.length;
const channels = size / width / height;
const targetDPI = 70;
const targetWidth = Math.floor(width * (targetDPI / 72));
const targetHeight = Math.floor(height * (targetDPI / 72));
const image = this.sharp(img.data, {
raw: { width, height, channels },
density: targetDPI,
})
.resize({
width: targetWidth,
height: targetHeight,
fit: "fill",
})
.withMetadata({
density: targetDPI,
resolution: targetDPI,
})
.png();
// For debugging purposes
// await image.toFile(path.resolve(__dirname, `../../storage/`, `pg${page.pageNumber}.png`));
return await image.toBuffer();
} catch (error) {
this.log(`Iteration error: ${error.message}`, error.stack);
continue;
}
}
this.log(`No valid images found on page ${page.pageNumber}`);
return null;
} catch (error) {
this.log(`Error: ${error.message}`, error.stack);
return null;
}
} | Converts a PDF page to a buffer.
@param {Object} options - The options for the Sharp PDF page object.
@param {Object} options.page - The PDFJS page proxy object.
@returns {Promise<Buffer>} The buffer of the page. | pageToBuffer ( { page } ) | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
function isInvalidIp({ hostname }) {
const IPRegex = new RegExp(
/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gi
);
// Not an IP address at all - passthrough
if (!IPRegex.test(hostname)) return false;
const [octetOne, ..._rest] = hostname.split(".");
// If fails to validate to number - abort and return as invalid.
if (isNaN(Number(octetOne))) return true;
// Allow localhost loopback and 0.0.0.0 for scraping convenience
// for locally hosted services or websites
if (["127.0.0.1", "0.0.0.0"].includes(hostname)) return false;
return INVALID_OCTETS.includes(Number(octetOne));
}
function validURL(url) {
try {
const destination = new URL(url);
if (!VALID_PROTOCOLS.includes(destination.protocol)) return false;
if (isInvalidIp(destination)) return false;
return true;
} catch {}
return false;
}
module.exports = {
validURL,
}; | If an ip address is passed in the user is attempting to collector some internal service running on internal/private IP.
This is not a security feature and simply just prevents the user from accidentally entering invalid IP addresses.
@param {URL} param0
@param {URL['hostname']} param0.hostname
@returns {boolean} | isInvalidIp ( { hostname } ) | javascript | Mintplex-Labs/anything-llm | collector/utils/url/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/url/index.js | MIT |
function validBaseUrl(baseUrl) {
try {
new URL(baseUrl);
return true;
} catch (e) {
return false;
}
} | Validates if the provided baseUrl is a valid URL at all.
@param {string} baseUrl
@returns {boolean} | validBaseUrl ( baseUrl ) | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/Confluence/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/Confluence/index.js | MIT |
function generateChunkSource(
{ doc, baseUrl, spaceKey, accessToken, username, cloud },
encryptionWorker
) {
const payload = {
baseUrl,
spaceKey,
token: accessToken,
username,
cloud,
};
return `confluence://${doc.metadata.url}?payload=${encryptionWorker.encrypt(
JSON.stringify(payload)
)}`;
} | Generate the full chunkSource for a specific Confluence page so that we can resync it later.
This data is encrypted into a single `payload` query param so we can replay credentials later
since this was encrypted with the systems persistent password and salt.
@param {object} chunkSourceInformation
@param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker
@returns {string} | generateChunkSource ( { doc , baseUrl , spaceKey , accessToken , username , cloud } , encryptionWorker ) | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/Confluence/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/Confluence/index.js | MIT |
function resolveRepoLoader(platform = "github") {
switch (platform) {
case "github":
console.log(`Loading GitHub RepoLoader...`);
return require("./GithubRepo/RepoLoader");
case "gitlab":
console.log(`Loading GitLab RepoLoader...`);
return require("./GitlabRepo/RepoLoader");
default:
console.log(`Loading GitHub RepoLoader...`);
return require("./GithubRepo/RepoLoader");
}
} | Dynamically load the correct repository loader from a specific platform
by default will return GitHub.
@param {('github'|'gitlab')} platform
@returns {import("./GithubRepo/RepoLoader")|import("./GitlabRepo/RepoLoader")} the repo loader class for provider | resolveRepoLoader ( platform = "github" ) | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/index.js | MIT |
function resolveRepoLoaderFunction(platform = "github") {
switch (platform) {
case "github":
console.log(`Loading GitHub loader function...`);
return require("./GithubRepo").loadGithubRepo;
case "gitlab":
console.log(`Loading GitLab loader function...`);
return require("./GitlabRepo").loadGitlabRepo;
default:
console.log(`Loading GitHub loader function...`);
return require("./GithubRepo").loadGithubRepo;
}
} | Dynamically load the correct repository loader function from a specific platform
by default will return Github.
@param {('github'|'gitlab')} platform
@returns {import("./GithubRepo")['fetchGithubFile'] | import("./GitlabRepo")['fetchGitlabFile']} the repo loader class for provider | resolveRepoLoaderFunction ( platform = "github" ) | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/index.js | MIT |
async function fetchGithubFile({
repoUrl,
branch,
accessToken = null,
sourceFilePath,
}) {
const repo = new RepoLoader({
repo: repoUrl,
branch,
accessToken,
});
await repo.init();
if (!repo.ready)
return {
success: false,
content: null,
reason: "Could not prepare GitHub repo for loading! Check URL or PAT.",
};
console.log(
`-- Working GitHub ${repo.author}/${repo.project}:${repo.branch} file:${sourceFilePath} --`
);
const fileContent = await repo.fetchSingleFile(sourceFilePath);
if (!fileContent) {
return {
success: false,
reason: "Target file returned a null content response.",
content: null,
};
}
return {
success: true,
reason: null,
content: fileContent,
};
} | Gets the page content from a specific source file in a give GitHub Repo, not all items in a repo.
@returns | fetchGithubFile ( { repoUrl , branch , accessToken = null , sourceFilePath , } ) | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/index.js | MIT |
function generateChunkSource(repo, doc, encryptionWorker) {
const payload = {
owner: repo.author,
project: repo.project,
branch: repo.branch,
path: doc.metadata.source,
pat: !!repo.accessToken ? repo.accessToken : null,
};
return `github://${repo.repo}?payload=${encryptionWorker.encrypt(
JSON.stringify(payload)
)}`;
} | Generate the full chunkSource for a specific file so that we can resync it later.
This data is encrypted into a single `payload` query param so we can replay credentials later
since this was encrypted with the systems persistent password and salt.
@param {RepoLoader} repo
@param {import("@langchain/core/documents").Document} doc
@param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker
@returns {string} | generateChunkSource ( repo , doc , encryptionWorker ) | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/index.js | MIT |
constructor(args = {}) {
this.ready = false;
this.repo = args?.repo;
this.branch = args?.branch;
this.accessToken = args?.accessToken || null;
this.ignorePaths = args?.ignorePaths || [];
this.author = null;
this.project = null;
this.branches = [];
} | Creates an instance of RepoLoader.
@param {RepoLoaderArgs} [args] - The configuration options.
@returns {GitHubRepoLoader} | constructor ( args = { } ) | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | MIT |
constructor(args = {}) {
this.ready = false;
this.repo = args?.repo;
this.branch = args?.branch;
this.accessToken = args?.accessToken || null;
this.ignorePaths = args?.ignorePaths || [];
this.ignoreFilter = ignore().add(this.ignorePaths);
this.withIssues = args?.fetchIssues || false;
this.projectId = null;
this.apiBase = "https://gitlab.com";
this.author = null;
this.project = null;
this.branches = [];
} | Creates an instance of RepoLoader.
@param {RepoLoaderArgs} [args] - The configuration options.
@returns {GitLabRepoLoader} | constructor ( args = { } ) | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
expandPayload(chunkSource = "") {
try {
const url = new URL(chunkSource);
if (!url.searchParams.has("payload")) return url;
const decryptedPayload = this.decrypt(url.searchParams.get("payload"));
const encodedParams = JSON.parse(decryptedPayload);
url.searchParams.delete("payload"); // remove payload prop
// Add all query params needed to replay as query params
Object.entries(encodedParams).forEach(([key, value]) =>
url.searchParams.append(key, value)
);
return url;
} catch (e) {
console.error(e);
}
return new URL(chunkSource);
} | Give a chunk source, parse its payload query param and expand that object back into the URL
as additional query params
@param {string} chunkSource
@returns {URL} Javascript URL object with query params decrypted from payload query param. | expandPayload ( chunkSource = "" ) | javascript | Mintplex-Labs/anything-llm | collector/utils/EncryptionWorker/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/EncryptionWorker/index.js | MIT |
getType(filepath) {
const parsedMime = this.lib.getType(filepath);
if (!!parsedMime) return parsedMime;
return null;
} | Returns the MIME type of the file. If the file has no extension found, it will be processed as a text file.
@param {string} filepath
@returns {string} | getType ( filepath ) | javascript | Mintplex-Labs/anything-llm | collector/utils/files/mime.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/mime.js | MIT |
function isTextType(filepath) {
if (!fs.existsSync(filepath)) return false;
const result = isKnownTextMime(filepath);
if (result.valid) return true; // Known text type - return true.
if (result.reason !== "generic") return false; // If any other reason than generic - return false.
return parseableAsText(filepath); // Fallback to parsing as text via buffer inspection.
} | Checks if a file is text by checking the mime type and then falling back to buffer inspection.
This way we can capture all the cases where the mime type is not known but still parseable as text
without having to constantly add new mime type overrides.
@param {string} filepath - The path to the file.
@returns {boolean} - Returns true if the file is text, false otherwise. | isTextType ( filepath ) | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
function isKnownTextMime(filepath) {
try {
const mimeLib = new MimeDetector();
const mime = mimeLib.getType(filepath);
if (mimeLib.badMimes.includes(mime))
return { valid: false, reason: "bad_mime" };
const type = mime.split("/")[0];
if (mimeLib.nonTextTypes.includes(type))
return { valid: false, reason: "non_text_mime" };
return { valid: true, reason: "valid_mime" };
} catch (e) {
return { valid: false, reason: "generic" };
}
} | Checks if a file is known to be text by checking the mime type.
@param {string} filepath - The path to the file.
@returns {boolean} - Returns true if the file is known to be text, false otherwise. | isKnownTextMime ( filepath ) | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
async function getLinkText(link, captureAs = "text") {
if (!validURL(link)) return { success: false, reason: "Not a valid URL." };
return await scrapeGenericUrl(link, captureAs, false);
} | Get the text content of a link
@param {string} link - The link to get the text content of
@param {('html' | 'text' | 'json')} captureAs - The format to capture the page content as
@returns {Promise<{success: boolean, content: string}>} - Response from collector | getLinkText ( link , captureAs = "text" ) | javascript | Mintplex-Labs/anything-llm | collector/processLink/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/processLink/index.js | MIT |
async function getPageContent(link, captureAs = "text") {
try {
let pageContents = [];
const loader = new PuppeteerWebBaseLoader(link, {
launchOptions: {
headless: "new",
ignoreHTTPSErrors: true,
},
gotoOptions: {
waitUntil: "networkidle2",
},
async evaluate(page, browser) {
const result = await page.evaluate((captureAs) => {
if (captureAs === "text") return document.body.innerText;
if (captureAs === "html") return document.documentElement.innerHTML;
return document.body.innerText;
}, captureAs);
await browser.close();
return result;
},
});
const docs = await loader.load();
for (const doc of docs) {
pageContents.push(doc.pageContent);
}
return pageContents.join(" ");
} catch (error) {
console.error(
"getPageContent failed to be fetched by puppeteer - falling back to fetch!",
error
);
}
try {
const pageText = await fetch(link, {
method: "GET",
headers: {
"Content-Type": "text/plain",
"User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36,gzip(gfe)",
},
}).then((res) => res.text());
return pageText;
} catch (error) {
console.error("getPageContent failed to be fetched by any method.", error);
}
return null;
} | Get the content of a page
@param {string} link - The URL to get the content of
@param {('html' | 'text')} captureAs - The format to capture the page content as
@returns {Promise<string>} - The content of the page | getPageContent ( link , captureAs = "text" ) | javascript | Mintplex-Labs/anything-llm | collector/processLink/convert/generic.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/processLink/convert/generic.js | MIT |
closeIfNotUsed() {
const isUsed = this.subscribers.length > 0;
if (isUsed) {
return;
}
this.close();
} | If there's no subscriber on this DataSubscription, we will close it. | closeIfNotUsed ( ) | javascript | digitallyinduced/thin-backend | datasync.js | https://github.com/digitallyinduced/thin-backend/blob/master/datasync.js | MIT |
export function runChildCompiler (compiler) {
return new Promise((resolve, reject) => {
compiler.compile((err, compilation) => {
// still allow the parent compiler to track execution of the child:
compiler.parentCompilation.children.push(compilation);
if (err) return reject(err);
// Bubble stat errors up and reject the Promise:
if (compilation.errors && compilation.errors.length) {
const errorDetails = compilation.errors.map(error => error.details).join('\n');
return reject(Error('Child compilation failed:\n' + errorDetails));
}
resolve(compilation);
});
});
} | Promisified version of compiler.runAsChild() with error hoisting and isolated output/assets.
(runAsChild() merges assets into the parent compilation, we don't want that) | runChildCompiler ( compiler ) | javascript | GoogleChromeLabs/prerender-loader | src/util.js | https://github.com/GoogleChromeLabs/prerender-loader/blob/master/src/util.js | Apache-2.0 |
function isNil(value) {
return value === undefined || value === null;
} | Checks if `value` is `null` or `undefined`
@ignore
@function isNil
@param {*} value The object to check
@return {boolean} Returns `true` is `value` is `undefined` or `null`, `false` otherwise | isNil ( value ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function coerceToBoolean(value) {
var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (isNil(value)) {
return defaultValue;
}
return Boolean(value);
} | Converts the `value` to a boolean. If `value` is `undefined` or `null`, returns `defaultValue`.
@ignore
@function toBoolean
@param {*} value The value to convert.
@param {boolean} [defaultValue=false] The default value.
@return {boolean} Returns the coercion to boolean. | coerceToBoolean ( value ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isString(subject) {
return typeof subject === 'string';
} | Checks whether `subject` is a string primitive type.
@function isString
@static
@since 1.0.0
@memberOf Query
@param {string} subject The value to verify.
@return {boolean} Returns `true` if `subject` is string primitive type or `false` otherwise.
@example
v.isString('vacation');
// => true
v.isString(560);
// => false | isString ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function coerceToString(value) {
var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
if (isNil(value)) {
return defaultValue;
}
if (isString(value)) {
return value;
}
return String(value);
} | Get the string representation of the `value`.
Converts the `value` to string.
If `value` is `null` or `undefined`, return `defaultValue`.
@ignore
@function toString
@param {*} value The value to convert.
@param {*} [defaultValue=''] The default value to return.
@return {string|null} Returns the string representation of `value`. Returns `defaultValue` if `value` is
`null` or `undefined`. | coerceToString ( value ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function capitalize(subject, restToLower) {
var subjectString = coerceToString(subject);
var restToLowerCaseBoolean = coerceToBoolean(restToLower);
if (subjectString === '') {
return '';
}
if (restToLowerCaseBoolean) {
subjectString = subjectString.toLowerCase();
}
return subjectString.substr(0, 1).toUpperCase() + subjectString.substr(1);
} | Converts the first character of `subject` to upper case. If `restToLower` is `true`, convert the rest of
`subject` to lower case.
@function capitalize
@static
@since 1.0.0
@memberOf Case
@param {string} [subject=''] The string to capitalize.
@param {boolean} [restToLower=false] Convert the rest of `subject` to lower case.
@return {string} Returns the capitalized string.
@example
v.capitalize('apple');
// => 'Apple'
v.capitalize('aPPle', true);
// => 'Apple' | capitalize ( subject , restToLower ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function lowerCase(subject) {
var subjectString = coerceToString(subject, '');
return subjectString.toLowerCase();
} | Converts the `subject` to lower case.
@function lowerCase
@static
@since 1.0.0
@memberOf Case
@param {string} [subject=''] The string to convert to lower case.
@return {string} Returns the lower case string.
@example
v.lowerCase('Green');
// => 'green'
v.lowerCase('BLUE');
// => 'blue' | lowerCase ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function camelCase(subject) {
var subjectString = coerceToString(subject);
if (subjectString === '') {
return '';
}
return words(subjectString)
.map(wordToCamel)
.join('');
} | Converts the `subject` to <a href="https://en.wikipedia.org/wiki/CamelCase">camel case</a>.
@function camelCase
@static
@since 1.0.0
@memberOf Case
@param {string} [subject=''] The string to convert to camel case.
@return {string} The camel case string.
@example
v.camelCase('bird flight');
// => 'birdFlight'
v.camelCase('BirdFlight');
// => 'birdFlight'
v.camelCase('-BIRD-FLIGHT-');
// => 'birdFlight' | camelCase ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function decapitalize(subject) {
var subjectString = coerceToString(subject);
if (subjectString === '') {
return '';
}
return subjectString.substr(0, 1).toLowerCase() + subjectString.substr(1);
} | Converts the first character of `subject` to lower case.
@function decapitalize
@static
@since 1.0.0
@memberOf Case
@param {string} [subject=''] The string to decapitalize.
@return {string} Returns the decapitalized string.
@example
v.decapitalize('Sun');
// => 'sun'
v.decapitalize('moon');
// => 'moon' | decapitalize ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function kebabCase(subject) {
var subjectString = coerceToString(subject);
if (subjectString === '') {
return '';
}
return words(subjectString)
.map(lowerCase)
.join('-');
} | Converts the `subject` to <a href="https://en.wikipedia.org/wiki/Letter_case#cite_ref-13">kebab case</a>,
also called <i>spinal case</i> or <i>lisp case</i>.
@function kebabCase
@static
@since 1.0.0
@memberOf Case
@param {string} [subject=''] The string to convert to kebab case.
@return {string} Returns the kebab case string.
@example
v.kebabCase('goodbye blue sky');
// => 'goodbye-blue-sky'
v.kebabCase('GoodbyeBlueSky');
// => 'goodbye-blue-sky'
v.kebabCase('-Goodbye-Blue-Sky-');
// => 'goodbye-blue-sky' | kebabCase ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function snakeCase(subject) {
var subjectString = coerceToString(subject);
if (subjectString === '') {
return '';
}
return words(subjectString)
.map(lowerCase)
.join('_');
} | Converts the `subject` to <a href="https://en.wikipedia.org/wiki/Snake_case">snake case</a>.
@function snakeCase
@static
@since 1.0.0
@memberOf Case
@param {string} [subject=''] The string to convert to snake case.
@return {string} Returns the snake case string.
@example
v.snakeCase('learning to fly');
// => 'learning_to_fly'
v.snakeCase('LearningToFly');
// => 'learning_to_fly'
v.snakeCase('-Learning-To-Fly-');
// => 'learning_to_fly' | snakeCase ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function upperCase(subject) {
var subjectString = coerceToString(subject);
return subjectString.toUpperCase();
} | Converts the `subject` to upper case.
@function upperCase
@static
@since 1.0.0
@memberOf Case
@param {string} [subject=''] The string to convert to upper case.
@return {string} Returns the upper case string.
@example
v.upperCase('school');
// => 'SCHOOL' | upperCase ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function swapCase(subject) {
var subjectString = coerceToString(subject);
return subjectString.split('').reduce(swapAndConcat, '');
} | Converts the uppercase alpha characters of `subject` to lowercase and lowercase
characters to uppercase.
@function swapCase
@static
@since 1.3.0
@memberOf Case
@param {string} [subject=''] The string to swap the case.
@return {string} Returns the converted string.
@example
v.swapCase('League of Shadows');
// => 'lEAGUE OF sHADOWS'
v.swapCase('2 Bees');
// => '2 bEES' | swapCase ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function titleCase(subject, noSplit) {
var subjectString = coerceToString(subject);
var noSplitArray = Array.isArray(noSplit) ? noSplit : [];
var wordsRegExp = REGEXP_EXTENDED_ASCII.test(subjectString) ? REGEXP_LATIN_WORD : REGEXP_WORD;
return subjectString.replace(wordsRegExp, function(word, index) {
var isNoSplit = index > 0 && noSplitArray.indexOf(subjectString[index - 1]) >= 0;
return isNoSplit ? word.toLowerCase() : capitalize(word, true);
});
} | Converts the subject to title case.
@function titleCase
@static
@since 1.4.0
@memberOf Case
@param {string} [subject=''] The string to convert to title case.
@param {Array} [noSplit] Do not split words at the specified characters.
@return {string} Returns the title case string.
@example
v.titleCase('learning to fly');
// => 'Learning To Fly'
v.titleCase('jean-luc is good-looking', ['-']);
// => 'Jean-luc Is Good-looking' | titleCase ( subject , noSplit ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function clipNumber(value, downLimit, upLimit) {
if (value <= downLimit) {
return downLimit;
}
if (value >= upLimit) {
return upLimit;
}
return value;
} | Clip the number to interval `downLimit` to `upLimit`.
@ignore
@function clipNumber
@param {number} value The number to clip
@param {number} downLimit The down limit
@param {number} upLimit The upper limit
@return {number} The clipped number | clipNumber ( value , downLimit , upLimit ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function toInteger(value) {
if (value === Infinity) {
return MAX_SAFE_INTEGER;
}
if (value === -Infinity) {
return -MAX_SAFE_INTEGER;
}
return ~~value;
} | Transforms `value` to an integer.
@ignore
@function toInteger
@param {number} value The number to transform.
@returns {number} Returns the transformed integer. | toInteger ( value ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function truncate(subject, length, end) {
var subjectString = coerceToString(subject);
var lengthInt = isNil(length) ? subjectString.length : clipNumber(toInteger(length), 0, MAX_SAFE_INTEGER);
var endString = coerceToString(end, '...');
if (lengthInt >= subjectString.length) {
return subjectString;
}
return subjectString.substr(0, length - endString.length) + endString;
} | Truncates `subject` to a new `length`.
@function truncate
@static
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to truncate.
@param {int} length The length to truncate the string.
@param {string} [end='...'] The string to be added at the end.
@return {string} Returns the truncated string.
@example
v.truncate('Once upon a time', 7);
// => 'Once...'
v.truncate('Good day, Little Red Riding Hood', 14, ' (...)');
// => 'Good day (...)'
v.truncate('Once upon', 10);
// => 'Once upon' | truncate ( subject , length , end ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function charAt(subject, position) {
var subjectString = coerceToString(subject);
return subjectString.charAt(position);
} | Access a character from `subject` at specified `position`.
@function charAt
@static
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to extract from.
@param {numbers} position The position to get the character.
@return {string} Returns the character at specified position.
@example
v.charAt('helicopter', 0);
// => 'h'
v.charAt('helicopter', 1);
// => 'e' | charAt ( subject , position ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isHighSurrogate(codePoint) {
return codePoint >= HIGH_SURROGATE_START && codePoint <= HIGH_SURROGATE_END;
} | Checks if `codePoint` is a high-surrogate number from range 0xD800 to 0xDBFF.
@ignore
@param {number} codePoint The code point number to be verified
@return {boolean} Returns a boolean whether `codePoint` is a high-surrogate number. | isHighSurrogate ( codePoint ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function isLowSurrogate(codePoint) {
return codePoint >= LOW_SURROGATE_START && codePoint <= LOW_SURROGATE_END;
} | Checks if `codePoint` is a low-surrogate number from range 0xDC00 to 0xDFFF.
@ignore
@param {number} codePoint The code point number to be verified
@return {boolean} Returns a boolean whether `codePoint` is a low-surrogate number. | isLowSurrogate ( codePoint ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function getAstralNumberFromSurrogatePair(highSurrogate, lowSurrogate) {
return (highSurrogate - HIGH_SURROGATE_START) * 0x400 + lowSurrogate - LOW_SURROGATE_START + 0x10000;
} | Get the astral code point number based on surrogate pair numbers.
@ignore
@param {number} highSurrogate The high-surrogate code point number.
@param {number} lowSurrogate The low-surrogate code point number.
@return {number} Returns the astral symbol number. | getAstralNumberFromSurrogatePair ( highSurrogate , lowSurrogate ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function coerceToNumber(value) {
var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (isNil(value)) {
return defaultValue;
}
if (typeof value === 'number') {
return value;
}
return Number(value);
} | Get the number representation of the `value`.
Converts the `value` to number.
If `value` is `null` or `undefined`, return `defaultValue`.
@ignore
@function toString
@param {*} value The value to convert.
@param {*} [defaultValue=''] The default value to return.
@return {number|null} Returns the number representation of `value`. Returns `defaultValue` if `value` is
`null` or `undefined`. | coerceToNumber ( value ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function nanDefault(value, defaultValue) {
return value !== value ? defaultValue : value;
} | If `value` is `NaN`, return `defaultValue`. In other case returns `value`.
@ignore
@function nanDefault
@param {*} value The value to verify.
@param {*} defaultValue The default value.
@return {*} Returns `defaultValue` if `value` is `NaN`, otherwise `defaultValue`. | nanDefault ( value , defaultValue ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function codePointAt(subject, position) {
var subjectString = coerceToString(subject);
var subjectStringLength = subjectString.length;
var positionNumber = coerceToNumber(position);
positionNumber = nanDefault(positionNumber, 0);
if (positionNumber < 0 || positionNumber >= subjectStringLength) {
return undefined;
}
var firstCodePoint = subjectString.charCodeAt(positionNumber);
var secondCodePoint;
if (isHighSurrogate(firstCodePoint) && subjectStringLength > positionNumber + 1) {
secondCodePoint = subjectString.charCodeAt(positionNumber + 1);
if (isLowSurrogate(secondCodePoint)) {
return getAstralNumberFromSurrogatePair(firstCodePoint, secondCodePoint);
}
}
return firstCodePoint;
} | Get the Unicode code point value of the character at `position`. <br/>
If a valid UTF-16 <a href="https://rainsoft.io/what-every-javascript-developer-should-know-about-unicode/#24surrogatepairs">
surrogate pair</a> starts at `position`, the
<a href="https://rainsoft.io/what-every-javascript-developer-should-know-about-unicode/#astralplanes">astral code point</a>
value at `position` is returned.
@function codePointAt
@static
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to extract from.
@param {number} position The position to get the code point number.
@return {number} Returns a non-negative number less than or equal to `0x10FFFF`.
@example
v.codePointAt('rain', 1);
// => 97, or 0x0061
v.codePointAt('\uD83D\uDE00 is smile', 0); // or '😀 is smile'
// => 128512, or 0x1F600 | codePointAt ( subject , position ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function first(subject, length) {
var subjectString = coerceToString(subject);
var lengthInt = isNil(length) ? 1 : clipNumber(toInteger(length), 0, MAX_SAFE_INTEGER);
if (subjectString.length <= lengthInt) {
return subjectString;
}
return subjectString.substr(0, lengthInt);
} | Extracts the first `length` characters from `subject`.
@function first
@static
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to extract from.
@param {int} [length=1] The number of characters to extract.
@return {string} Returns the first characters string.
@example
v.first('helicopter');
// => 'h'
v.first('vehicle', 2);
// => 've'
v.first('car', 5);
// => 'car' | first ( subject , length ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function graphemeAt(subject, position) {
var subjectString = coerceToString(subject);
var positionNumber = coerceToNumber(position);
var graphemeMatch;
var graphemeMatchIndex = 0;
positionNumber = nanDefault(positionNumber, 0);
while ((graphemeMatch = REGEXP_UNICODE_CHARACTER.exec(subjectString)) !== null) {
if (graphemeMatchIndex === positionNumber) {
REGEXP_UNICODE_CHARACTER.lastIndex = 0;
return graphemeMatch[0];
}
graphemeMatchIndex++;
}
return '';
} | Get a grapheme from `subject` at specified `position` 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 graphemeAt
@static
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to extract from.
@param {number} position The position to get the grapheme.
@return {string} Returns the grapheme at specified position.
@example
v.graphemeAt('\uD835\uDC00\uD835\uDC01', 0); // or '𝐀𝐁'
// => 'A'
v.graphemeAt('cafe\u0301', 3); // or 'café'
// => 'é' | graphemeAt ( subject , position ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function last(subject, length) {
var subjectString = coerceToString(subject);
var lengthInt = isNil(length) ? 1 : clipNumber(toInteger(length), 0, MAX_SAFE_INTEGER);
if (subjectString.length <= lengthInt) {
return subjectString;
}
return subjectString.substr(subjectString.length - lengthInt, lengthInt);
} | Extracts the last `length` characters from `subject`.
@function last
@static
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to extract from.
@param {int} [length=1] The number of characters to extract.
@return {string} Returns the last characters string.
@example
v.last('helicopter');
// => 'r'
v.last('vehicle', 2);
// => 'le'
v.last('car', 5);
// => 'car' | last ( subject , length ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function prune(subject, length, end) {
var subjectString = coerceToString(subject);
var lengthInt = isNil(length) ? subjectString.length : clipNumber(toInteger(length), 0, MAX_SAFE_INTEGER);
var endString = coerceToString(end, '...');
if (lengthInt >= subjectString.length) {
return subjectString;
}
var pattern = REGEXP_EXTENDED_ASCII.test(subjectString) ? REGEXP_LATIN_WORD : REGEXP_WORD;
var truncatedLength = 0;
subjectString.replace(pattern, function(word, offset) {
var wordInsertLength = offset + word.length;
if (wordInsertLength <= lengthInt - endString.length) {
truncatedLength = wordInsertLength;
}
});
return subjectString.substr(0, truncatedLength) + endString;
} | Truncates `subject` to a new `length` and does not break the words. Guarantees that the truncated string is no longer
than `length`.
@static
@function prune
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to prune.
@param {int} length The length to prune the string.
@param {string} [end='...'] The string to be added at the end.
@return {string} Returns the pruned string.
@example
v.prune('Once upon a time', 7);
// => 'Once...'
v.prune('Good day, Little Red Riding Hood', 16, ' (more)');
// => 'Good day (more)'
v.prune('Once upon', 10);
// => 'Once upon' | prune ( subject , length , end ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function slice(subject, start, end) {
return coerceToString(subject).slice(start, end);
} | Extracts from `subject` a string from `start` position up to `end` position. The character at `end` position is not
included.
@function slice
@static
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to extract from.
@param {number} start The position to start extraction. If negative use `subject.length + start`.
@param {number} [end=subject.length] The position to end extraction. If negative use `subject.length + end`.
@return {string} Returns the extracted string.
@note Uses native `String.prototype.slice()`
@example
v.slice('miami', 1);
// => 'iami'
v.slice('florida', -4);
// => 'rida'
v.slice('florida', 1, 4);
// => "lor" | slice ( subject , start , end ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function substr(subject, start, length) {
return coerceToString(subject).substr(start, length);
} | Extracts from `subject` a string from `start` position a number of `length` characters.
@function substr
@static
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to extract from.
@param {number} start The position to start extraction.
@param {number} [length=subject.endOfString] The number of characters to extract. If omitted, extract to the end of `subject`.
@return {string} Returns the extracted string.
@note Uses native `String.prototype.substr()`
@example
v.substr('infinite loop', 9);
// => 'loop'
v.substr('dreams', 2, 2);
// => 'ea' | substr ( subject , start , length ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function substring(subject, start, end) {
return coerceToString(subject).substring(start, end);
} | Extracts from `subject` a string from `start` position up to `end` position. The character at `end` position is not
included.
@function substring
@static
@since 1.0.0
@memberOf Chop
@param {string} [subject=''] The string to extract from.
@param {number} start The position to start extraction.
@param {number} [end=subject.length] The position to end extraction.
@return {string} Returns the extracted string.
@note Uses native `String.prototype.substring()`
@example
v.substring('beach', 1);
// => 'each'
v.substring('ocean', 1, 3);
// => 'ea' | substring ( subject , start , end ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function count(subject) {
return coerceToString(subject).length;
} | Counts the characters in `subject`.<br/>
@function count
@static
@since 1.0.0
@memberOf Count
@param {string} [subject=''] The string to count characters.
@return {number} Returns the number of characters in `subject`.
@example
v.count('rain');
// => 4 | count ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function countGrapheme(subject) {
return coerceToString(subject)
.replace(REGEXP_COMBINING_MARKS, '*')
.replace(REGEXP_SURROGATE_PAIRS, '*').length;
} | Counts the graphemes in `subject` 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 countGraphemes
@static
@since 1.0.0
@memberOf Count
@param {string} [subject=''] The string to count graphemes.
@return {number} Returns the number of graphemes in `subject`.
@example
v.countGraphemes('cafe\u0301'); // or 'café'
// => 4
v.countGraphemes('\uD835\uDC00\uD835\uDC01'); // or '𝐀𝐁'
// => 2
v.countGraphemes('rain');
// => 4 | countGrapheme ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function countSubstrings(subject, substring) {
var subjectString = coerceToString(subject);
var substringString = coerceToString(substring);
var substringLength = substringString.length;
var count = 0;
var matchIndex = 0;
if (subjectString === '' || substringString === '') {
return count;
}
do {
matchIndex = subjectString.indexOf(substringString, matchIndex);
if (matchIndex !== -1) {
count++;
matchIndex += substringLength;
}
} while (matchIndex !== -1);
return count;
} | Counts the number of `substring` appearances in `subject`.
@function countSubstrings
@static
@since 1.0.0
@memberOf Count
@param {string} [subject=''] The string where to count.
@param {string} substring The substring to be counted.
@return {number} Returns the number of `substring` appearances.
@example
v.countSubstrings('bad boys, bad boys whatcha gonna do?', 'boys');
// => 2
v.countSubstrings('every dog has its day', 'cat');
// => 0 | countSubstrings ( subject , substring ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function countWhere(subject, predicate, context) {
var subjectString = coerceToString(subject);
if (subjectString === '' || typeof predicate !== 'function') {
return 0;
}
var predicateWithContext = predicate.bind(context);
return reduce.call(
subjectString,
function(countTruthy, character, index) {
return predicateWithContext(character, index, subjectString) ? countTruthy + 1 : countTruthy;
},
0
);
} | Counts the characters in `subject` for which `predicate` returns truthy.
@function countWhere
@static
@since 1.0.0
@memberOf Count
@param {string} [subject=''] The string to count characters.
@param {Function} predicate The predicate function invoked on each character with parameters `(character, index, string)`.
@param {Object} [context] The context to invoke the `predicate`.
@return {number} Returns the number of characters for which `predicate` returns truthy.
@example
v.countWhere('hola!', v.isAlpha);
// => 4
v.countWhere('2022', function(character, index, str) {
return character === '2';
});
// => 3 | countWhere ( subject , predicate , context ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function countWords(subject, pattern, flags) {
return words(subject, pattern, flags).length;
} | Counts the number of words in `subject`.
@function countWords
@static
@since 1.0.0
@memberOf Count
@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 {number} Returns the number of words.
@example
v.countWords('gravity can cross dimensions');
// => 4
v.countWords('GravityCanCrossDimensions');
// => 4
v.countWords('Gravity - can cross dimensions!');
// => 4
v.words('Earth gravity', /[^\s]+/g);
// => 2 | countWords ( subject , pattern , flags ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function ReplacementIndex() {
this.index = 0;
} | The current index.
@ignore
@name ReplacementIndex#index
@type {number}
@return {ReplacementIndex} ReplacementIndex instance. | ReplacementIndex ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ReplacementIndex.prototype.increment = function() {
this.index++;
}; | Increment the current index.
@ignore
@return {undefined} | ReplacementIndex.prototype.increment ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ReplacementIndex.prototype.incrementOnEmptyPosition = function(position) {
if (isNil(position)) {
this.increment();
}
}; | Increment the current index by position.
@ignore
@param {number} [position] The replacement position.
@return {undefined} | ReplacementIndex.prototype.incrementOnEmptyPosition ( position ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ReplacementIndex.prototype.getIndexByPosition = function(position) {
return isNil(position) ? this.index : position - 1;
}; | Get the replacement index by position.
@ignore
@param {number} [position] The replacement position.
@return {number} The replacement index. | ReplacementIndex.prototype.getIndexByPosition ( position ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function repeat(subject, times) {
var subjectString = coerceToString(subject);
var timesInt = isNil(times) ? 1 : clipNumber(toInteger(times), 0, MAX_SAFE_INTEGER);
var repeatString = '';
while (timesInt) {
if (timesInt & 1) {
repeatString += subjectString;
}
if (timesInt > 1) {
subjectString += subjectString;
}
timesInt >>= 1;
}
return repeatString;
} | Repeats the `subject` number of `times`.
@function repeat
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to repeat.
@param {number} [times=1] The number of times to repeat.
@return {string} Returns the repeated string.
@example
v.repeat('w', 3);
// => 'www'
v.repeat('world', 0);
// => '' | repeat ( subject , times ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function buildPadding(padCharacters, length) {
var padStringRepeat = toInteger(length / padCharacters.length);
var padStringRest = length % padCharacters.length;
return repeat(padCharacters, padStringRepeat + padStringRest).substr(0, length);
} | Creates the padding string.
@ignore
@param {string} padCharacters The characters to create padding string.
@param {number} length The padding string length.
@return {string} The padding string. | buildPadding ( padCharacters , length ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function padLeft(subject, length, pad) {
var subjectString = coerceToString(subject);
var lengthInt = isNil(length) ? 0 : clipNumber(toInteger(length), 0, MAX_SAFE_INTEGER);
var padString = coerceToString(pad, ' ');
if (lengthInt <= subjectString.length) {
return subjectString;
}
return buildPadding(padString, lengthInt - subjectString.length) + subjectString;
} | Pads `subject` from left to a new `length`.
@function padLeft
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to pad.
@param {int} [length=0] The length to left pad the string. No changes are made if `length` is less than `subject.length`.
@param {string} [pad=' '] The string to be used for padding.
@return {string} Returns the left padded string.
@example
v.padLeft('dog', 5);
// => ' dog'
v.padLeft('bird', 6, '-');
// => '--bird'
v.padLeft('cat', 6, '-=');
// => '-=-cat' | padLeft ( subject , length , pad ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function padRight(subject, length, pad) {
var subjectString = coerceToString(subject);
var lengthInt = isNil(length) ? 0 : clipNumber(toInteger(length), 0, MAX_SAFE_INTEGER);
var padString = coerceToString(pad, ' ');
if (lengthInt <= subjectString.length) {
return subjectString;
}
return subjectString + buildPadding(padString, lengthInt - subjectString.length);
} | Pads `subject` from right to a new `length`.
@function padRight
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to pad.
@param {int} [length=0] The length to right pad the string. No changes are made if `length` is less than `subject.length`.
@param {string} [pad=' '] The string to be used for padding.
@return {string} Returns the right padded string.
@example
v.padRight('dog', 5);
// => 'dog '
v.padRight('bird', 6, '-');
// => 'bird--'
v.padRight('cat', 6, '-=');
// => 'cat-=-' | padRight ( subject , length , pad ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function alignAndPad(subject, conversion) {
var width = conversion.width;
if (isNil(width) || subject.length >= width) {
return subject;
}
var padType = conversion.alignmentSpecifier === LITERAL_MINUS ? padRight : padLeft;
return padType(subject, width, conversion.getPaddingCharacter());
} | Aligns and pads `subject` string.
@ignore
@param {string} subject The subject string.
@param {ConversionSpecification} conversion The conversion specification object.
@return {string} Returns the aligned and padded string. | alignAndPad ( subject , conversion ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function addSignToFormattedNumber(replacementNumber, formattedReplacement, conversion) {
if (conversion.signSpecifier === LITERAL_PLUS && replacementNumber >= 0) {
formattedReplacement = LITERAL_PLUS + formattedReplacement;
}
return formattedReplacement;
} | Add sign to the formatted number.
@ignore
@name addSignToFormattedNumber
@param {number} replacementNumber The number to be replaced.
@param {string} formattedReplacement The formatted version of number.
@param {ConversionSpecification} conversion The conversion specification object.
@return {string} Returns the formatted number string with a sign. | addSignToFormattedNumber ( replacementNumber , formattedReplacement , conversion ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function float(replacement, conversion) {
var replacementNumber = parseFloat(replacement);
var formattedReplacement;
if (isNaN(replacementNumber)) {
replacementNumber = 0;
}
var precision = coerceToNumber(conversion.precision, 6);
switch (conversion.typeSpecifier) {
case TYPE_FLOAT:
formattedReplacement = replacementNumber.toFixed(precision);
break;
case TYPE_FLOAT_SCIENTIFIC:
formattedReplacement = replacementNumber.toExponential(precision);
break;
case TYPE_FLOAT_SCIENTIFIC_UPPERCASE:
formattedReplacement = replacementNumber.toExponential(precision).toUpperCase();
break;
case TYPE_FLOAT_SHORT:
case TYPE_FLOAT_SHORT_UPPERCASE:
formattedReplacement = formatFloatAsShort(replacementNumber, precision, conversion);
break;
}
formattedReplacement = addSignToFormattedNumber(replacementNumber, formattedReplacement, conversion);
return coerceToString(formattedReplacement);
} | Formats a float type according to specifiers.
@ignore
@param {string} replacement The string to be formatted.
@param {ConversionSpecification} conversion The conversion specification object.
@return {string} Returns the formatted string. | float ( replacement , conversion ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function formatFloatAsShort(replacementNumber, precision, conversion) {
if (replacementNumber === 0) {
return '0';
}
var nonZeroPrecision = precision === 0 ? 1 : precision;
var formattedReplacement = replacementNumber.toPrecision(nonZeroPrecision).replace(REGEXP_TRAILING_ZEROS, '');
if (conversion.typeSpecifier === TYPE_FLOAT_SHORT_UPPERCASE) {
formattedReplacement = formattedReplacement.toUpperCase();
}
return formattedReplacement;
} | Formats the short float.
@ignore
@param {number} replacementNumber The number to format.
@param {number} precision The precision to format the float.
@param {ConversionSpecification} conversion The conversion specification object.
@return {string} Returns the formatted short float. | formatFloatAsShort ( replacementNumber , precision , conversion ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function integerBase(replacement, conversion) {
var integer = parseInt(replacement);
if (isNaN(integer)) {
integer = 0;
}
integer = integer >>> 0;
switch (conversion.typeSpecifier) {
case TYPE_INTEGER_ASCII_CHARACTER:
integer = String.fromCharCode(integer);
break;
case TYPE_INTEGER_BINARY:
integer = integer.toString(RADIX_BINARY);
break;
case TYPE_INTEGER_OCTAL:
integer = integer.toString(RADIX_OCTAL);
break;
case TYPE_INTEGER_HEXADECIMAL:
integer = integer.toString(RADIX_HEXADECIMAL);
break;
case TYPE_INTEGER_HEXADECIMAL_UPPERCASE:
integer = integer.toString(RADIX_HEXADECIMAL).toUpperCase();
break;
}
return coerceToString(integer);
} | Formats an integer type according to specifiers.
@ignore
@param {string} replacement The string to be formatted.
@param {ConversionSpecification} conversion The conversion specification object.
@return {string} Returns the formatted string. | integerBase ( replacement , conversion ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function integerDecimal(replacement, conversion) {
var integer = parseInt(replacement);
if (isNaN(integer)) {
integer = 0;
}
return addSignToFormattedNumber(integer, toString(integer), conversion);
} | Formats a decimal integer type according to specifiers.
@ignore
@param {string} replacement The string to be formatted.
@param {ConversionSpecification} conversion The conversion specification object.
@return {string} Returns the formatted string. | integerDecimal ( replacement , conversion ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function stringFormat(replacement, conversion) {
var formattedReplacement = replacement;
var precision = conversion.precision;
if (!isNil(precision) && formattedReplacement.length > precision) {
formattedReplacement = truncate(formattedReplacement, precision, '');
}
return formattedReplacement;
} | Formats a string type according to specifiers.
@ignore
@param {string} replacement The string to be formatted.
@param {ConversionSpecification} conversion The conversion specification object.
@return {string} Returns the formatted string. | stringFormat ( replacement , conversion ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function compute(replacement, conversion) {
var formatFunction;
switch (conversion.typeSpecifier) {
case TYPE_STRING:
formatFunction = stringFormat;
break;
case TYPE_INTEGER_DECIMAL:
case TYPE_INTEGER:
formatFunction = integerDecimal;
break;
case TYPE_INTEGER_ASCII_CHARACTER:
case TYPE_INTEGER_BINARY:
case TYPE_INTEGER_OCTAL:
case TYPE_INTEGER_HEXADECIMAL:
case TYPE_INTEGER_HEXADECIMAL_UPPERCASE:
case TYPE_INTEGER_UNSIGNED_DECIMAL:
formatFunction = integerBase;
break;
case TYPE_FLOAT:
case TYPE_FLOAT_SCIENTIFIC:
case TYPE_FLOAT_SCIENTIFIC_UPPERCASE:
case TYPE_FLOAT_SHORT:
case TYPE_FLOAT_SHORT_UPPERCASE:
formatFunction = float;
break;
}
var formattedString = formatFunction(replacement, conversion);
return alignAndPad(formattedString, conversion);
} | Returns the computed string based on format specifiers.
@ignore
@name computeReplacement
@param {string} replacement The replacement value.
@param {ConversionSpecification} conversion The conversion specification object.
@return {string} Returns the computed string. | compute ( replacement , conversion ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function ConversionSpecification(properties) {
/**
* The percent characters from conversion specification.
*
* @ignore
* @name ConversionSpecification#percent
* @type {string}
*/
this.percent = properties.percent;
/**
* The sign specifier to force a sign to be used on a number.
*
* @ignore
* @name ConversionSpecification#signSpecifier
* @type {string}
*/
this.signSpecifier = properties.signSpecifier;
/**
* The padding specifier that says what padding character will be used.
*
* @ignore
* @name ConversionSpecification#paddingSpecifier
* @type {string}
*/
this.paddingSpecifier = properties.paddingSpecifier;
/**
* The alignment specifier that says if the result should be left-justified or right-justified.
*
* @ignore
* @name ConversionSpecification#alignmentSpecifier
* @type {string}
*/
this.alignmentSpecifier = properties.alignmentSpecifier;
/**
* The width specifier how many characters this conversion should result in.
*
* @ignore
* @name ConversionSpecification#width
* @type {number}
*/
this.width = properties.width;
/**
* The precision specifier says how many decimal digits should be displayed for floating-point numbers.
*
* @ignore
* @name ConversionSpecification#precision
* @type {number}
*/
this.precision = properties.precision;
/**
* The type specifier says what type the argument data should be treated as.
*
* @ignore
* @name ConversionSpecification#typeSpecifier
* @type {string}
*/
this.typeSpecifier = properties.typeSpecifier;
} | Construct the new conversion specification object.
@ignore
@param {Object} properties An object with properties to initialize.
@return {ConversionSpecification} ConversionSpecification instance. | ConversionSpecification ( properties ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ConversionSpecification.prototype.isPercentLiteral = function() {
return LITERAL_PERCENT_SPECIFIER === this.percent;
}; | Check if the conversion specification is a percent literal "%%".
@ignore
@return {boolean} Returns true if the conversion is a percent literal, false otherwise. | ConversionSpecification.prototype.isPercentLiteral ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
ConversionSpecification.prototype.getPaddingCharacter = function() {
var paddingCharacter = nilDefault(this.paddingSpecifier, ' ');
if (paddingCharacter.length === 2 && paddingCharacter[0] === LITERAL_SINGLE_QUOTE) {
paddingCharacter = paddingCharacter[1];
}
return paddingCharacter;
}; | Get the padding character from padding specifier.
@ignore
@returns {string} Returns the padding character. | ConversionSpecification.prototype.getPaddingCharacter ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function validate(index, replacementsLength, conversion) {
if (isNil(conversion.typeSpecifier)) {
throw new Error('sprintf(): Unknown type specifier');
}
if (index > replacementsLength - 1) {
throw new Error('sprintf(): Too few arguments');
}
if (index < 0) {
throw new Error('sprintf(): Argument number must be greater than zero');
}
} | Validates the specifier type and replacement position.
@ignore
@throws {Error} Throws an exception on insufficient arguments or unknown specifier.
@param {number} index The index of the matched specifier.
@param {number} replacementsLength The number of replacements.
@param {ConversionSpecification} conversion The conversion specification object.
@return {undefined} | validate ( index , replacementsLength , conversion ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function vprintf(format, replacements) {
return sprintf.apply(void 0, [format].concat(_toConsumableArray(nilDefault(replacements, []))));
} | Produces a string according to `format`. Works exactly like <a href="#sprintf"><code>sprintf()</code></a>,
with the only difference that accepts the formatting arguments in an array `values`.<br/>
See <a href="#sprintf-format">here</a> `format` string specifications.
@function vprintf
@static
@since 1.0.0
@memberOf Format
@param {string} format=''] The format string.
@param {Array} replacements The array of replacements to produce the string.
@return {string} Returns the produced string.
@example
v.vprintf('%s', ['Welcome'])
// => 'Welcome'
v.vprintf('%s has %d apples', ['Alexandra', 3]);
// => 'Alexandra has 3 apples' | vprintf ( format , replacements ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function replaceSpecialCharacter(character) {
return escapeCharactersMap[character];
} | Return the escaped version of `character`.
@ignore
@param {string} character The character to be escape.
@return {string} The escaped version of character. | replaceSpecialCharacter ( character ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function escapeHtml(subject) {
return coerceToString(subject).replace(REGEXP_HTML_SPECIAL_CHARACTERS, replaceSpecialCharacter);
} | Escapes HTML special characters <code>< > & ' " `</code> in <code>subject</code>.
@function escapeHtml
@static
@since 1.0.0
@memberOf Escape
@param {string} [subject=''] The string to escape.
@return {string} Returns the escaped string.
@example
v.escapeHtml('<p>wonderful world</p>');
// => '<p>wonderful world</p>' | escapeHtml ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function escapeRegExp(subject) {
return coerceToString(subject).replace(REGEXP_SPECIAL_CHARACTERS, '\\$&');
} | Escapes the regular expression special characters `- [ ] / { } ( ) * + ? . \ ^ $ |` in `subject`.
@function escapeRegExp
@static
@since 1.0.0
@memberOf Escape
@param {string} [subject=''] The string to escape.
@return {string} Returns the escaped string.
@example
v.escapeRegExp('(hours)[minutes]{seconds}');
// => '\(hours\)\[minutes\]\{seconds\}' | escapeRegExp ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function reduceUnescapedString(string, key) {
return string.replace(unescapeCharactersMap[key], key);
} | Replaces the HTML entities with corresponding characters.
@ignore
@param {string} string The accumulator string.
@param {string} key The character.
@return {string} The string with replaced HTML entity | reduceUnescapedString ( string , key ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function unescapeHtml(subject) {
var subjectString = coerceToString(subject);
return characters.reduce(reduceUnescapedString, subjectString);
} | Unescapes HTML special characters from <code>&lt; &gt; &amp; &quot; &#x27; &#x60;</code>
to corresponding <code>< > & ' " `</code> in <code>subject</code>.
@function unescapeHtml
@static
@since 1.0.0
@memberOf Escape
@param {string} [subject=''] The string to unescape.
@return {string} Returns the unescaped string.
@example
v.unescapeHtml('<p>wonderful world</p>');
// => '<p>wonderful world</p>' | unescapeHtml ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function indexOf(subject, search, fromIndex) {
var subjectString = coerceToString(subject);
return subjectString.indexOf(search, fromIndex);
} | Returns the first occurrence index of `search` in `subject`.
@function indexOf
@static
@since 1.0.0
@memberOf Index
@param {string} [subject=''] The string where to search.
@param {string} search The string to search.
@param {number} [fromIndex=0] The index to start searching.
@return {number} Returns the first occurrence index or `-1` if not found.
@example
v.indexOf('morning', 'n');
// => 3
v.indexOf('evening', 'o');
// => -1 | indexOf ( subject , search , fromIndex ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function lastIndexOf(subject, search, fromIndex) {
var subjectString = coerceToString(subject);
return subjectString.lastIndexOf(search, fromIndex);
} | Returns the last occurrence index of `search` in `subject`.
@function lastIndexOf
@static
@since 1.0.0
@memberOf Index
@param {string} [subject=''] The string where to search.
@param {string} search The string to search.
@param {number} [fromIndex=subject.length - 1] The index to start searching backward in the string.
@return {number} Returns the last occurrence index or `-1` if not found.
@example
v.lastIndexOf('morning', 'n');
// => 5
v.lastIndexOf('evening', 'o');
// => -1 | lastIndexOf ( subject , search , fromIndex ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function search(subject, pattern, fromIndex) {
var subjectString = coerceToString(subject);
var fromIndexNumber = isNil(fromIndex) ? 0 : clipNumber(toInteger(fromIndex), 0, subjectString.length);
var matchIndex = subjectString.substr(fromIndexNumber).search(pattern);
if (matchIndex !== -1 && !isNaN(fromIndexNumber)) {
matchIndex += fromIndexNumber;
}
return matchIndex;
} | Returns the first index of a `pattern` match in `subject`.
@function search
@static
@since 1.0.0
@memberOf Index
@param {string} [subject=''] The string where to search.
@param {string|RegExp} pattern The pattern to match. If `pattern` is not RegExp, it is transformed to `new RegExp(pattern)`.
@param {number} [fromIndex=0] The index to start searching.
@return {number} Returns the first match index or `-1` if not found.
@example
v.search('morning', /rn/);
// => 2
v.search('evening', '/\d/');
// => -1 | search ( subject , pattern , fromIndex ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function insert(subject, toInsert, position) {
var subjectString = coerceToString(subject);
var toInsertString = coerceToString(toInsert);
var positionNumber = coerceToNumber(position);
if (positionNumber < 0 || positionNumber > subjectString.length || toInsertString === '') {
return subjectString;
}
return subjectString.slice(0, positionNumber) + toInsertString + subjectString.slice(positionNumber);
} | Inserts into `subject` a string `toInsert` at specified `position`.
@function insert
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string where to insert.
@param {string} [toInsert=''] The string to be inserted.
@param {number} [position=0] The position to insert.
@return {string} Returns the string after insertion.
@example
v.insert('ct', 'a', 1);
// => 'cat'
v.insert('sunny', ' day', 5);
// => 'sunny day' | insert ( subject , toInsert , position ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function getDiacriticsMap() {
if (diacriticsMap !== null) {
return diacriticsMap;
}
diacriticsMap = {};
Object.keys(diacritics).forEach(function(key) {
var characters = diacritics[key];
for (var index = 0; index < characters.length; index++) {
var character = characters[index];
diacriticsMap[character] = key;
}
});
return diacriticsMap;
} | Creates a map of the diacritics.
@ignore
@returns {Object} Returns the diacritics map. | getDiacriticsMap ( ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function getLatinCharacter(character) {
var characterWithoutDiacritic = getDiacriticsMap()[character];
return characterWithoutDiacritic ? characterWithoutDiacritic : character;
} | Get the latin character from character with diacritics.
@ignore
@param {string} character The character with diacritics.
@returns {string} Returns the character without diacritics. | getLatinCharacter ( character ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function removeCombiningMarks(character, cleanCharacter) {
return cleanCharacter;
} | Returns the `cleanCharacter` from combining marks regular expression match.
@ignore
@param {string} character The character with combining marks
@param {string} cleanCharacter The character without combining marks.
@return {string} The character without combining marks. | removeCombiningMarks ( character , cleanCharacter ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function latinise(subject) {
var subjectString = coerceToString(subject);
if (subjectString === '') {
return '';
}
return subjectString
.replace(REGEXP_NON_LATIN, getLatinCharacter)
.replace(REGEXP_COMBINING_MARKS, removeCombiningMarks);
} | Latinises the `subject` by removing diacritic characters.
@function latinise
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to latinise.
@return {string} Returns the latinised string.
@example
v.latinise('cafe\u0301'); // or 'café'
// => 'cafe'
v.latinise('août décembre');
// => 'aout decembre'
v.latinise('как прекрасен этот мир');
// => 'kak prekrasen etot mir' | latinise ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function pad(subject, length, pad) {
var subjectString = coerceToString(subject);
var lengthInt = isNil(length) ? 0 : clipNumber(toInteger(length), 0, MAX_SAFE_INTEGER);
var padString = coerceToString(pad, ' ');
if (lengthInt <= subjectString.length) {
return subjectString;
}
var paddingLength = lengthInt - subjectString.length;
var paddingSideLength = toInteger(paddingLength / 2);
var paddingSideRemainingLength = paddingLength % 2;
return (
buildPadding(padString, paddingSideLength) +
subjectString +
buildPadding(padString, paddingSideLength + paddingSideRemainingLength)
);
} | Pads `subject` to a new `length`.
@function pad
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to pad.
@param {int} [length=0] The length to pad the string. No changes are made if `length` is less than `subject.length`.
@param {string} [pad=' '] The string to be used for padding.
@return {string} Returns the padded string.
@example
v.pad('dog', 5);
// => ' dog '
v.pad('bird', 6, '-');
// => '-bird-'
v.pad('cat', 6, '-=');
// => '-cat-=' | pad ( subject , length , pad ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function replace(subject, search, replace) {
var subjectString = coerceToString(subject);
return subjectString.replace(search, replace);
} | Replaces the matches of `search` with `replace`. <br/>
@function replace
@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 and only the first occurrence replaced.
@param {string|Function} replace The string or function which invocation result replaces `search` match.
@return {string} Returns the replacement result.
@example
v.replace('swan', 'wa', 'u');
// => 'sun'
v.replace('domestic duck', /domestic\s/, '');
// => 'duck'
v.replace('nice duck', /(nice)(duck)/, function(match, nice, duck) {
return 'the ' + duck + ' is ' + nice;
});
// => 'the duck is nice' | replace ( subject , search , replace ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function reverse(subject) {
var subjectString = coerceToString(subject);
return subjectString
.split('')
.reverse()
.join('');
} | Reverses the `subject`.
@function reverse
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to reverse.
@return {string} Returns the reversed string.
@example
v.reverse('winter');
// => 'retniw' | reverse ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function reverseGrapheme(subject) {
var subjectString = coerceToString(subject);
/**
* @see https://github.com/mathiasbynens/esrever
*/
subjectString = subjectString
.replace(REGEXP_COMBINING_MARKS, function($0, $1, $2) {
return reverseGrapheme($2) + $1;
})
.replace(REGEXP_SURROGATE_PAIRS, '$2$1');
var reversedString = '';
var index = subjectString.length;
while (index--) {
reversedString += subjectString.charAt(index);
}
return reversedString;
} | Reverses the `subject` 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 reverseGrapheme
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to reverse.
@return {string} Returns the reversed string.
@example
v.reverseGrapheme('summer');
// => 'remmus'
v.reverseGrapheme('𝌆 bar mañana mañana');
// => 'anañam anañam rab 𝌆' | reverseGrapheme ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function slugify(subject) {
var subjectString = coerceToString(subject);
if (subjectString === '') {
return '';
}
var cleanSubjectString = latinise(subjectString).replace(REGEXP_NON_LATIN, '-');
return kebabCase(cleanSubjectString);
} | Slugifies the `subject`. Cleans the `subject` by replacing diacritics with corresponding latin characters.
@function slugify
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string to slugify.
@return {string} Returns the slugified string.
@example
v.slugify('Italian cappuccino drink');
// => 'italian-cappuccino-drink'
v.slugify('caffé latté');
// => 'caffe-latte'
v.slugify('хорошая погода');
// => 'horoshaya-pogoda' | slugify ( subject ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function splice(subject, start, deleteCount, toAdd) {
var subjectString = coerceToString(subject);
var toAddString = coerceToString(toAdd);
var startPosition = coerceToNumber(start);
if (startPosition < 0) {
startPosition = subjectString.length + startPosition;
if (startPosition < 0) {
startPosition = 0;
}
} else if (startPosition > subjectString.length) {
startPosition = subjectString.length;
}
var deleteCountNumber = coerceToNumber(deleteCount, subjectString.length - startPosition);
if (deleteCountNumber < 0) {
deleteCountNumber = 0;
}
return subjectString.slice(0, startPosition) + toAddString + subjectString.slice(startPosition + deleteCountNumber);
} | Changes `subject` by deleting `deleteCount` of characters starting at position `start`. Places a new string
`toAdd` instead of deleted characters.
@function splice
@static
@since 1.0.0
@memberOf Manipulate
@param {string} [subject=''] The string where to insert.
@param {string} start The position to start changing the string. For a negative position will start from the end of
the string.
@param {number} [deleteCount=subject.length-start] The number of characters to delete from string.
@param {string} [toAdd=''] The string to be added instead of deleted characters.
@return {string} Returns the modified string.
@example
v.splice('new year', 0, 4);
// => 'year'
v.splice('new year', 0, 3, 'happy');
// => 'happy year'
v.splice('new year', -4, 4, 'day');
// => 'new day' | splice ( subject , start , deleteCount , toAdd ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function tr(subject, from, to) {
var subjectString = coerceToString(subject);
var keys;
var values;
if (isString(from) && isString(to)) {
keys = from.split('');
values = to.split('');
} else {
var _extractKeysAndValues = extractKeysAndValues(nilDefault(from, {}));
var _extractKeysAndValues2 = _slicedToArray(_extractKeysAndValues, 2);
keys = _extractKeysAndValues2[0];
values = _extractKeysAndValues2[1];
}
var keysLength = keys.length;
if (keysLength === 0) {
return subjectString;
}
var result = '';
var valuesLength = values.length;
for (var index = 0; index < subjectString.length; index++) {
var isMatch = false;
var matchValue = void 0;
for (var keyIndex = 0; keyIndex < keysLength && keyIndex < valuesLength; keyIndex++) {
var key = keys[keyIndex];
if (subjectString.substr(index, key.length) === key) {
isMatch = true;
matchValue = values[keyIndex];
index = index + key.length - 1;
break;
}
}
result += isMatch ? matchValue : subjectString[index];
}
return result;
} | Translates characters or replaces substrings in `subject`.
@function tr
@static
@since 1.3.0
@memberOf Manipulate
@param {string} [subject=''] The string to translate.
@param {string|Object} from The string of characters to translate from. Or an object, then the object keys are replaced with corresponding values (longest keys are tried first).
@param {string} to The string of characters to translate to. Ignored when `from` is an object.
@return {string} Returns the translated string.
@example
v.tr('hello', 'el', 'ip');
// => 'hippo'
v.tr('légèreté', 'éè', 'ee');
// => 'legerete'
v.tr('Yes. The fire rises.', {
'Yes': 'Awesome',
'fire': 'flame'
})
// => 'Awesome. The flame rises.'
v.tr(':where is the birthplace of :what', {
':where': 'Africa',
':what': 'Humanity'
});
// => 'Africa is the birthplace of Humanity' | tr ( subject , from , to ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function includes(subject, search, position) {
var subjectString = coerceToString(subject);
var searchString = toString(search);
if (searchString === null) {
return false;
}
if (searchString === '') {
return true;
}
position = isNil(position) ? 0 : clipNumber(toInteger(position), 0, subjectString.length);
return subjectString.indexOf(searchString, position) !== -1;
} | Checks whether `subject` includes `search` starting from `position`.
@function includes
@static
@since 1.0.0
@memberOf Query
@param {string} [subject=''] The string where to search.
@param {string} search The string to search.
@param {number} [position=0] The position to start searching.
@return {boolean} Returns `true` if `subject` includes `search` or `false` otherwise.
@example
v.includes('starship', 'star');
// => true
v.includes('galaxy', 'g', 1);
// => false | includes ( subject , search , position ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function trimLeft(subject, whitespace) {
var subjectString = coerceToString(subject);
if (whitespace === '' || subjectString === '') {
return subjectString;
}
var whitespaceString = toString(whitespace);
if (isNil(whitespaceString)) {
return subjectString.replace(REGEXP_TRIM_LEFT, '');
}
var matchWhitespace = true;
return reduce$1.call(
subjectString,
function(trimmed, character) {
if (matchWhitespace && includes(whitespaceString, character)) {
return trimmed;
}
matchWhitespace = false;
return trimmed + character;
},
''
);
} | Removes whitespaces from the left side of the `subject`.
@function trimLeft
@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.trimLeft(' Starship Troopers');
// => 'Starship Troopers'
v.trimLeft('***Mobile Infantry', '*');
// => 'Mobile Infantry' | trimLeft ( subject , whitespace ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
function trimRight(subject, whitespace) {
var subjectString = coerceToString(subject);
if (whitespace === '' || subjectString === '') {
return subjectString;
}
var whitespaceString = toString(whitespace);
if (isNil(whitespaceString)) {
return subjectString.replace(REGEXP_TRIM_RIGHT, '');
}
var matchWhitespace = true;
return reduceRight.call(
subjectString,
function(trimmed, character) {
if (matchWhitespace && includes(whitespaceString, character)) {
return trimmed;
}
matchWhitespace = false;
return character + trimmed;
},
''
);
} | Removes whitespaces from the right side of the `subject`.
@function trimRight
@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.trimRight('the fire rises ');
// => 'the fire rises'
v.trimRight('do you feel in charge?!!!', '!');
// => 'do you feel in charge?' | trimRight ( subject , whitespace ) | javascript | panzerdp/voca | dist/voca.js | https://github.com/panzerdp/voca/blob/master/dist/voca.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.