"stringValues" is defined but never used no-unused-vars - javascript

I'm new to JS and I am trying to call a function inside another function. When I try it I am getting the lint error.
- stringValues inserts comma in between numbers to display correct formats, for 1000 it displays as 1,000 and for 10000 it displays as 10,000
return Number(unitsOfNumbers.join('')).stringValues();
providing my code and error below.
ERROR:
"stringValues" is defined but never used no-unused-vars
CODE:
import {differentCountriesCurrency} from 'sports-input-utils/lib/formatting';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.appleBrowser = appleBrowser;
exports.appleBrowserWithDecimals = appleBrowserWithDecimals;
function stringValues(x, sep, grp) {
var sx = (''+x).split('.'), s = '', i, j;
sep || (sep = ','); // default seperator
grp || grp === 0 || (grp = 3); // default grouping
i = sx[0].length;
while (i > grp) {
j = i - grp;
s = sep + sx[0].slice(j, i) + s;
i = j;
}
s = sx[0].slice(0, i) + s;
sx[0] = s;
return sx.join('.');
}
function appleBrowser(value, parm) {
var unitsOfNumbers;
if (!value) {
return value;
}
// extract unitsOfNumbers. if no unitsOfNumbers, fill in a zero.
unitsOfNumbers = value.match(/\d/g) || ['0'];
return Number(unitsOfNumbers.join('')).stringValues();
}
function appleBrowserWithDecimals(value, parm) {
var unitsOfNumbers;
if (!value) {
return value;
}
// extract unitsOfNumbers. if no unitsOfNumbers, fill in a zero.
unitsOfNumbers = value.match(/\d/g) || ['0'];
// zero-pad a one-digit input
if (unitsOfNumbers.length === 1) {
unitsOfNumbers.unshift('0');
}
// add a decimal point
unitsOfNumbers.splice(unitsOfNumbers.length - 2, 0, '.');
return Number(unitsOfNumbers.join('')).stringValues();
}
//# sourceMappingURL=formatting.js.map
exports.limitMaximumLength = limitMaximumLength;
function limitMaximumLength(value, parm) {
if (value.length < parm) {
return value;
} else {
return value.substring(0, parm);
}
}
exports.differentCountriesCurrencyWithMaxLen = differentCountriesCurrencyWithMaxLen;
function differentCountriesCurrencyWithMaxLen (value) {
var isSafari;
return differentCountriesCurrency(limitMaximumLength(value, 7));
isSafari = navigator.userAgent.indexOf("Safari") > -1;
if (isSafari) {
return appleBrowser(limitMaximumLength(value, 7));
}
}

Not worrying about other linting errors or checking anything about the logic (haven't checked if it does what you want or not), I can remove the no-unused-vars error like this:
import {differentCountriesCurrency} from 'sports-input-utils/lib/formatting';
Object.defineProperty(exports, '__esModule', {
value: true
});
function stringValues(x, sep, grp) {
var sx = (''+x).split('.'), s = '', i, j;
sep || (sep = ','); // default seperator
grp || grp === 0 || (grp = 3); // default grouping
i = sx[0].length;
while (i > grp) {
j = i - grp;
s = sep + sx[0].slice(j, i) + s;
i = j;
}
s = sx[0].slice(0, i) + s;
sx[0] = s;
return sx.join('.');
};
exports.appleBrowser = function (value, parm) {
var unitsOfNumbers;
if (!value) {
return value;
}
// extract unitsOfNumbers. if no unitsOfNumbers, fill in a zero.
unitsOfNumbers = value.match(/\d/g) || ['0'];
return stringValues(Number(unitsOfNumbers.join('')));
};
exports.appleBrowserWithDecimals = function (value, parm) {
var unitsOfNumbers;
if (!value) {
return value;
}
// extract unitsOfNumbers. if no unitsOfNumbers, fill in a zero.
unitsOfNumbers = value.match(/\d/g) || ['0'];
// zero-pad a one-digit input
if (unitsOfNumbers.length === 1) {
unitsOfNumbers.unshift('0');
}
// add a decimal point
unitsOfNumbers.splice(unitsOfNumbers.length - 2, 0, '.');
return stringValues(Number(unitsOfNumbers.join('')));
};
exports.limitMaximumLength = function (value, parm) {
if (value.length < parm) {
return value;
} else {
return value.substring(0, parm);
}
};
exports.differentCountriesCurrencyWithMaxLen = function (value) {
var isSafari;
return differentCountriesCurrency(limitMaximumLength(value, 7));
// ^^^ There's no way this ^^^ is what you want.
// The rest of the function is always ignored. You've already returned.
isSafari = navigator.userAgent.indexOf("Safari") > -1;
if (isSafari) {
return appleBrowser(limitMaximumLength(value, 7));
}
};
To remove the error, I did exactly what #JosephYoung says. You haven't added stringValues to whatever Number returns. You declared it globally.
So don't do this:
return Number(unitsOfNumbers.join('')).stringValues();
That pretends there's another stringValues as a function-property on Number's return value. Your function stringValues exists at global scope, and is never called.
To call what you declared, you do this:
return stringValues(Number(unitsOfNumbers.join('')));
One important readability issue to notice: Instead of the lines you have like this...
exports.limitMaximumLength = limitMaximumLength;
function limitMaximumLength(value, parm) {
... go ahead and put the assignment on a single line like this...
exports.limitMaximumLength = function (value, parm) {
Makes it easier to tell what you're exporting and what's a "private" utility function.

Related

Convert Arrow function to function expression

I have a function with a map object:
function xml_encode(s)
{
return Array.from(s).map(c =>
{
var cp = c.codePointAt(0);
return ((cp > 127) ? '&#' + cp + ';' : c);
}).join('');
}
This has worked great except it has broken everything when running Internet Explorer 11.
I tried to rewrite the code using a function expression however I get a c is not defined:
function xml_encode(s)
{
return Array.from(s).map(function()
{
var cp = c.codePointAt(0);
return ((cp > 127) ? '&#' + cp + ';' : c);
}).join('');
}
Unfortunately this needs to be a public-facing function and I am required to support IE11 for now. How do I rewrite this function to work with IE11?
You're missing the argument of your function so try this
function xml_encode(s) {
return Array.from(s).map(function(c) {
var cp = c.codePointAt(0);
return ((cp > 127) ? '&#' + cp + ';' : c);
}).join('');
}
You are missing the c paramter to your anonymous function.
function xml_encode(s)
{
return Array.from(s).map(
function(c) {
//use charCodeAt for IE or use a polyfill
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt#Polyfill
var cp = c.codePointAt(0);
return ((cp > 127) ? '&#' + cp + ';' : c);
}
).join('');
}
Bonus:
You might want to use s.split('') instead of Array.from(s) for better performance and browser support. String.prototype.split is supported in every browser while Array.from is not supported in IE for example. split is also 30% faster on Chrome and 80% faster on FF on my PC.
Try to modify your code as below (you are missing an argument in the function):
function xml_encode(s) {
return Array.from(s).map(function (c) {
var cp = c.codePointAt(0);
return cp > 127 ? '&#' + cp + ';' : c;
}).join('');
}
Since, you are using Array.from and codePointAt function, they don't support IE Browser. To use them in the IE browser, we need to add the related popyfill before using this function.
Polyfill code as below (I have created a sample to test it, it works well on my side.):
// Production steps of ECMA-262, Edition 6, 22.1.2.1
if (!Array.from) {
Array.from = (function () {
var toStr = Object.prototype.toString;
var isCallable = function (fn) {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
};
var toInteger = function (value) {
var number = Number(value);
if (isNaN(number)) { return 0; }
if (number === 0 || !isFinite(number)) { return number; }
return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
};
var maxSafeInteger = Math.pow(2, 53) - 1;
var toLength = function (value) {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
};
// The length property of the from method is 1.
return function from(arrayLike/*, mapFn, thisArg */) {
// 1. Let C be the this value.
var C = this;
// 2. Let items be ToObject(arrayLike).
var items = Object(arrayLike);
// 3. ReturnIfAbrupt(items).
if (arrayLike == null) {
throw new TypeError('Array.from requires an array-like object - not null or undefined');
}
// 4. If mapfn is undefined, then let mapping be false.
var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
var T;
if (typeof mapFn !== 'undefined') {
// 5. else
// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
if (!isCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
// 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 2) {
T = arguments[2];
}
}
// 10. Let lenValue be Get(items, "length").
// 11. Let len be ToLength(lenValue).
var len = toLength(items.length);
// 13. If IsConstructor(C) is true, then
// 13. a. Let A be the result of calling the [[Construct]] internal method
// of C with an argument list containing the single item len.
// 14. a. Else, Let A be ArrayCreate(len).
var A = isCallable(C) ? Object(new C(len)) : new Array(len);
// 16. Let k be 0.
var k = 0;
// 17. Repeat, while k < len… (also steps a - h)
var kValue;
while (k < len) {
kValue = items[k];
if (mapFn) {
A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
} else {
A[k] = kValue;
}
k += 1;
}
// 18. Let putStatus be Put(A, "length", len, true).
A.length = len;
// 20. Return A.
return A;
};
}());
}
/*! https://mths.be/codepointat v0.2.0 by #mathias */
if (!String.prototype.codePointAt) {
(function () {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var defineProperty = (function () {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result = $defineProperty(object, object, object) && $defineProperty;
} catch (error) { }
return result;
}());
var codePointAt = function (position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
// `ToInteger`
var index = position ? Number(position) : 0;
if (index != index) { // better `isNaN`
index = 0;
}
// Account for out-of-bounds indices:
if (index < 0 || index >= size) {
return undefined;
}
// Get the first code unit
var first = string.charCodeAt(index);
var second;
if ( // check if it’s the start of a surrogate pair
first >= 0xD800 && first <= 0xDBFF && // high surrogate
size > index + 1 // there is a next code unit
) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
};
if (defineProperty) {
defineProperty(String.prototype, 'codePointAt', {
'value': codePointAt,
'configurable': true,
'writable': true
});
} else {
String.prototype.codePointAt = codePointAt;
}
}());
}
More detail information, please check the Array.from() method and the codePointAt() method

Check if string exists in another string (not exactly equal)

I have this 2 strings:
var test = 'BN123';
var behaviour = 'BN***,TA****';
I need to check if behaviour contains a string with the same format as test.
On the behaviour, the BN and TA as to be equal, and the * means it can be any char. (behaviour comes from an API, so I never know what it has, this is just a test.)
In this case it should return true. Right now I'm only comparing is case behaviour as a single string, but I need to modify that:
isValidInput(behaviour, test) {
if (behaviour.length != test.length) {
return false;
}
for (var i = 0; i < behaviour.length; i++) {
if (behaviour.charAt(i) == '*') {
continue;
}
if (behaviour.charAt(i) != test.charAt(i)) {
return false;
}
}
return true;
}
You can use .some() of Array.prototype.
like below
function isValidInput(behaviour, string1) {
if (behaviour.length != string1.length) {
return false;
}
for (var i = 0; i < behaviour.length; i++) {
if (behaviour.charAt(i) == '*') {
continue;
}
if (behaviour.charAt(i) != string1.charAt(i)) {
return false;
}
}
return true;
}
var test = 'BN123';
var behaviour = 'BN***,TA****';
console.log(behaviour.split(',').some(x => isValidInput(x,test)));
console.log(behaviour.split(',').some(x => isValidInput(x,"test")));
The only issue I see with your implementation is that you're not allowing for the fact behaviour contains possible strings separated with a comma (or at least, that's how it looks to me). So you need to check each of them:
// Check one behaviour string from the list
function isOneValidInput(behaviour, string) {
if (behaviour.length != string.length) {
return false;
}
for (var i = 0; i < behaviour.length; i++) {
// Note we can easily combine those conditions, and use []
// with strings
if (behaviour[i] != '*' && behaviour[i] != string[i]) {
return false;
}
}
return true;
}
// Check all behaviour strings in a comma-separated one
function isValidInput(behaviours, string) {
return behaviours.split(",").some(function(behaviour) {
return isOneValidInput(behaviour, string);
});
}
var string = 'BN123';
var behaviour = 'BN***,TA****';
console.log(isValidInput(behaviour, string));
(I stuck to ES5 there because you seemed to be doing so.)
Is this what you want?
var test = 'BN123';
var behaviour = 'BN***,TA****';
var behaviours = behaviour.split(',');
var result = behaviours.map(b => {
if (b.length != test.length)
return false;
var pattern = b.split('*')[0];
return pattern === test.substring(0,pattern.length);
}).find(r => r === true) > -1;
console.log(result)
You can use the new .includes() method to see if a string is contained within another. Note that this is case sensitive. I have included two dodgied up behaviours to check the string against.
var string = 'BN123';
var behaviour1 = 'BN123,TA1234';
var behaviour2 = 'BN120,TA1230';
function testStr(behaviour,string) {
return behaviour.includes(string);
}
console.log(testStr(behaviour1,string)) // gives true
console.log(testStr(behaviour2,string)) // gives false
isValidInput(behaviour, string) {
var array = behaviour.split(",");
var flag = 0;
for(var i = 0;i< array.length;i++){
var now = array[i];
var _flag = 1;
if (now.length == string.length) {
for (var j = 0; j < now.length; j++) {
if (now.charAt(j) == '*') {
continue;
}
if (now.charAt(j) != string.charAt(j)) {
_flag = 0;
}
}
flag |= _flag;
}
}
return flag;
}
Try modify your behaviour to RegExp:
function checkFn(testStr) {
var behaviour = '(BN...)|(TA....)'
var r = new RegExp('^(' + behaviour + ')$')
return r.test(testStr)
}
checkFn('BN123') // true
checkFn('BN12') // false
checkFn('BN1234') // false
checkFn('TA1234') // true
checkFn('TA123') // false
checkFn('TA12345') // false
Or use this fn:
function checkFn(testStr) {
var behaviour = 'BN***,TA****'
behaviour = behaviour
.split(',')
.reduce((r, el) => {
r.push('(' + el.replace(/\*/g, '.') + ')')
return r
}, [])
.join('|')
var r = new RegExp('^('+behaviour+')$')
return r.test(testStr)
}

Javascript String Manipulation and Conversion with Range

I have a string like this (must be in this format):
var string = "[0] No new notifications | [1,] Some new notifications"
And I want to get "No new notifications" if a variable is 0 and if that variable is 1 or greater, show "Some new notifications".
How can I do that?
Here's a generic processesor for ISO 31-11 strings. It takes the ISO 31-11 string and the numeric value, then returns the appropriate string or undefined. Here's a fiddle.
function processISO31_11(rangeGuide, n) {
var separator = /\[(\d+)(,)?(\d+)?\]\s?(.+)/;
var rangeGuides = rangeGuide.split('|');
var guideCount = rangeGuides.length;
for (var guide = 0; guide < guideCount; guide++) {
var elements = separator.exec(rangeGuides[guide]);
if (elements != null) {
if (n < parseFloat(elements[1])) {
return; // return undefined indicating failure to match any range
}
if (n == parseFloat(elements[1])) {
return elements[4];
}
if (elements[2] === "," && (typeof elements[3] === "undefined" || n <= parseFloat(elements[3]))) {
return elements[4];
}
}
}
}
var somevar = 3;
var yourString = '[0] No new notifications | [1,] Some new notifications';
var notification = yourString .split(' | ');
var message=(somevar == 0 ? notification[0].split('] ')[1] : notification[1].split('] ')[1]);
the var message has your needed output.
After examining more closely exactly what you are looking for, I have come up with a solution that will read in the rules you pass it and essentially turn that into logic that your program will follow. Here is a demo of how it would work:
var myVar = 3;
var myStr = '[0] No new notifications | [1,4] Some new notifications | [5,] Several new notifications';
var notificationRules = getRules(myStr);
function getRules(rulesString) {
return rulesString.split(' | ').map(function(rule) {
var startValue, endValue;
var values = rule.match(/\[\d*,?\d*\]/g)[0];
values = values.replace(/\[|\]/g, "").split(",");
startValue = values[0];
endValue = +values[1] === 0 ? Infinity : values[1];
return {
startValue: Number(startValue),
endValue: endValue != undefined ? Number(endValue) : undefined,
message: rule.replace(/\[\d*,?\d*\]/g, "").trim()
};
});
}
function getMessage(myVar, rules) {
var message = "No rule match!";
rules.some(function(rule) {
if (myVar === rule.startValue) {
message = rule.message;
return true;
} else if (myVar >= rule.startValue && myVar <= rule.endValue) {
message = rule.message;
}
});
return message;
}
console.log(getMessage(0, notificationRules));
console.log(getMessage(2, notificationRules));
console.log(getMessage(5, notificationRules));
console.log(getMessage(100, notificationRules));
console.log(getMessage(-1, notificationRules));
Complex solution using String.prototype.split(), String.prototype.match() and String.prototype.slice() functions:
var configStr = '[0] No new notifications | [1,] Some new notifications',
getNotifyMessage = function (config, num) {
var num = Number(num),
items = config.split('|'),
len = items.length, parts;
while (len--) {
parts = items[len].match(/\[(\d+,?)\]\s([\w ]+)(?=\||$)/i);
if (Number(parts[1]) === num) {
return parts[2];
}
if (parts[1].slice(-1) === ',' && Number(parts[1].slice(0,-1)) <= num) {
return parts[2];
}
}
return '';
};
console.log(getNotifyMessage(configStr, 1));
console.log(getNotifyMessage(configStr, 0));
console.log(getNotifyMessage(configStr, 3));

If-else-statement returns undefined in palindrome function

In my palindrome function an if-else-statement returns undefined. Basically, I am trying to find the biggest palindromic number with three digits. For example with two digits: 99 * 91 = 9009.
var palindromic = function(n) {
var save,
result,
counter = 900;
var checker = function(string) {
s = string.toString();
if(!(s)) {
return true;
} else if(s[0] !== s[s.length - 1]) {
return false;
}
checker(s.slice(1, -1));
}
var recursive = function() {
result = counter * n;
if(counter === n) {
return;
} else if(checker(result)) { // this line of code here, undefined.
save = result;
}
counter++;
recursive();
}
recursive();
return save;
};
What is wrong? Any help is welcome!
There are two problems in the code
checker() should have return checker(s.slice(1,-1)); as last line.
In recursive() when checker(result) is true recursive() should return.
Here's corrected code.
var palindromic = function (n) {
var save,
result,
counter = 900;
var checker = function (s) {
//s = string.toString();
if ( !(s) ) {
return true;
} else if ( s[0] !== s[s.length-1] ) {
return false;
}
return checker(s.slice(1,-1));
}
var recursive = function () {
result = counter * n;
if ( counter === n ) {
return;
} else if ( checker(result + "") ) { // this line of code here, undefined.
save = result;
return;
}
counter++;
recursive();
}
recursive();
return save;
};
Output:
palindromic(2)
2002
palindromic(3)
2772
palindromic(5)
5005
palindromic(6)
6006
palindromic(9)
8118
palindromic(23423)
188484881
A little spoiler and improving
You can do it without a recursion.
Usage of a reverse function to reverse a string.
Usage of two for loops, starting from the highest number.
function strReverse(str) {
var reverse = "";
for(var i = (str.length - 1); i >= 0; i -= 1) {
reverse += str[i];
}
return reverse;
}
function palindromic(n) {
var highestPalindrom = 0;
// Start with the highest number!
for(var i = n; i > 1; i -= 1) {
// Start also with the highest number!
for(var j = n; j > 1; j -= 1) {
// Get product
var product = i * j;
// Compare the string in reverse with the string itself
// If it is true, then it is a palindrom!
if(strReverse(product.toString()) === product.toString()) {
highestPalindrom = product;
// Break inner loop
break;
}
}
// Break outer loop
break;
}
return highestPalindrom;
}
var hP = palindromic(99);
console.log(hP);

Change the parameter like this [function.value(new-value)]

function add(n) {
return function(x) {
this.value = n;
return this.value + x;
}
}
var add3 = add(3);
var add4 = add(4);
I'm trying to figure out if I can re-write this function above to:
Allow to modify the first parameter like this:
add3.value(1);
console.log(add3(4))
// 5
Also so that the value method returns the current value if no parameter is passed:
add3.value(1);
console.log(add3.value())
// 1
Functions are just objects, so you can assign a property value to it, whose value is a function that modifies n:
function add(n) {
var result = function(x) {
return n + x;
};
result.value = function(x) {
if (typeof x === 'undefined') {
return n;
}
n = x;
};
return result;
}
Why you'd want to do that I don't know, but it's possible.
To use the interface you've described, your inner function will need to return a object with a 'value' method.
eg.
function add (n) {
return {
value: function (x) {
x = x || 0;
return n + x;
}
};
}
But, what it sounds like you're trying to do is currying & partial application. In which case, returning a function is probably simpler.
function add (n) {
return function (x) {
x = x || 0;
return n + x;
};
}
This would be used like so:
var add3 = add(3);
console.log(add3(4)); // output: 7
or, with the default value:
var add4 = add(4);
console.log(add4()); // output: 4
Similar to Felix's answer, but permitting empty inputs, remembering last values and also giving it a valueOf so it can be used like a number itself.
function adder(i) {
i || (i = 0);
var add = function (x) {
return i += (+x || 0); // += modifies i
};
add.value = function (x) {
return !x && x !== 0 ? i : i = (+x || 0); // if x falsy but not zero
};
add.valueOf = function () {
return i;
};
return add;
}
var add = adder();
add.value(1); // 1
add(4); // 5
add(5); // 10
add + 2; // 12, via valueOf
add(); // 10

Categories

Resources