language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function IsFQDN(options, validationOptions) {
return ValidateBy({
name: IS_FQDN,
constraints: [options],
validator: {
validate: function (value, args) { return isFQDN(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid domain name'; }, validationOptions),
},
}, validationOptions);
} | function IsFQDN(options, validationOptions) {
return ValidateBy({
name: IS_FQDN,
constraints: [options],
validator: {
validate: function (value, args) { return isFQDN(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid domain name'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsFullWidth(validationOptions) {
return ValidateBy({
name: IS_FULL_WIDTH,
validator: {
validate: function (value, args) { return isFullWidth(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain a full-width characters'; }, validationOptions),
},
}, validationOptions);
} | function IsFullWidth(validationOptions) {
return ValidateBy({
name: IS_FULL_WIDTH,
validator: {
validate: function (value, args) { return isFullWidth(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain a full-width characters'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsHalfWidth(validationOptions) {
return ValidateBy({
name: IS_HALF_WIDTH,
validator: {
validate: function (value, args) { return isHalfWidth(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain a half-width characters'; }, validationOptions),
},
}, validationOptions);
} | function IsHalfWidth(validationOptions) {
return ValidateBy({
name: IS_HALF_WIDTH,
validator: {
validate: function (value, args) { return isHalfWidth(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain a half-width characters'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsVariableWidth(validationOptions) {
return ValidateBy({
name: IS_VARIABLE_WIDTH,
validator: {
validate: function (value, args) { return isVariableWidth(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain a full-width and half-width characters'; }, validationOptions),
},
}, validationOptions);
} | function IsVariableWidth(validationOptions) {
return ValidateBy({
name: IS_VARIABLE_WIDTH,
validator: {
validate: function (value, args) { return isVariableWidth(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain a full-width and half-width characters'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsHexColor(validationOptions) {
return ValidateBy({
name: IS_HEX_COLOR,
validator: {
validate: function (value, args) { return isHexColor(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a hexadecimal color'; }, validationOptions),
},
}, validationOptions);
} | function IsHexColor(validationOptions) {
return ValidateBy({
name: IS_HEX_COLOR,
validator: {
validate: function (value, args) { return isHexColor(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a hexadecimal color'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsHexadecimal(validationOptions) {
return ValidateBy({
name: IS_HEXADECIMAL,
validator: {
validate: function (value, args) { return isHexadecimal(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a hexadecimal number'; }, validationOptions),
},
}, validationOptions);
} | function IsHexadecimal(validationOptions) {
return ValidateBy({
name: IS_HEXADECIMAL,
validator: {
validate: function (value, args) { return isHexadecimal(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a hexadecimal number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsIP(version, validationOptions) {
return ValidateBy({
name: IS_IP,
constraints: [version],
validator: {
validate: function (value, args) { return isIP(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an ip address'; }, validationOptions),
},
}, validationOptions);
} | function IsIP(version, validationOptions) {
return ValidateBy({
name: IS_IP,
constraints: [version],
validator: {
validate: function (value, args) { return isIP(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an ip address'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsPort(validationOptions) {
return ValidateBy({
name: IS_PORT,
validator: {
validate: function (value, args) { return isPort(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a port'; }, validationOptions),
},
}, validationOptions);
} | function IsPort(validationOptions) {
return ValidateBy({
name: IS_PORT,
validator: {
validate: function (value, args) { return isPort(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a port'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsISBN(version, validationOptions) {
return ValidateBy({
name: IS_ISBN,
constraints: [version],
validator: {
validate: function (value, args) { return isISBN(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an ISBN'; }, validationOptions),
},
}, validationOptions);
} | function IsISBN(version, validationOptions) {
return ValidateBy({
name: IS_ISBN,
constraints: [version],
validator: {
validate: function (value, args) { return isISBN(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an ISBN'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsISIN(validationOptions) {
return ValidateBy({
name: IS_ISIN,
validator: {
validate: function (value, args) { return isISIN(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an ISIN (stock/security identifier)'; }, validationOptions),
},
}, validationOptions);
} | function IsISIN(validationOptions) {
return ValidateBy({
name: IS_ISIN,
validator: {
validate: function (value, args) { return isISIN(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an ISIN (stock/security identifier)'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsISO8601(options, validationOptions) {
return ValidateBy({
name: IS_ISO8601,
constraints: [options],
validator: {
validate: function (value, args) { return isISO8601(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid ISO 8601 date string'; }, validationOptions),
},
}, validationOptions);
} | function IsISO8601(options, validationOptions) {
return ValidateBy({
name: IS_ISO8601,
constraints: [options],
validator: {
validate: function (value, args) { return isISO8601(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid ISO 8601 date string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsJSON(validationOptions) {
return ValidateBy({
name: IS_JSON,
validator: {
validate: function (value, args) { return isJSON(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a json string'; }, validationOptions),
},
}, validationOptions);
} | function IsJSON(validationOptions) {
return ValidateBy({
name: IS_JSON,
validator: {
validate: function (value, args) { return isJSON(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a json string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsJWT(validationOptions) {
return ValidateBy({
name: IS_JWT,
validator: {
validate: function (value, args) { return isJWT(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a jwt string'; }, validationOptions),
},
}, validationOptions);
} | function IsJWT(validationOptions) {
return ValidateBy({
name: IS_JWT,
validator: {
validate: function (value, args) { return isJWT(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a jwt string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsLowercase(validationOptions) {
return ValidateBy({
name: IS_LOWERCASE,
validator: {
validate: function (value, args) { return isLowercase(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a lowercase string'; }, validationOptions),
},
}, validationOptions);
} | function IsLowercase(validationOptions) {
return ValidateBy({
name: IS_LOWERCASE,
validator: {
validate: function (value, args) { return isLowercase(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a lowercase string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsISO31661Alpha2(validationOptions) {
return ValidateBy({
name: IS_ISO31661_ALPHA_2,
validator: {
validate: function (value, args) { return isISO31661Alpha2(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid ISO31661 Alpha2 code'; }, validationOptions),
},
}, validationOptions);
} | function IsISO31661Alpha2(validationOptions) {
return ValidateBy({
name: IS_ISO31661_ALPHA_2,
validator: {
validate: function (value, args) { return isISO31661Alpha2(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid ISO31661 Alpha2 code'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsISO31661Alpha3(validationOptions) {
return ValidateBy({
name: IS_ISO31661_ALPHA_3,
validator: {
validate: function (value, args) { return isISO31661Alpha3(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid ISO31661 Alpha3 code'; }, validationOptions),
},
}, validationOptions);
} | function IsISO31661Alpha3(validationOptions) {
return ValidateBy({
name: IS_ISO31661_ALPHA_3,
validator: {
validate: function (value, args) { return isISO31661Alpha3(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid ISO31661 Alpha3 code'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsMongoId(validationOptions) {
return ValidateBy({
name: IS_MONGO_ID,
validator: {
validate: function (value, args) { return isMongoId(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a mongodb id'; }, validationOptions),
},
}, validationOptions);
} | function IsMongoId(validationOptions) {
return ValidateBy({
name: IS_MONGO_ID,
validator: {
validate: function (value, args) { return isMongoId(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a mongodb id'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsMultibyte(validationOptions) {
return ValidateBy({
name: IS_MULTIBYTE,
validator: {
validate: function (value, args) { return isMultibyte(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain one or more multibyte chars'; }, validationOptions),
},
}, validationOptions);
} | function IsMultibyte(validationOptions) {
return ValidateBy({
name: IS_MULTIBYTE,
validator: {
validate: function (value, args) { return isMultibyte(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain one or more multibyte chars'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsSurrogatePair(validationOptions) {
return ValidateBy({
name: IS_SURROGATE_PAIR,
validator: {
validate: function (value, args) { return isSurrogatePair(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain any surrogate pairs chars'; }, validationOptions),
},
}, validationOptions);
} | function IsSurrogatePair(validationOptions) {
return ValidateBy({
name: IS_SURROGATE_PAIR,
validator: {
validate: function (value, args) { return isSurrogatePair(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain any surrogate pairs chars'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsUrl(options, validationOptions) {
return ValidateBy({
name: IS_URL,
constraints: [options],
validator: {
validate: function (value, args) { return isURL(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an URL address'; }, validationOptions),
},
}, validationOptions);
} | function IsUrl(options, validationOptions) {
return ValidateBy({
name: IS_URL,
constraints: [options],
validator: {
validate: function (value, args) { return isURL(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an URL address'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsUUID(version, validationOptions) {
return ValidateBy({
name: IS_UUID,
constraints: [version],
validator: {
validate: function (value, args) { return isUUID(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a UUID'; }, validationOptions),
},
}, validationOptions);
} | function IsUUID(version, validationOptions) {
return ValidateBy({
name: IS_UUID,
constraints: [version],
validator: {
validate: function (value, args) { return isUUID(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a UUID'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsFirebasePushId(validationOptions) {
return ValidateBy({
name: IS_FIREBASE_PUSH_ID,
validator: {
validate: function (value, args) { return isFirebasePushId(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a Firebase Push Id'; }, validationOptions),
},
}, validationOptions);
} | function IsFirebasePushId(validationOptions) {
return ValidateBy({
name: IS_FIREBASE_PUSH_ID,
validator: {
validate: function (value, args) { return isFirebasePushId(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a Firebase Push Id'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsUppercase(validationOptions) {
return ValidateBy({
name: IS_UPPERCASE,
validator: {
validate: function (value, args) { return isUppercase(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be uppercase'; }, validationOptions),
},
}, validationOptions);
} | function IsUppercase(validationOptions) {
return ValidateBy({
name: IS_UPPERCASE,
validator: {
validate: function (value, args) { return isUppercase(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be uppercase'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function Length(min, max, validationOptions) {
return ValidateBy({
name: IS_LENGTH,
constraints: [min, max],
validator: {
validate: function (value, args) { return length(value, args.constraints[0], args.constraints[1]); },
defaultMessage: buildMessage(function (eachPrefix, args) {
var isMinLength = args.constraints[0] !== null && args.constraints[0] !== undefined;
var isMaxLength = args.constraints[1] !== null && args.constraints[1] !== undefined;
if (isMinLength && (!args.value || args.value.length < args.constraints[0])) {
return eachPrefix + '$property must be longer than or equal to $constraint1 characters';
}
else if (isMaxLength && args.value.length > args.constraints[1]) {
return eachPrefix + '$property must be shorter than or equal to $constraint2 characters';
}
return (eachPrefix +
'$property must be longer than or equal to $constraint1 and shorter than or equal to $constraint2 characters');
}, validationOptions),
},
}, validationOptions);
} | function Length(min, max, validationOptions) {
return ValidateBy({
name: IS_LENGTH,
constraints: [min, max],
validator: {
validate: function (value, args) { return length(value, args.constraints[0], args.constraints[1]); },
defaultMessage: buildMessage(function (eachPrefix, args) {
var isMinLength = args.constraints[0] !== null && args.constraints[0] !== undefined;
var isMaxLength = args.constraints[1] !== null && args.constraints[1] !== undefined;
if (isMinLength && (!args.value || args.value.length < args.constraints[0])) {
return eachPrefix + '$property must be longer than or equal to $constraint1 characters';
}
else if (isMaxLength && args.value.length > args.constraints[1]) {
return eachPrefix + '$property must be shorter than or equal to $constraint2 characters';
}
return (eachPrefix +
'$property must be longer than or equal to $constraint1 and shorter than or equal to $constraint2 characters');
}, validationOptions),
},
}, validationOptions);
} |
JavaScript | function MaxLength(max, validationOptions) {
return ValidateBy({
name: MAX_LENGTH,
constraints: [max],
validator: {
validate: function (value, args) { return maxLength(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be shorter than or equal to $constraint1 characters'; }, validationOptions),
},
}, validationOptions);
} | function MaxLength(max, validationOptions) {
return ValidateBy({
name: MAX_LENGTH,
constraints: [max],
validator: {
validate: function (value, args) { return maxLength(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be shorter than or equal to $constraint1 characters'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function MinLength(min, validationOptions) {
return ValidateBy({
name: MIN_LENGTH,
constraints: [min],
validator: {
validate: function (value, args) { return minLength(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be longer than or equal to $constraint1 characters'; }, validationOptions),
},
}, validationOptions);
} | function MinLength(min, validationOptions) {
return ValidateBy({
name: MIN_LENGTH,
constraints: [min],
validator: {
validate: function (value, args) { return minLength(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be longer than or equal to $constraint1 characters'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function createExtensionPattern(purpose) {
// We cap the maximum length of an extension based on the ambiguity of the way
// the extension is prefixed. As per ITU, the officially allowed length for
// extensions is actually 40, but we don't support this since we haven't seen real
// examples and this introduces many false interpretations as the extension labels
// are not standardized.
/** @type {string} */
var extLimitAfterExplicitLabel = '20';
/** @type {string} */
var extLimitAfterLikelyLabel = '15';
/** @type {string} */
var extLimitAfterAmbiguousChar = '9';
/** @type {string} */
var extLimitWhenNotSure = '6';
/** @type {string} */
var possibleSeparatorsBetweenNumberAndExtLabel = "[ \xA0\\t,]*"; // Optional full stop (.) or colon, followed by zero or more spaces/tabs/commas.
/** @type {string} */
var possibleCharsAfterExtLabel = "[:\\.\uFF0E]?[ \xA0\\t,-]*";
/** @type {string} */
var optionalExtnSuffix = "#?"; // Here the extension is called out in more explicit way, i.e mentioning it obvious
// patterns like "ext.".
/** @type {string} */
var explicitExtLabels = "(?:e?xt(?:ensi(?:o\u0301?|\xF3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|\u0434\u043E\u0431|anexo)"; // One-character symbols that can be used to indicate an extension, and less
// commonly used or more ambiguous extension labels.
/** @type {string} */
var ambiguousExtLabels = "(?:[x\uFF58#\uFF03~\uFF5E]|int|\uFF49\uFF4E\uFF54)"; // When extension is not separated clearly.
/** @type {string} */
var ambiguousSeparator = "[- ]+"; // This is the same as possibleSeparatorsBetweenNumberAndExtLabel, but not matching
// comma as extension label may have it.
/** @type {string} */
var possibleSeparatorsNumberExtLabelNoComma = "[ \xA0\\t]*"; // ",," is commonly used for auto dialling the extension when connected. First
// comma is matched through possibleSeparatorsBetweenNumberAndExtLabel, so we do
// not repeat it here. Semi-colon works in Iphone and Android also to pop up a
// button with the extension number following.
/** @type {string} */
var autoDiallingAndExtLabelsFound = "(?:,{2}|;)";
/** @type {string} */
var rfcExtn = RFC3966_EXTN_PREFIX + getExtensionDigitsPattern(extLimitAfterExplicitLabel);
/** @type {string} */
var explicitExtn = possibleSeparatorsBetweenNumberAndExtLabel + explicitExtLabels + possibleCharsAfterExtLabel + getExtensionDigitsPattern(extLimitAfterExplicitLabel) + optionalExtnSuffix;
/** @type {string} */
var ambiguousExtn = possibleSeparatorsBetweenNumberAndExtLabel + ambiguousExtLabels + possibleCharsAfterExtLabel + getExtensionDigitsPattern(extLimitAfterAmbiguousChar) + optionalExtnSuffix;
/** @type {string} */
var americanStyleExtnWithSuffix = ambiguousSeparator + getExtensionDigitsPattern(extLimitWhenNotSure) + "#";
/** @type {string} */
var autoDiallingExtn = possibleSeparatorsNumberExtLabelNoComma + autoDiallingAndExtLabelsFound + possibleCharsAfterExtLabel + getExtensionDigitsPattern(extLimitAfterLikelyLabel) + optionalExtnSuffix;
/** @type {string} */
var onlyCommasExtn = possibleSeparatorsNumberExtLabelNoComma + "(?:,)+" + possibleCharsAfterExtLabel + getExtensionDigitsPattern(extLimitAfterAmbiguousChar) + optionalExtnSuffix; // The first regular expression covers RFC 3966 format, where the extension is added
// using ";ext=". The second more generic where extension is mentioned with explicit
// labels like "ext:". In both the above cases we allow more numbers in extension than
// any other extension labels. The third one captures when single character extension
// labels or less commonly used labels are used. In such cases we capture fewer
// extension digits in order to reduce the chance of falsely interpreting two
// numbers beside each other as a number + extension. The fourth one covers the
// special case of American numbers where the extension is written with a hash
// at the end, such as "- 503#". The fifth one is exclusively for extension
// autodialling formats which are used when dialling and in this case we accept longer
// extensions. The last one is more liberal on the number of commas that acts as
// extension labels, so we have a strict cap on the number of digits in such extensions.
return rfcExtn + "|" + explicitExtn + "|" + ambiguousExtn + "|" + americanStyleExtnWithSuffix + "|" + autoDiallingExtn + "|" + onlyCommasExtn;
} | function createExtensionPattern(purpose) {
// We cap the maximum length of an extension based on the ambiguity of the way
// the extension is prefixed. As per ITU, the officially allowed length for
// extensions is actually 40, but we don't support this since we haven't seen real
// examples and this introduces many false interpretations as the extension labels
// are not standardized.
/** @type {string} */
var extLimitAfterExplicitLabel = '20';
/** @type {string} */
var extLimitAfterLikelyLabel = '15';
/** @type {string} */
var extLimitAfterAmbiguousChar = '9';
/** @type {string} */
var extLimitWhenNotSure = '6';
/** @type {string} */
var possibleSeparatorsBetweenNumberAndExtLabel = "[ \xA0\\t,]*"; // Optional full stop (.) or colon, followed by zero or more spaces/tabs/commas.
/** @type {string} */
var possibleCharsAfterExtLabel = "[:\\.\uFF0E]?[ \xA0\\t,-]*";
/** @type {string} */
var optionalExtnSuffix = "#?"; // Here the extension is called out in more explicit way, i.e mentioning it obvious
// patterns like "ext.".
/** @type {string} */
var explicitExtLabels = "(?:e?xt(?:ensi(?:o\u0301?|\xF3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|\u0434\u043E\u0431|anexo)"; // One-character symbols that can be used to indicate an extension, and less
// commonly used or more ambiguous extension labels.
/** @type {string} */
var ambiguousExtLabels = "(?:[x\uFF58#\uFF03~\uFF5E]|int|\uFF49\uFF4E\uFF54)"; // When extension is not separated clearly.
/** @type {string} */
var ambiguousSeparator = "[- ]+"; // This is the same as possibleSeparatorsBetweenNumberAndExtLabel, but not matching
// comma as extension label may have it.
/** @type {string} */
var possibleSeparatorsNumberExtLabelNoComma = "[ \xA0\\t]*"; // ",," is commonly used for auto dialling the extension when connected. First
// comma is matched through possibleSeparatorsBetweenNumberAndExtLabel, so we do
// not repeat it here. Semi-colon works in Iphone and Android also to pop up a
// button with the extension number following.
/** @type {string} */
var autoDiallingAndExtLabelsFound = "(?:,{2}|;)";
/** @type {string} */
var rfcExtn = RFC3966_EXTN_PREFIX + getExtensionDigitsPattern(extLimitAfterExplicitLabel);
/** @type {string} */
var explicitExtn = possibleSeparatorsBetweenNumberAndExtLabel + explicitExtLabels + possibleCharsAfterExtLabel + getExtensionDigitsPattern(extLimitAfterExplicitLabel) + optionalExtnSuffix;
/** @type {string} */
var ambiguousExtn = possibleSeparatorsBetweenNumberAndExtLabel + ambiguousExtLabels + possibleCharsAfterExtLabel + getExtensionDigitsPattern(extLimitAfterAmbiguousChar) + optionalExtnSuffix;
/** @type {string} */
var americanStyleExtnWithSuffix = ambiguousSeparator + getExtensionDigitsPattern(extLimitWhenNotSure) + "#";
/** @type {string} */
var autoDiallingExtn = possibleSeparatorsNumberExtLabelNoComma + autoDiallingAndExtLabelsFound + possibleCharsAfterExtLabel + getExtensionDigitsPattern(extLimitAfterLikelyLabel) + optionalExtnSuffix;
/** @type {string} */
var onlyCommasExtn = possibleSeparatorsNumberExtLabelNoComma + "(?:,)+" + possibleCharsAfterExtLabel + getExtensionDigitsPattern(extLimitAfterAmbiguousChar) + optionalExtnSuffix; // The first regular expression covers RFC 3966 format, where the extension is added
// using ";ext=". The second more generic where extension is mentioned with explicit
// labels like "ext:". In both the above cases we allow more numbers in extension than
// any other extension labels. The third one captures when single character extension
// labels or less commonly used labels are used. In such cases we capture fewer
// extension digits in order to reduce the chance of falsely interpreting two
// numbers beside each other as a number + extension. The fourth one covers the
// special case of American numbers where the extension is written with a hash
// at the end, such as "- 503#". The fifth one is exclusively for extension
// autodialling formats which are used when dialling and in this case we accept longer
// extensions. The last one is more liberal on the number of commas that acts as
// extension labels, so we have a strict cap on the number of digits in such extensions.
return rfcExtn + "|" + explicitExtn + "|" + ambiguousExtn + "|" + americanStyleExtnWithSuffix + "|" + autoDiallingExtn + "|" + onlyCommasExtn;
} |
JavaScript | function extractExtension(number) {
var start = number.search(EXTN_PATTERN);
if (start < 0) {
return {};
} // If we find a potential extension, and the number preceding this is a viable
// number, we assume it is an extension.
var numberWithoutExtension = number.slice(0, start);
var matches = number.match(EXTN_PATTERN);
var i = 1;
while (i < matches.length) {
if (matches[i]) {
return {
number: numberWithoutExtension,
ext: matches[i]
};
}
i++;
}
} | function extractExtension(number) {
var start = number.search(EXTN_PATTERN);
if (start < 0) {
return {};
} // If we find a potential extension, and the number preceding this is a viable
// number, we assume it is an extension.
var numberWithoutExtension = number.slice(0, start);
var matches = number.match(EXTN_PATTERN);
var i = 1;
while (i < matches.length) {
if (matches[i]) {
return {
number: numberWithoutExtension,
ext: matches[i]
};
}
i++;
}
} |
JavaScript | function checkNumberLengthForType(nationalNumber, type, metadata) {
var type_info = metadata.type(type); // There should always be "<possiblePengths/>" set for every type element.
// This is declared in the XML schema.
// For size efficiency, where a sub-description (e.g. fixed-line)
// has the same "<possiblePengths/>" as the "general description", this is missing,
// so we fall back to the "general description". Where no numbers of the type
// exist at all, there is one possible length (-1) which is guaranteed
// not to match the length of any real phone number.
var possible_lengths = type_info && type_info.possibleLengths() || metadata.possibleLengths(); // let local_lengths = type_info && type.possibleLengthsLocal() || metadata.possibleLengthsLocal()
// Metadata before version `1.0.18` didn't contain `possible_lengths`.
if (!possible_lengths) {
return 'IS_POSSIBLE';
}
if (type === 'FIXED_LINE_OR_MOBILE') {
// No such country in metadata.
/* istanbul ignore next */
if (!metadata.type('FIXED_LINE')) {
// The rare case has been encountered where no fixedLine data is available
// (true for some non-geographic entities), so we just check mobile.
return checkNumberLengthForType(nationalNumber, 'MOBILE', metadata);
}
var mobile_type = metadata.type('MOBILE');
if (mobile_type) {
// Merge the mobile data in if there was any. "Concat" creates a new
// array, it doesn't edit possible_lengths in place, so we don't need a copy.
// Note that when adding the possible lengths from mobile, we have
// to again check they aren't empty since if they are this indicates
// they are the same as the general desc and should be obtained from there.
possible_lengths = mergeArrays(possible_lengths, mobile_type.possibleLengths()); // The current list is sorted; we need to merge in the new list and
// re-sort (duplicates are okay). Sorting isn't so expensive because
// the lists are very small.
// if (local_lengths) {
// local_lengths = mergeArrays(local_lengths, mobile_type.possibleLengthsLocal())
// } else {
// local_lengths = mobile_type.possibleLengthsLocal()
// }
}
} // If the type doesn't exist then return 'INVALID_LENGTH'.
else if (type && !type_info) {
return 'INVALID_LENGTH';
}
var actual_length = nationalNumber.length; // In `libphonenumber-js` all "local-only" formats are dropped for simplicity.
// // This is safe because there is never an overlap beween the possible lengths
// // and the local-only lengths; this is checked at build time.
// if (local_lengths && local_lengths.indexOf(nationalNumber.length) >= 0)
// {
// return 'IS_POSSIBLE_LOCAL_ONLY'
// }
var minimum_length = possible_lengths[0];
if (minimum_length === actual_length) {
return 'IS_POSSIBLE';
}
if (minimum_length > actual_length) {
return 'TOO_SHORT';
}
if (possible_lengths[possible_lengths.length - 1] < actual_length) {
return 'TOO_LONG';
} // We skip the first element since we've already checked it.
return possible_lengths.indexOf(actual_length, 1) >= 0 ? 'IS_POSSIBLE' : 'INVALID_LENGTH';
} | function checkNumberLengthForType(nationalNumber, type, metadata) {
var type_info = metadata.type(type); // There should always be "<possiblePengths/>" set for every type element.
// This is declared in the XML schema.
// For size efficiency, where a sub-description (e.g. fixed-line)
// has the same "<possiblePengths/>" as the "general description", this is missing,
// so we fall back to the "general description". Where no numbers of the type
// exist at all, there is one possible length (-1) which is guaranteed
// not to match the length of any real phone number.
var possible_lengths = type_info && type_info.possibleLengths() || metadata.possibleLengths(); // let local_lengths = type_info && type.possibleLengthsLocal() || metadata.possibleLengthsLocal()
// Metadata before version `1.0.18` didn't contain `possible_lengths`.
if (!possible_lengths) {
return 'IS_POSSIBLE';
}
if (type === 'FIXED_LINE_OR_MOBILE') {
// No such country in metadata.
/* istanbul ignore next */
if (!metadata.type('FIXED_LINE')) {
// The rare case has been encountered where no fixedLine data is available
// (true for some non-geographic entities), so we just check mobile.
return checkNumberLengthForType(nationalNumber, 'MOBILE', metadata);
}
var mobile_type = metadata.type('MOBILE');
if (mobile_type) {
// Merge the mobile data in if there was any. "Concat" creates a new
// array, it doesn't edit possible_lengths in place, so we don't need a copy.
// Note that when adding the possible lengths from mobile, we have
// to again check they aren't empty since if they are this indicates
// they are the same as the general desc and should be obtained from there.
possible_lengths = mergeArrays(possible_lengths, mobile_type.possibleLengths()); // The current list is sorted; we need to merge in the new list and
// re-sort (duplicates are okay). Sorting isn't so expensive because
// the lists are very small.
// if (local_lengths) {
// local_lengths = mergeArrays(local_lengths, mobile_type.possibleLengthsLocal())
// } else {
// local_lengths = mobile_type.possibleLengthsLocal()
// }
}
} // If the type doesn't exist then return 'INVALID_LENGTH'.
else if (type && !type_info) {
return 'INVALID_LENGTH';
}
var actual_length = nationalNumber.length; // In `libphonenumber-js` all "local-only" formats are dropped for simplicity.
// // This is safe because there is never an overlap beween the possible lengths
// // and the local-only lengths; this is checked at build time.
// if (local_lengths && local_lengths.indexOf(nationalNumber.length) >= 0)
// {
// return 'IS_POSSIBLE_LOCAL_ONLY'
// }
var minimum_length = possible_lengths[0];
if (minimum_length === actual_length) {
return 'IS_POSSIBLE';
}
if (minimum_length > actual_length) {
return 'TOO_SHORT';
}
if (possible_lengths[possible_lengths.length - 1] < actual_length) {
return 'TOO_LONG';
} // We skip the first element since we've already checked it.
return possible_lengths.indexOf(actual_length, 1) >= 0 ? 'IS_POSSIBLE' : 'INVALID_LENGTH';
} |
JavaScript | function matchesEntirely(text, regular_expression) {
// If assigning the `''` default value is moved to the arguments above,
// code coverage would decrease for some weird reason.
text = text || '';
return new RegExp('^(?:' + regular_expression + ')$').test(text);
} | function matchesEntirely(text, regular_expression) {
// If assigning the `''` default value is moved to the arguments above,
// code coverage would decrease for some weird reason.
text = text || '';
return new RegExp('^(?:' + regular_expression + ')$').test(text);
} |
JavaScript | function isValidNumber(input, options, metadata) {
// If assigning the `{}` default value is moved to the arguments above,
// code coverage would decrease for some weird reason.
options = options || {};
metadata = new Metadata(metadata); // This is just to support `isValidNumber({})`
// for cases when `parseNumber()` returns `{}`.
if (!input.country) {
return false;
}
metadata.selectNumberingPlan(input.country, input.countryCallingCode); // By default, countries only have type regexps when it's required for
// distinguishing different countries having the same `countryCallingCode`.
if (metadata.hasTypes()) {
return getNumberType(input, options, metadata.metadata) !== undefined;
} // If there are no type regexps for this country in metadata then use
// `nationalNumberPattern` as a "better than nothing" replacement.
var national_number = options.v2 ? input.nationalNumber : input.phone;
return matchesEntirely(national_number, metadata.nationalNumberPattern());
} | function isValidNumber(input, options, metadata) {
// If assigning the `{}` default value is moved to the arguments above,
// code coverage would decrease for some weird reason.
options = options || {};
metadata = new Metadata(metadata); // This is just to support `isValidNumber({})`
// for cases when `parseNumber()` returns `{}`.
if (!input.country) {
return false;
}
metadata.selectNumberingPlan(input.country, input.countryCallingCode); // By default, countries only have type regexps when it's required for
// distinguishing different countries having the same `countryCallingCode`.
if (metadata.hasTypes()) {
return getNumberType(input, options, metadata.metadata) !== undefined;
} // If there are no type regexps for this country in metadata then use
// `nationalNumberPattern` as a "better than nothing" replacement.
var national_number = options.v2 ? input.nationalNumber : input.phone;
return matchesEntirely(national_number, metadata.nationalNumberPattern());
} |
JavaScript | function isPhoneNumber(value, region) {
try {
var phoneNum = parsePhoneNumberFromString$2(value, region);
var result = phoneNum === null || phoneNum === void 0 ? void 0 : phoneNum.isValid();
return !!result;
}
catch (error) {
// logging?
return false;
}
} | function isPhoneNumber(value, region) {
try {
var phoneNum = parsePhoneNumberFromString$2(value, region);
var result = phoneNum === null || phoneNum === void 0 ? void 0 : phoneNum.isValid();
return !!result;
}
catch (error) {
// logging?
return false;
}
} |
JavaScript | function IsPhoneNumber(region, validationOptions) {
return ValidateBy({
name: IS_PHONE_NUMBER,
constraints: [region],
validator: {
validate: function (value, args) { return isPhoneNumber(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid phone number'; }, validationOptions),
},
}, validationOptions);
} | function IsPhoneNumber(region, validationOptions) {
return ValidateBy({
name: IS_PHONE_NUMBER,
constraints: [region],
validator: {
validate: function (value, args) { return isPhoneNumber(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid phone number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsMilitaryTime(validationOptions) {
return ValidateBy({
name: IS_MILITARY_TIME,
validator: {
validate: function (value, args) { return isMilitaryTime(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid representation of military time in the format HH:MM'; }, validationOptions),
},
}, validationOptions);
} | function IsMilitaryTime(validationOptions) {
return ValidateBy({
name: IS_MILITARY_TIME,
validator: {
validate: function (value, args) { return isMilitaryTime(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid representation of military time in the format HH:MM'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsHash(algorithm, validationOptions) {
return ValidateBy({
name: IS_HASH,
constraints: [algorithm],
validator: {
validate: function (value, args) { return isHash(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a hash of type $constraint1'; }, validationOptions),
},
}, validationOptions);
} | function IsHash(algorithm, validationOptions) {
return ValidateBy({
name: IS_HASH,
constraints: [algorithm],
validator: {
validate: function (value, args) { return isHash(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a hash of type $constraint1'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsISSN(options, validationOptions) {
return ValidateBy({
name: IS_ISSN,
constraints: [options],
validator: {
validate: function (value, args) { return isISSN(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a ISSN'; }, validationOptions),
},
}, validationOptions);
} | function IsISSN(options, validationOptions) {
return ValidateBy({
name: IS_ISSN,
constraints: [options],
validator: {
validate: function (value, args) { return isISSN(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a ISSN'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsBooleanString(validationOptions) {
return ValidateBy({
name: IS_BOOLEAN_STRING,
validator: {
validate: function (value, args) { return isBooleanString(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a boolean string'; }, validationOptions),
},
}, validationOptions);
} | function IsBooleanString(validationOptions) {
return ValidateBy({
name: IS_BOOLEAN_STRING,
validator: {
validate: function (value, args) { return isBooleanString(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a boolean string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsNumberString(options, validationOptions) {
return ValidateBy({
name: IS_NUMBER_STRING,
constraints: [options],
validator: {
validate: function (value, args) { return isNumberString(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a number string'; }, validationOptions),
},
}, validationOptions);
} | function IsNumberString(options, validationOptions) {
return ValidateBy({
name: IS_NUMBER_STRING,
constraints: [options],
validator: {
validate: function (value, args) { return isNumberString(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a number string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsBase32(validationOptions) {
return ValidateBy({
name: IS_BASE32,
validator: {
validate: function (value, args) { return isBase32(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be base32 encoded'; }, validationOptions),
},
}, validationOptions);
} | function IsBase32(validationOptions) {
return ValidateBy({
name: IS_BASE32,
validator: {
validate: function (value, args) { return isBase32(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be base32 encoded'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsBIC(validationOptions) {
return ValidateBy({
name: IS_BIC,
validator: {
validate: function (value, args) { return isBIC(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a BIC or SWIFT code'; }, validationOptions),
},
}, validationOptions);
} | function IsBIC(validationOptions) {
return ValidateBy({
name: IS_BIC,
validator: {
validate: function (value, args) { return isBIC(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a BIC or SWIFT code'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsBtcAddress(validationOptions) {
return ValidateBy({
name: IS_BTC_ADDRESS,
validator: {
validate: function (value, args) { return isBtcAddress(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a BTC address'; }, validationOptions),
},
}, validationOptions);
} | function IsBtcAddress(validationOptions) {
return ValidateBy({
name: IS_BTC_ADDRESS,
validator: {
validate: function (value, args) { return isBtcAddress(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a BTC address'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsDataURI(validationOptions) {
return ValidateBy({
name: IS_DATA_URI,
validator: {
validate: function (value, args) { return isDataURI(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a data uri format'; }, validationOptions),
},
}, validationOptions);
} | function IsDataURI(validationOptions) {
return ValidateBy({
name: IS_DATA_URI,
validator: {
validate: function (value, args) { return isDataURI(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a data uri format'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsEAN(validationOptions) {
return ValidateBy({
name: IS_EAN,
validator: {
validate: function (value, args) { return isEAN(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an EAN (European Article Number)'; }, validationOptions),
},
}, validationOptions);
} | function IsEAN(validationOptions) {
return ValidateBy({
name: IS_EAN,
validator: {
validate: function (value, args) { return isEAN(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an EAN (European Article Number)'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsEthereumAddress(validationOptions) {
return ValidateBy({
name: IS_ETHEREUM_ADDRESS,
validator: {
validate: function (value, args) { return isEthereumAddress(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an Ethereum address'; }, validationOptions),
},
}, validationOptions);
} | function IsEthereumAddress(validationOptions) {
return ValidateBy({
name: IS_ETHEREUM_ADDRESS,
validator: {
validate: function (value, args) { return isEthereumAddress(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an Ethereum address'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsHSL(validationOptions) {
return ValidateBy({
name: IS_HSL,
validator: {
validate: function (value, args) { return isHSL(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a HSL color'; }, validationOptions),
},
}, validationOptions);
} | function IsHSL(validationOptions) {
return ValidateBy({
name: IS_HSL,
validator: {
validate: function (value, args) { return isHSL(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a HSL color'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsIBAN(validationOptions) {
return ValidateBy({
name: IS_IBAN,
validator: {
validate: function (value, args) { return isIBAN(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an IBAN'; }, validationOptions),
},
}, validationOptions);
} | function IsIBAN(validationOptions) {
return ValidateBy({
name: IS_IBAN,
validator: {
validate: function (value, args) { return isIBAN(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an IBAN'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsIdentityCard(locale, validationOptions) {
return ValidateBy({
name: IS_IDENTITY_CARD,
constraints: [locale],
validator: {
validate: function (value, args) { return isIdentityCard(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a identity card number'; }, validationOptions),
},
}, validationOptions);
} | function IsIdentityCard(locale, validationOptions) {
return ValidateBy({
name: IS_IDENTITY_CARD,
constraints: [locale],
validator: {
validate: function (value, args) { return isIdentityCard(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a identity card number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsISRC(validationOptions) {
return ValidateBy({
name: IS_ISRC,
validator: {
validate: function (value, args) { return isISRC(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an ISRC'; }, validationOptions),
},
}, validationOptions);
} | function IsISRC(validationOptions) {
return ValidateBy({
name: IS_ISRC,
validator: {
validate: function (value, args) { return isISRC(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an ISRC'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsLocale(validationOptions) {
return ValidateBy({
name: IS_LOCALE,
validator: {
validate: function (value, args) { return isLocale(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be locale'; }, validationOptions),
},
}, validationOptions);
} | function IsLocale(validationOptions) {
return ValidateBy({
name: IS_LOCALE,
validator: {
validate: function (value, args) { return isLocale(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be locale'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsMagnetURI(validationOptions) {
return ValidateBy({
name: IS_MAGNET_URI,
validator: {
validate: function (value, args) { return isMagnetURI(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be magnet uri format'; }, validationOptions),
},
}, validationOptions);
} | function IsMagnetURI(validationOptions) {
return ValidateBy({
name: IS_MAGNET_URI,
validator: {
validate: function (value, args) { return isMagnetURI(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be magnet uri format'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsMimeType(validationOptions) {
return ValidateBy({
name: IS_MIME_TYPE,
validator: {
validate: function (value, args) { return isMimeType(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be MIME type format'; }, validationOptions),
},
}, validationOptions);
} | function IsMimeType(validationOptions) {
return ValidateBy({
name: IS_MIME_TYPE,
validator: {
validate: function (value, args) { return isMimeType(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be MIME type format'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsOctal(validationOptions) {
return ValidateBy({
name: IS_OCTAL,
validator: {
validate: function (value, args) { return isOctal(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be valid octal number'; }, validationOptions),
},
}, validationOptions);
} | function IsOctal(validationOptions) {
return ValidateBy({
name: IS_OCTAL,
validator: {
validate: function (value, args) { return isOctal(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be valid octal number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsPassportNumber(countryCode, validationOptions) {
return ValidateBy({
name: IS_PASSPORT_NUMBER,
constraints: [countryCode],
validator: {
validate: function (value, args) { return isPassportNumber(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be valid passport number'; }, validationOptions),
},
}, validationOptions);
} | function IsPassportNumber(countryCode, validationOptions) {
return ValidateBy({
name: IS_PASSPORT_NUMBER,
constraints: [countryCode],
validator: {
validate: function (value, args) { return isPassportNumber(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be valid passport number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsRFC3339(validationOptions) {
return ValidateBy({
name: IS_RFC_3339,
validator: {
validate: function (value, args) { return isRFC3339(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be RFC 3339 date'; }, validationOptions),
},
}, validationOptions);
} | function IsRFC3339(validationOptions) {
return ValidateBy({
name: IS_RFC_3339,
validator: {
validate: function (value, args) { return isRFC3339(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be RFC 3339 date'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsRgbColor(includePercentValues, validationOptions) {
return ValidateBy({
name: IS_RGB_COLOR,
constraints: [includePercentValues],
validator: {
validate: function (value, args) { return isRgbColor(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be RGB color'; }, validationOptions),
},
}, validationOptions);
} | function IsRgbColor(includePercentValues, validationOptions) {
return ValidateBy({
name: IS_RGB_COLOR,
constraints: [includePercentValues],
validator: {
validate: function (value, args) { return isRgbColor(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be RGB color'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsSemVer(validationOptions) {
return ValidateBy({
name: IS_SEM_VER,
validator: {
validate: function (value, args) { return isSemVer(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a Semantic Versioning Specification'; }, validationOptions),
},
}, validationOptions);
} | function IsSemVer(validationOptions) {
return ValidateBy({
name: IS_SEM_VER,
validator: {
validate: function (value, args) { return isSemVer(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a Semantic Versioning Specification'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsBoolean(validationOptions) {
return ValidateBy({
name: IS_BOOLEAN,
validator: {
validate: function (value, args) { return isBoolean(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a boolean value'; }, validationOptions),
},
}, validationOptions);
} | function IsBoolean(validationOptions) {
return ValidateBy({
name: IS_BOOLEAN,
validator: {
validate: function (value, args) { return isBoolean(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a boolean value'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsDate(validationOptions) {
return ValidateBy({
name: IS_DATE,
validator: {
validate: function (value, args) { return isDate(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a Date instance'; }, validationOptions),
},
}, validationOptions);
} | function IsDate(validationOptions) {
return ValidateBy({
name: IS_DATE,
validator: {
validate: function (value, args) { return isDate(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a Date instance'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function isNumber(value, options) {
if (options === void 0) { options = {}; }
if (typeof value !== 'number') {
return false;
}
if (value === Infinity || value === -Infinity) {
return options.allowInfinity;
}
if (Number.isNaN(value)) {
return options.allowNaN;
}
if (options.maxDecimalPlaces !== undefined) {
var decimalPlaces = 0;
if (value % 1 !== 0) {
decimalPlaces = value.toString().split('.')[1].length;
}
if (decimalPlaces > options.maxDecimalPlaces) {
return false;
}
}
return Number.isFinite(value);
} | function isNumber(value, options) {
if (options === void 0) { options = {}; }
if (typeof value !== 'number') {
return false;
}
if (value === Infinity || value === -Infinity) {
return options.allowInfinity;
}
if (Number.isNaN(value)) {
return options.allowNaN;
}
if (options.maxDecimalPlaces !== undefined) {
var decimalPlaces = 0;
if (value % 1 !== 0) {
decimalPlaces = value.toString().split('.')[1].length;
}
if (decimalPlaces > options.maxDecimalPlaces) {
return false;
}
}
return Number.isFinite(value);
} |
JavaScript | function IsNumber(options, validationOptions) {
if (options === void 0) { options = {}; }
return ValidateBy({
name: IS_NUMBER,
constraints: [options],
validator: {
validate: function (value, args) { return isNumber(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a number conforming to the specified constraints'; }, validationOptions),
},
}, validationOptions);
} | function IsNumber(options, validationOptions) {
if (options === void 0) { options = {}; }
return ValidateBy({
name: IS_NUMBER,
constraints: [options],
validator: {
validate: function (value, args) { return isNumber(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a number conforming to the specified constraints'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsEnum(entity, validationOptions) {
return ValidateBy({
name: IS_ENUM,
constraints: [entity],
validator: {
validate: function (value, args) { return isEnum(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid enum value'; }, validationOptions),
},
}, validationOptions);
} | function IsEnum(entity, validationOptions) {
return ValidateBy({
name: IS_ENUM,
constraints: [entity],
validator: {
validate: function (value, args) { return isEnum(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a valid enum value'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsInt(validationOptions) {
return ValidateBy({
name: IS_INT,
validator: {
validate: function (value, args) { return isInt(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an integer number'; }, validationOptions),
},
}, validationOptions);
} | function IsInt(validationOptions) {
return ValidateBy({
name: IS_INT,
validator: {
validate: function (value, args) { return isInt(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an integer number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsString(validationOptions) {
return ValidateBy({
name: IS_STRING,
validator: {
validate: function (value, args) { return isString(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a string'; }, validationOptions),
},
}, validationOptions);
} | function IsString(validationOptions) {
return ValidateBy({
name: IS_STRING,
validator: {
validate: function (value, args) { return isString(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsArray(validationOptions) {
return ValidateBy({
name: IS_ARRAY,
validator: {
validate: function (value, args) { return isArray(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an array'; }, validationOptions),
},
}, validationOptions);
} | function IsArray(validationOptions) {
return ValidateBy({
name: IS_ARRAY,
validator: {
validate: function (value, args) { return isArray(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an array'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsObject(validationOptions) {
return ValidateBy({
name: IS_OBJECT,
validator: {
validate: function (value, args) { return isObject$1(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an object'; }, validationOptions),
},
}, validationOptions);
} | function IsObject(validationOptions) {
return ValidateBy({
name: IS_OBJECT,
validator: {
validate: function (value, args) { return isObject$1(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an object'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function arrayContains(array, values) {
if (!(array instanceof Array))
return false;
return values.every(function (value) { return array.indexOf(value) !== -1; });
} | function arrayContains(array, values) {
if (!(array instanceof Array))
return false;
return values.every(function (value) { return array.indexOf(value) !== -1; });
} |
JavaScript | function ArrayContains(values, validationOptions) {
return ValidateBy({
name: ARRAY_CONTAINS,
constraints: [values],
validator: {
validate: function (value, args) { return arrayContains(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain $constraint1 values'; }, validationOptions),
},
}, validationOptions);
} | function ArrayContains(values, validationOptions) {
return ValidateBy({
name: ARRAY_CONTAINS,
constraints: [values],
validator: {
validate: function (value, args) { return arrayContains(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain $constraint1 values'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function arrayNotContains(array, values) {
if (!(array instanceof Array))
return false;
return values.every(function (value) { return array.indexOf(value) === -1; });
} | function arrayNotContains(array, values) {
if (!(array instanceof Array))
return false;
return values.every(function (value) { return array.indexOf(value) === -1; });
} |
JavaScript | function ArrayNotContains(values, validationOptions) {
return ValidateBy({
name: ARRAY_NOT_CONTAINS,
constraints: [values],
validator: {
validate: function (value, args) { return arrayNotContains(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property should not contain $constraint1 values'; }, validationOptions),
},
}, validationOptions);
} | function ArrayNotContains(values, validationOptions) {
return ValidateBy({
name: ARRAY_NOT_CONTAINS,
constraints: [values],
validator: {
validate: function (value, args) { return arrayNotContains(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property should not contain $constraint1 values'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function ArrayNotEmpty(validationOptions) {
return ValidateBy({
name: ARRAY_NOT_EMPTY,
validator: {
validate: function (value, args) { return arrayNotEmpty(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property should not be empty'; }, validationOptions),
},
}, validationOptions);
} | function ArrayNotEmpty(validationOptions) {
return ValidateBy({
name: ARRAY_NOT_EMPTY,
validator: {
validate: function (value, args) { return arrayNotEmpty(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property should not be empty'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function ArrayMinSize(min, validationOptions) {
return ValidateBy({
name: ARRAY_MIN_SIZE,
constraints: [min],
validator: {
validate: function (value, args) { return arrayMinSize(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain at least $constraint1 elements'; }, validationOptions),
},
}, validationOptions);
} | function ArrayMinSize(min, validationOptions) {
return ValidateBy({
name: ARRAY_MIN_SIZE,
constraints: [min],
validator: {
validate: function (value, args) { return arrayMinSize(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain at least $constraint1 elements'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function ArrayMaxSize(max, validationOptions) {
return ValidateBy({
name: ARRAY_MAX_SIZE,
constraints: [max],
validator: {
validate: function (value, args) { return arrayMaxSize(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain not more than $constraint1 elements'; }, validationOptions),
},
}, validationOptions);
} | function ArrayMaxSize(max, validationOptions) {
return ValidateBy({
name: ARRAY_MAX_SIZE,
constraints: [max],
validator: {
validate: function (value, args) { return arrayMaxSize(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain not more than $constraint1 elements'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function arrayUnique(array, identifier) {
if (!(array instanceof Array))
return false;
if (identifier) {
array = array.map(function (o) { return (o != null ? identifier(o) : o); });
}
var uniqueItems = array.filter(function (a, b, c) { return c.indexOf(a) === b; });
return array.length === uniqueItems.length;
} | function arrayUnique(array, identifier) {
if (!(array instanceof Array))
return false;
if (identifier) {
array = array.map(function (o) { return (o != null ? identifier(o) : o); });
}
var uniqueItems = array.filter(function (a, b, c) { return c.indexOf(a) === b; });
return array.length === uniqueItems.length;
} |
JavaScript | function ArrayUnique(identifierOrOptions, validationOptions) {
var identifier = typeof identifierOrOptions === 'function' ? identifierOrOptions : undefined;
var options = typeof identifierOrOptions !== 'function' ? identifierOrOptions : validationOptions;
return ValidateBy({
name: ARRAY_UNIQUE,
validator: {
validate: function (value, args) { return arrayUnique(value, identifier); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + "All $property's elements must be unique"; }, options),
},
}, options);
} | function ArrayUnique(identifierOrOptions, validationOptions) {
var identifier = typeof identifierOrOptions === 'function' ? identifierOrOptions : undefined;
var options = typeof identifierOrOptions !== 'function' ? identifierOrOptions : validationOptions;
return ValidateBy({
name: ARRAY_UNIQUE,
validator: {
validate: function (value, args) { return arrayUnique(value, identifier); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + "All $property's elements must be unique"; }, options),
},
}, options);
} |
JavaScript | function isNotEmptyObject(value, options) {
if (!isObject$1(value)) {
return false;
}
if ((options === null || options === void 0 ? void 0 : options.nullable) === true) {
return !Object.values(value).every(function (propertyValue) { return propertyValue === null || propertyValue === undefined; });
}
for (var key in value) {
if (value.hasOwnProperty(key)) {
return true;
}
}
return false;
} | function isNotEmptyObject(value, options) {
if (!isObject$1(value)) {
return false;
}
if ((options === null || options === void 0 ? void 0 : options.nullable) === true) {
return !Object.values(value).every(function (propertyValue) { return propertyValue === null || propertyValue === undefined; });
}
for (var key in value) {
if (value.hasOwnProperty(key)) {
return true;
}
}
return false;
} |
JavaScript | function IsNotEmptyObject(options, validationOptions) {
return ValidateBy({
name: IS_NOT_EMPTY_OBJECT,
constraints: [options],
validator: {
validate: function (value, args) { return isNotEmptyObject(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a non-empty object'; }, validationOptions),
},
}, validationOptions);
} | function IsNotEmptyObject(options, validationOptions) {
return ValidateBy({
name: IS_NOT_EMPTY_OBJECT,
constraints: [options],
validator: {
validate: function (value, args) { return isNotEmptyObject(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a non-empty object'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsInstance(targetType, validationOptions) {
return ValidateBy({
name: IS_INSTANCE,
constraints: [targetType],
validator: {
validate: function (value, args) { return isInstance(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix, args) {
if (args.constraints[0]) {
return eachPrefix + ("$property must be an instance of " + args.constraints[0].name);
}
else {
return eachPrefix + (IS_INSTANCE + " decorator expects and object as value, but got falsy value.");
}
}, validationOptions),
},
}, validationOptions);
} | function IsInstance(targetType, validationOptions) {
return ValidateBy({
name: IS_INSTANCE,
constraints: [targetType],
validator: {
validate: function (value, args) { return isInstance(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix, args) {
if (args.constraints[0]) {
return eachPrefix + ("$property must be an instance of " + args.constraints[0].name);
}
else {
return eachPrefix + (IS_INSTANCE + " decorator expects and object as value, but got falsy value.");
}
}, validationOptions),
},
}, validationOptions);
} |
JavaScript | function validate(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions) {
if (typeof schemaNameOrObject === 'string') {
return getFromContainer(Validator).validate(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions);
}
else {
return getFromContainer(Validator).validate(schemaNameOrObject, objectOrValidationOptions);
}
} | function validate(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions) {
if (typeof schemaNameOrObject === 'string') {
return getFromContainer(Validator).validate(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions);
}
else {
return getFromContainer(Validator).validate(schemaNameOrObject, objectOrValidationOptions);
}
} |
JavaScript | function validateOrReject(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions) {
if (typeof schemaNameOrObject === 'string') {
return getFromContainer(Validator).validateOrReject(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions);
}
else {
return getFromContainer(Validator).validateOrReject(schemaNameOrObject, objectOrValidationOptions);
}
} | function validateOrReject(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions) {
if (typeof schemaNameOrObject === 'string') {
return getFromContainer(Validator).validateOrReject(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions);
}
else {
return getFromContainer(Validator).validateOrReject(schemaNameOrObject, objectOrValidationOptions);
}
} |
JavaScript | function validateSync(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions) {
if (typeof schemaNameOrObject === 'string') {
return getFromContainer(Validator).validateSync(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions);
}
else {
return getFromContainer(Validator).validateSync(schemaNameOrObject, objectOrValidationOptions);
}
} | function validateSync(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions) {
if (typeof schemaNameOrObject === 'string') {
return getFromContainer(Validator).validateSync(schemaNameOrObject, objectOrValidationOptions, maybeValidatorOptions);
}
else {
return getFromContainer(Validator).validateSync(schemaNameOrObject, objectOrValidationOptions);
}
} |
JavaScript | function createDreamTeam(members) {
// throw new NotImplementedError('Not implemented');
return members && members.length > 0
? members
.filter((i) => typeof i === 'string' && i.length > 0)
.map((j) => {
return j.trim().charAt(0).toUpperCase();
})
.sort()
.join('')
: false;
} | function createDreamTeam(members) {
// throw new NotImplementedError('Not implemented');
return members && members.length > 0
? members
.filter((i) => typeof i === 'string' && i.length > 0)
.map((j) => {
return j.trim().charAt(0).toUpperCase();
})
.sort()
.join('')
: false;
} |
JavaScript | function minesweeper(matrix) {
// throw new NotImplementedError('Not implemented');
// remove line with error and write your code here
let res_arr = JSON.parse(JSON.stringify(matrix)).map((i) => i.fill(0));
matrix.forEach((row, r_index) => {
row.forEach((elem, index) => {
if (elem) {
if (matrix[r_index - 1]) {
res_arr[r_index - 1][index] += 1;
res_arr[r_index - 1][index + 1] += 1;
res_arr[r_index - 1][index - 1] += 1;
}
if (matrix[r_index + 1]) {
res_arr[r_index + 1][index] += 1;
res_arr[r_index + 1][index + 1] += 1;
res_arr[r_index + 1][index - 1] += 1;
}
res_arr[r_index][index - 1] += 1;
res_arr[r_index][index + 1] += 1;
}
});
});
return res_arr;
} | function minesweeper(matrix) {
// throw new NotImplementedError('Not implemented');
// remove line with error and write your code here
let res_arr = JSON.parse(JSON.stringify(matrix)).map((i) => i.fill(0));
matrix.forEach((row, r_index) => {
row.forEach((elem, index) => {
if (elem) {
if (matrix[r_index - 1]) {
res_arr[r_index - 1][index] += 1;
res_arr[r_index - 1][index + 1] += 1;
res_arr[r_index - 1][index - 1] += 1;
}
if (matrix[r_index + 1]) {
res_arr[r_index + 1][index] += 1;
res_arr[r_index + 1][index + 1] += 1;
res_arr[r_index + 1][index - 1] += 1;
}
res_arr[r_index][index - 1] += 1;
res_arr[r_index][index + 1] += 1;
}
});
});
return res_arr;
} |
JavaScript | function FancyMessage(title, question, bullets, options) {
options = options || {title: "=", bullet: "*"};
if (options.title == "=") {
var stylizedTitle = title + "\n===============================";
}
else {
var stylizedTitle = "# " + title + " #";
}
var msg = `\`\`\`md\n${stylizedTitle}\`\`\`\n\`\`\`md\n< ${question} >\n\n`;
var stylizedBullets = "";
bullets.forEach((bullet) => {
stylizedBullets += options.bullet + " " + bullet + "\n";
});
msg += stylizedBullets + "\n<!-- Menu will close in 5 minutes.\nDo not include punctuation or the command prefix in your response. -->\`\`\`";
this.get = () => {return msg};
} | function FancyMessage(title, question, bullets, options) {
options = options || {title: "=", bullet: "*"};
if (options.title == "=") {
var stylizedTitle = title + "\n===============================";
}
else {
var stylizedTitle = "# " + title + " #";
}
var msg = `\`\`\`md\n${stylizedTitle}\`\`\`\n\`\`\`md\n< ${question} >\n\n`;
var stylizedBullets = "";
bullets.forEach((bullet) => {
stylizedBullets += options.bullet + " " + bullet + "\n";
});
msg += stylizedBullets + "\n<!-- Menu will close in 5 minutes.\nDo not include punctuation or the command prefix in your response. -->\`\`\`";
this.get = () => {return msg};
} |
JavaScript | function Interface(message, question, callback) {
var collected = false;
var closed = false;
var qMessage;
message.channel.send(question).then((msg) => {
qMessage = msg;
});
const collector = new Discord.MessageCollector(message.channel, m => m.author.id == message.author.id, {maxMatches: 1});
collector.on("collect", msg => {
collected = true;
callback(msg, qMessage);
});
collector.on("end", () => {
closed = true;
});
setTimeout(() => {
if (closed) return;
else if (!collected) {
collector.stop("User did not give a response within 5 minutes.");
qMessage.edit(`<a:no_animated:670060124399730699> <@!${message.author.id}>, the menu closed because you did not respond within 5 minutes.`);
closed = true;
callback(false);
}
}, 5 * 60 * 1000);
} | function Interface(message, question, callback) {
var collected = false;
var closed = false;
var qMessage;
message.channel.send(question).then((msg) => {
qMessage = msg;
});
const collector = new Discord.MessageCollector(message.channel, m => m.author.id == message.author.id, {maxMatches: 1});
collector.on("collect", msg => {
collected = true;
callback(msg, qMessage);
});
collector.on("end", () => {
closed = true;
});
setTimeout(() => {
if (closed) return;
else if (!collected) {
collector.stop("User did not give a response within 5 minutes.");
qMessage.edit(`<a:no_animated:670060124399730699> <@!${message.author.id}>, the menu closed because you did not respond within 5 minutes.`);
closed = true;
callback(false);
}
}, 5 * 60 * 1000);
} |
JavaScript | function viewLobby (event) {
hideElement(viewScoresCard);
showElement(lobbyCard);
// show high scores button
scoresBtn.style.visibility = "visible";
} | function viewLobby (event) {
hideElement(viewScoresCard);
showElement(lobbyCard);
// show high scores button
scoresBtn.style.visibility = "visible";
} |
JavaScript | function writeQuestion (index) {
clearGameBox();
questIndex.textContent = "Question #" + index;
// convert question object into an array for easier looping
// answers[0] -> question text
// answers[n] -> nth answer text
var answers = Object.values(questionArray[index]);
// create a header for the question
var questionHeading = document.createElement("h3");
questionHeading.textContent = answers[0];
gameBox.append(questionHeading);
// generate buttons for answers
for (i = 1; i < answers.length; i++) {
var answerEl = document.createElement("button");
// attach event listeners
answerEl.addEventListener("click", checkAnswer);
// add text and attach to document
answerEl.textContent = answers[i];
answerEl.setAttribute("class", "game-button");
gameBox.append(answerEl);
}
} | function writeQuestion (index) {
clearGameBox();
questIndex.textContent = "Question #" + index;
// convert question object into an array for easier looping
// answers[0] -> question text
// answers[n] -> nth answer text
var answers = Object.values(questionArray[index]);
// create a header for the question
var questionHeading = document.createElement("h3");
questionHeading.textContent = answers[0];
gameBox.append(questionHeading);
// generate buttons for answers
for (i = 1; i < answers.length; i++) {
var answerEl = document.createElement("button");
// attach event listeners
answerEl.addEventListener("click", checkAnswer);
// add text and attach to document
answerEl.textContent = answers[i];
answerEl.setAttribute("class", "game-button");
gameBox.append(answerEl);
}
} |
JavaScript | function checkAnswer (event) {
if (event.target.textContent == questionArray[index].correctAnswer) {
feedbackBox.textContent = "Correct!";
index++;
// player wins if last question is answered correctly
if (index == questionArray.length) {
victory();
} else {
writeQuestion(index);
}
// player is penalized 10 seconds for an incorrect answer
} else {
timeLeft -= 10;
feedbackBox.textContent = "Incorrect. You have lost 10 seconds";
}
} | function checkAnswer (event) {
if (event.target.textContent == questionArray[index].correctAnswer) {
feedbackBox.textContent = "Correct!";
index++;
// player wins if last question is answered correctly
if (index == questionArray.length) {
victory();
} else {
writeQuestion(index);
}
// player is penalized 10 seconds for an incorrect answer
} else {
timeLeft -= 10;
feedbackBox.textContent = "Incorrect. You have lost 10 seconds";
}
} |
JavaScript | function writeHighScores () {
clearScoreTable();
// if no high scores to display, print message
if (highScores.length == 0) {
let tableRow = document.createElement("tr"); // create a <tr>
let tableHead = document.createElement("th"); // create a <th>
tableHead.textContent = "No high scores to display"; // add text to <th>
tableRow.append(tableHead); // append <th> to <tr>
scoreTable.append(tableRow); // append <tr> to <table>
} else {
let topRow = document.createElement("tr"); // create a <tr>
// create table headers for initials and score and append
let initHead = document.createElement("th");
initHead.textContent = "Initials";
topRow.append(initHead);
let scoreHead = document.createElement("th");
scoreHead.textContent = "Score";
topRow.append(scoreHead);
scoreTable.append(topRow);
// loop over high scores array
for (let i = 0; i < highScores.length; i++) {
let currentRow = document.createElement("tr"); // create a <tr>
let initDeet = document.createElement("td"); // create a <td>
initDeet.textContent = highScores[i].initials; // add initials str to <td>
currentRow.append(initDeet); // append to <tr>
let scoreDeet = document.createElement("td"); // create a <td>
scoreDeet.textContent = highScores[i].score; // add score str to <td>
currentRow.append(scoreDeet); // append to <tr>
scoreTable.append(currentRow); // append <tr> to <table>
}
}
} | function writeHighScores () {
clearScoreTable();
// if no high scores to display, print message
if (highScores.length == 0) {
let tableRow = document.createElement("tr"); // create a <tr>
let tableHead = document.createElement("th"); // create a <th>
tableHead.textContent = "No high scores to display"; // add text to <th>
tableRow.append(tableHead); // append <th> to <tr>
scoreTable.append(tableRow); // append <tr> to <table>
} else {
let topRow = document.createElement("tr"); // create a <tr>
// create table headers for initials and score and append
let initHead = document.createElement("th");
initHead.textContent = "Initials";
topRow.append(initHead);
let scoreHead = document.createElement("th");
scoreHead.textContent = "Score";
topRow.append(scoreHead);
scoreTable.append(topRow);
// loop over high scores array
for (let i = 0; i < highScores.length; i++) {
let currentRow = document.createElement("tr"); // create a <tr>
let initDeet = document.createElement("td"); // create a <td>
initDeet.textContent = highScores[i].initials; // add initials str to <td>
currentRow.append(initDeet); // append to <tr>
let scoreDeet = document.createElement("td"); // create a <td>
scoreDeet.textContent = highScores[i].score; // add score str to <td>
currentRow.append(scoreDeet); // append to <tr>
scoreTable.append(currentRow); // append <tr> to <table>
}
}
} |
JavaScript | function clearGameBox () {
while (gameBox.hasChildNodes()) {
gameBox.removeChild(gameBox.firstChild);
}
} | function clearGameBox () {
while (gameBox.hasChildNodes()) {
gameBox.removeChild(gameBox.firstChild);
}
} |
JavaScript | function clearScoreTable () {
while (scoreTable.hasChildNodes()) {
scoreTable.removeChild(scoreTable.firstChild);
}
} | function clearScoreTable () {
while (scoreTable.hasChildNodes()) {
scoreTable.removeChild(scoreTable.firstChild);
}
} |
JavaScript | function naturalSort(a, b) {
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
ore = /^0/,
// convert all to strings and trim()
x = a.toString().replace(sre, '') || '',
y = b.toString().replace(sre, '') || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0');
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
else if (typeof oFxNcL !== typeof oFyNcL) {
oFxNcL += '';
oFyNcL += '';
}
if (oFxNcL < oFyNcL) return -1;
if (oFxNcL > oFyNcL) return 1;
}
return 0;
} | function naturalSort(a, b) {
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
ore = /^0/,
// convert all to strings and trim()
x = a.toString().replace(sre, '') || '',
y = b.toString().replace(sre, '') || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0');
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
else if (typeof oFxNcL !== typeof oFyNcL) {
oFxNcL += '';
oFyNcL += '';
}
if (oFxNcL < oFyNcL) return -1;
if (oFxNcL > oFyNcL) return 1;
}
return 0;
} |
JavaScript | function deserializeQueryString(dataString) {
return _.reduce(dataString.split('&'), function(hash, pair) {
if ((pair = pair.split('='))[0]) {
var key = decodeURIComponent(pair.shift());
var value = pair.length > 1 ? pair.join('=') : pair[0];
if (value != undefined) value = decodeURIComponent(value);
if (key in hash) {
if (!_.isArray(hash[key]))
hash[key] = [hash[key]];
hash[key].push(value);
}
else hash[key] = value;
}
return hash;
}, {})
} | function deserializeQueryString(dataString) {
return _.reduce(dataString.split('&'), function(hash, pair) {
if ((pair = pair.split('='))[0]) {
var key = decodeURIComponent(pair.shift());
var value = pair.length > 1 ? pair.join('=') : pair[0];
if (value != undefined) value = decodeURIComponent(value);
if (key in hash) {
if (!_.isArray(hash[key]))
hash[key] = [hash[key]];
hash[key].push(value);
}
else hash[key] = value;
}
return hash;
}, {})
} |
JavaScript | function defaultComparator(a, b) {
a = String(a);
b = String(b);
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
} | function defaultComparator(a, b) {
a = String(a);
b = String(b);
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
} |
JavaScript | function naturalSort (a, b) {
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
ore = /^0/,
// convert all to strings and trim()
x = a.toString().replace(sre, '') || '',
y = b.toString().replace(sre, '') || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0');
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
else if (typeof oFxNcL !== typeof oFyNcL) {
oFxNcL += '';
oFyNcL += '';
}
if (oFxNcL < oFyNcL) return -1;
if (oFxNcL > oFyNcL) return 1;
}
return 0;
} | function naturalSort (a, b) {
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
ore = /^0/,
// convert all to strings and trim()
x = a.toString().replace(sre, '') || '',
y = b.toString().replace(sre, '') || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0');
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
else if (typeof oFxNcL !== typeof oFyNcL) {
oFxNcL += '';
oFyNcL += '';
}
if (oFxNcL < oFyNcL) return -1;
if (oFxNcL > oFyNcL) return 1;
}
return 0;
} |
JavaScript | function enableForm() {
self.formValidator.unpause();
closeCleanup();
toDisable.add(self.dialog)
.boolAttr('disabled', false).css('cursor', 'auto');
} | function enableForm() {
self.formValidator.unpause();
closeCleanup();
toDisable.add(self.dialog)
.boolAttr('disabled', false).css('cursor', 'auto');
} |
JavaScript | function request(url, params) {
if (typeof BUGSNAG_TESTING !== "undefined" && self.testRequest) {
self.testRequest(url, params);
} else {
var img = new Image();
img.src = url + "?" + serialize(params) + "&ct=img&cb=" + new Date().getTime();
}
} | function request(url, params) {
if (typeof BUGSNAG_TESTING !== "undefined" && self.testRequest) {
self.testRequest(url, params);
} else {
var img = new Image();
img.src = url + "?" + serialize(params) + "&ct=img&cb=" + new Date().getTime();
}
} |
JavaScript | function sendToBugsnag(details, metaData) {
// Validate the configured API key.
var apiKey = getSetting("apiKey");
if (!validateApiKey(apiKey) || !eventsRemaining) {
return;
}
eventsRemaining -= 1;
// Check if we should notify for this release stage.
var releaseStage = getSetting("releaseStage");
var notifyReleaseStages = getSetting("notifyReleaseStages");
if (notifyReleaseStages) {
var shouldNotify = false;
for (var i = 0; i < notifyReleaseStages.length; i++) {
if (releaseStage === notifyReleaseStages[i]) {
shouldNotify = true;
break;
}
}
if (!shouldNotify) {
return;
}
}
// Don't send multiple copies of the same error.
// This fixes a problem when a client goes into an infinite loop,
// and starts wasting all their bandwidth sending messages to bugsnag.
var deduplicate = [details.name, details.message, details.stacktrace].join("|");
if (deduplicate === previousNotification) {
return;
} else {
previousNotification = deduplicate;
}
if (lastEvent) {
metaData = metaData || {};
metaData["Last Event"] = eventToMetaData(lastEvent);
}
// Merge the local and global `metaData`.
var mergedMetaData = merge(merge({}, getSetting("metaData")), metaData);
// Run any `beforeNotify` function
var beforeNotify = self.beforeNotify;
if (typeof(beforeNotify) === "function") {
var retVal = beforeNotify(details, mergedMetaData);
if (retVal === false) {
return;
}
}
// Make the request:
//
// - Work out which endpoint to send to.
// - Combine error information with other data such as
// user-agent and locale, `metaData` and settings.
// - Make the HTTP request.
var location = window.location;
request(getSetting("endpoint") || DEFAULT_NOTIFIER_ENDPOINT, {
notifierVersion: NOTIFIER_VERSION,
apiKey: apiKey,
projectRoot: getSetting("projectRoot") || location.protocol + "//" + location.host,
context: getSetting("context") || location.pathname,
userId: getSetting("userId"), // Deprecated, remove in v3
user: getSetting("user"),
metaData: mergedMetaData,
releaseStage: releaseStage,
appVersion: getSetting("appVersion"),
url: window.location.href,
userAgent: navigator.userAgent,
language: navigator.language || navigator.userLanguage,
severity: details.severity,
name: details.name,
message: details.message,
stacktrace: details.stacktrace,
file: details.file,
lineNumber: details.lineNumber,
columnNumber: details.columnNumber,
payloadVersion: "2"
});
} | function sendToBugsnag(details, metaData) {
// Validate the configured API key.
var apiKey = getSetting("apiKey");
if (!validateApiKey(apiKey) || !eventsRemaining) {
return;
}
eventsRemaining -= 1;
// Check if we should notify for this release stage.
var releaseStage = getSetting("releaseStage");
var notifyReleaseStages = getSetting("notifyReleaseStages");
if (notifyReleaseStages) {
var shouldNotify = false;
for (var i = 0; i < notifyReleaseStages.length; i++) {
if (releaseStage === notifyReleaseStages[i]) {
shouldNotify = true;
break;
}
}
if (!shouldNotify) {
return;
}
}
// Don't send multiple copies of the same error.
// This fixes a problem when a client goes into an infinite loop,
// and starts wasting all their bandwidth sending messages to bugsnag.
var deduplicate = [details.name, details.message, details.stacktrace].join("|");
if (deduplicate === previousNotification) {
return;
} else {
previousNotification = deduplicate;
}
if (lastEvent) {
metaData = metaData || {};
metaData["Last Event"] = eventToMetaData(lastEvent);
}
// Merge the local and global `metaData`.
var mergedMetaData = merge(merge({}, getSetting("metaData")), metaData);
// Run any `beforeNotify` function
var beforeNotify = self.beforeNotify;
if (typeof(beforeNotify) === "function") {
var retVal = beforeNotify(details, mergedMetaData);
if (retVal === false) {
return;
}
}
// Make the request:
//
// - Work out which endpoint to send to.
// - Combine error information with other data such as
// user-agent and locale, `metaData` and settings.
// - Make the HTTP request.
var location = window.location;
request(getSetting("endpoint") || DEFAULT_NOTIFIER_ENDPOINT, {
notifierVersion: NOTIFIER_VERSION,
apiKey: apiKey,
projectRoot: getSetting("projectRoot") || location.protocol + "//" + location.host,
context: getSetting("context") || location.pathname,
userId: getSetting("userId"), // Deprecated, remove in v3
user: getSetting("user"),
metaData: mergedMetaData,
releaseStage: releaseStage,
appVersion: getSetting("appVersion"),
url: window.location.href,
userAgent: navigator.userAgent,
language: navigator.language || navigator.userLanguage,
severity: details.severity,
name: details.name,
message: details.message,
stacktrace: details.stacktrace,
file: details.file,
lineNumber: details.lineNumber,
columnNumber: details.columnNumber,
payloadVersion: "2"
});
} |
JavaScript | function generateStacktrace() {
var stacktrace;
var MAX_FAKE_STACK_SIZE = 10;
var ANONYMOUS_FUNCTION_PLACEHOLDER = "[anonymous]";
// Try to generate a real stacktrace (most browsers, except IE9 and below).
try {
throw new Error("");
} catch (exception) {
stacktrace = stacktraceFromException(exception);
}
// Otherwise, build a fake stacktrace from the list of method names by
// looping through the list of functions that called this one (and skip
// whoever called us).
if (!stacktrace) {
var functionStack = [];
try {
var curr = arguments.callee.caller.caller;
while (curr && functionStack.length < MAX_FAKE_STACK_SIZE) {
var fn = FUNCTION_REGEX.test(curr.toString()) ? RegExp.$1 || ANONYMOUS_FUNCTION_PLACEHOLDER : ANONYMOUS_FUNCTION_PLACEHOLDER;
functionStack.push(fn);
curr = curr.caller;
}
} catch (e) {
log(e);
}
stacktrace = functionStack.join("\n");
}
// Tell the backend to ignore the first two lines in the stack-trace.
// generateStacktrace() + window.onerror,
// generateStacktrace() + notify,
// generateStacktrace() + notifyException
return "<generated>\n" + stacktrace;
} | function generateStacktrace() {
var stacktrace;
var MAX_FAKE_STACK_SIZE = 10;
var ANONYMOUS_FUNCTION_PLACEHOLDER = "[anonymous]";
// Try to generate a real stacktrace (most browsers, except IE9 and below).
try {
throw new Error("");
} catch (exception) {
stacktrace = stacktraceFromException(exception);
}
// Otherwise, build a fake stacktrace from the list of method names by
// looping through the list of functions that called this one (and skip
// whoever called us).
if (!stacktrace) {
var functionStack = [];
try {
var curr = arguments.callee.caller.caller;
while (curr && functionStack.length < MAX_FAKE_STACK_SIZE) {
var fn = FUNCTION_REGEX.test(curr.toString()) ? RegExp.$1 || ANONYMOUS_FUNCTION_PLACEHOLDER : ANONYMOUS_FUNCTION_PLACEHOLDER;
functionStack.push(fn);
curr = curr.caller;
}
} catch (e) {
log(e);
}
stacktrace = functionStack.join("\n");
}
// Tell the backend to ignore the first two lines in the stack-trace.
// generateStacktrace() + window.onerror,
// generateStacktrace() + notify,
// generateStacktrace() + notifyException
return "<generated>\n" + stacktrace;
} |
JavaScript | createBoard() {
let board = [];
// creates an array-of-arrays of true/false values
for(let y = 0; y < this.props.nrows; y++){
let row = [];
for(let x = 0; x < this.props.ncols; x++){
row.push(Math.random() < this.props.chanceLightStartsOn);
}
board.push(row);
}
return board
} | createBoard() {
let board = [];
// creates an array-of-arrays of true/false values
for(let y = 0; y < this.props.nrows; y++){
let row = [];
for(let x = 0; x < this.props.ncols; x++){
row.push(Math.random() < this.props.chanceLightStartsOn);
}
board.push(row);
}
return board
} |
JavaScript | flipCellsAround(coord) {
let {ncols, nrows} = this.props;
let board = this.state.board;
let [y, x] = coord.split("-").map(Number);
function flipCell(y, x) {
// if this coord is actually on board, flip it
if (x >= 0 && x < ncols && y >= 0 && y < nrows) {
board[y][x] = !board[y][x];
}
}
// flips this cell and the cells around it
flipCell(y, x);
flipCell(y, x - 1);
flipCell(y, x + 1);
flipCell(y - 1, x);
flipCell(y + 1, x);
// wins when every cell is turned off
// determines is the game has been won
let hasWon = board.every(row => row.every(cell => !cell));
this.setState({board: board, hasWon: hasWon});
} | flipCellsAround(coord) {
let {ncols, nrows} = this.props;
let board = this.state.board;
let [y, x] = coord.split("-").map(Number);
function flipCell(y, x) {
// if this coord is actually on board, flip it
if (x >= 0 && x < ncols && y >= 0 && y < nrows) {
board[y][x] = !board[y][x];
}
}
// flips this cell and the cells around it
flipCell(y, x);
flipCell(y, x - 1);
flipCell(y, x + 1);
flipCell(y - 1, x);
flipCell(y + 1, x);
// wins when every cell is turned off
// determines is the game has been won
let hasWon = board.every(row => row.every(cell => !cell));
this.setState({board: board, hasWon: hasWon});
} |
Subsets and Splits