Javascript run a function against a variable usnig dot notation - javascript

I think I'm using the wrong terminology but here is what I would like to do. Using a function like this one:
function isNumeric(){
if (isNaN(this)) { return false; }
var x = parseFloat(this);
return (x | 0) === x;
};
I know this function won't work as is. I removed the parameter that was originally passed in and replaced it inside the function with this. I would like to call it like so:
var tmp1 = 10;
var tmp2 = "10";
if( tmp1.isNumeric() == true && tmp2.isNumeric() == true ){
...
}
Instead of this:
if( isNumeric(tmp1) == true && isNumeric(tmp2) == true ){
...
}

The way to achieve that is not considered a good option, but it's to modify the prototype chain for the types of data you want your function to work with, e.g. for number and string like your example you could have:
Number.prototype.isNumeric = String.prototype.isNumeric = function() {
// ...
}
What you have currently is the preferred option because it won't contaminate the prototype chain for inbuilt types, risk conflicts with other libraries, potentially overwrite functionality you didn't know existed, etc. You could meet halfway with something like:
class Val {
constructor(value) {
this.value = value;
}
isNumeric() {
if (isNaN(this.value)) { return false; }
var x = parseFloat(this.value);
return (x | 0) === x;
}
}
Used like:
var tmp1 = new Val(10);
var tmp2 = new Val('10');
console.log(tmp1.isNumeric(), tmp1.isNumeric());

try to add this function to Object.prototype
Object.prototype.isNumeric = function () {
return parseFloat(this) == this;
};

Below may be a better option for the class function if you are wanting "10" to return that is it not a number.
isNumeric() {
return typeof this.value === 'number';
}

isNumeric is just a function - what you are looking for is an object method. Right now, tmp1 and tmp2 are a Number, and String respectively, and neither of those have a function called isNumeric. You can restructure those variables like this if you want:
function TmpValue (initValue) {
this.value = initValue
}
TmpValue.prototype.isNumeric = function() {
if (isNaN(this.value)) { return false; }
var x = parseFloat(this.value);
return (x | 0) === x;
}
var tmp1 = new TmpValue(10);
var tmp2 = new TmpValue('10');

Related

How to replace return on if condition?

Is possible to replace by if condition instead using return while we have many condition in our program
var v2=[12,23,44,3,1,3,456,78,22];
function checkresult(v2) {
return v2 >= 18;
}
var a= v2.filter(checkresult);
document.getElementById("demo").innerHTML = a;
Yes, you can obviously use conditional statements inside a filter as long as you're returning a boolean value.
var v2=[12,23,44,3,1,3,456,78,22];
function checkresult(val) { // A suggestion to use different variable name other than v2
if(val >= 18)
return true;
else if(<condition-2>)
return true;
else if(<condition-n>)
return true;
return false;
}
var a= v2.filter(checkresult);
document.getElementById("demo").innerHTML = a;
Yes, it is possible
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
var a = [1,2,'a','b','a',1,'c'];
var unique = a.filter(onlyUnique);
As example this code, onlyUnique function is return unique values in array. You can change the function content.

Sequence from Class OO to Object Delegation pattern

My intention is to use function logFive2 to iterate over
a sequence object like ArraySeq2 or RangeSeq2 although I want to create the RangeSeq2 using Object delegation pattern and stay away from Class like way(ArraySeq2). What I am doing wrong with RangeSeq2?
My code doesn't work because logFive2 does not iterate over RangeSeq2 and I cannot see why. If you have any idea about what goes wrong please let me see. Thank you.
function logFive2(sequence){
for(var i = 0; i < 5 && sequence != null; i++){
console.log(sequence.head());
sequence = sequence.rest();
}
}
function ArraySeq2(array,offset){
this.array = array;
this.offset = offset;
}
ArraySeq2.prototype.rest = function(){
console.log("to follow " + this.offset);
return ArraySeq2.make(this.array,this.offset + 1);
};
ArraySeq2.prototype.head = function(){
return this.array[this.offset];
};
ArraySeq2.make = function(array,offset){
if(offset == null) offset = 0;
if(offset >= array.length)
return null;
else return new ArraySeq2(array,offset);
}
logFive2(ArraySeq2.make([1, 2,5,6,9,11]));
// → 1
// → 2
The part above works fine ______________ RangeSeq2 object it is my problem
var RangeSeq2 = {
init: function(from,to){
this.from = from;
this.to = to;
},
rest: function(){
if (from > to)
return null;
else
return this.init(this.from + 1,this.to);
},
head: function(){
return this.from;
}
};
var RangeTT = Object.create(RangeSeq2);
RangeTT.init(100,1000);
logFive2(RangeTT.init(100,1000));
function logFive2(sequence){
for(var i = 0; i < 5 ; i++){
console.log(sequence.head());
sequence.rest();
}
}
var RangeSeq2 = {
rest: function(){
if (this.from > this.to) {
return null;
}
else
return this.from += 1,this.to;
},
head: function(){
return this.from;
}
};
var RangeTT = Object.create(RangeSeq2);
RangeTT.from = 100;
RangeTT.to = 1000;
logFive2(RangeTT);
//100
//101
//102
//103
//104
Sorted out! the problem was so much simpler than I thought will be.
My problem was trying to do an unhealthy mixture of classical inheritance and instantiation over the Object delegation because I didn't understood how it works.
Soon as I managed to understand how "this" works and soon I understood Object.create (which is very powerful ) , the __proto__ and knew the difference it has compared to function Object.prototype I could find a solution.
1.My first mistake I think was trying to create state in the object by calling the method init() without having a property to hold the values in the object.
2.The rest() method would query on variables which would not exist on the object.
I have to mention that I had to change the iterator function LogFive2() to be suitable for the object delegation design in my case.

Javascript ING BANK 3 questions test interview

I had a test interview and for 3 questions I didn't know the answer:
Write a function that will insert underscore between characters: this will become t_h_i_s.
Write a function that will output this:
l('t') === 'lt'
l()('t') === 'l3t'
l()()('t') === 'l33t'
l()()('g') === 'l33g'
l()()()()()()()()()()()('t') === 'l33333333333t'
Why the output is true?
var bar = true;
function foo() {
bar = false;
return 5;
function bar() {}
}
foo();
console.log(bar);
Can someone help please with the answers?
Write a function that will insert underscore between characters: this will become t_h_i_s.
You want to write a function that iterates over all characters in a string, and appends an underscore between all characters.
For example:
function underscoreString(str) {
var result = str.charAt(0);
for (var i=1; i<str.length; i++) {
result += '_' + str.charAt(i);
}
return result;
}
console.log( underscoreString('this') );
Write a function that will output this:
You will need to write a function that returns another function, so you can chain the functions. Since Javascript allows you to store functions as variables, you can make use of this by re-calling the same function continuously until a proper argument is returned.
The following function is an example. It works as intended but is not the most beautiful.
function l(ch) {
var str = 'l';
if (ch) return str + ch;
else str += '3';
var newFunc = function (ch) {
if (ch) return str + ch;
str += '3';
return newFunc;
}
return newFunc
}
console.log( l('t') === 'lt' );
console.log( l()('t') === 'l3t' );
console.log( l()()('t') === 'l33t' );
console.log( l()()('g') === 'l33g' );
console.log( l()()()()()()()()()()()('t') === 'l33333333333t' );
Why the output is true?
var bar = true;
function foo() {
bar = false;
return 5;
function bar() {}
}
foo();
console.log(bar);
The bar that is within the function foo() is not referencing the global variable bar. Instead, it is referencing the function function bar() {}. This is because of hoisting, as mentioned in the comments.
Thus, the global bar variable is not touched at all by the function, and stays true at all times.
It really depends on the expected level of code. If you need to demonstrate understanding of algorithms or knowledge of how to use javascript constructs.
For example, the first one could be as simple as:
function insertUnderscore(x){
return x.split('').join('_');
}
2nd question a recursive method:
function l( end ){
var acc = '';
function iter( eChar ){
if( typeof eChar === "undefined"){
acc=acc+'3';
return iter;
}
return 'l'+acc+eChar;
}
if(typeof end === "undefined"){
acc = acc + '3';
return iter;
}
return iter(end);
}
Third question:
function bar(){} actually declares 'bar' within the local scope, so your assignment bar = false acts on local 'bar'.
This one simply returns the iterator function if the letter is undefined, When the letter is defined it repeats the character '3' n times.
The other two should be pretty easy to figure out
function l(letter) {
let count = 0
function iter(letter) {
if (typeof letter === 'undefined') {
count++
return iter
} else {
return 'l' + ('3'.repeat(count)) + letter
}
}
return iter(letter)
}
console.log(l('t') === 'lt')
console.log(l()('t') === 'l3t')
console.log(l()()('t') === 'l33t')
console.log(l()()('g') === 'l33g')
console.log(l()()()()()()()()()()()('t') === 'l33333333333t')
Question 1
Use a negative lookahead for the beginning of the string and a positive lookahead for a character. Replace the given empty string with an underscore.
function spacer(s) {
return s.replace(/(?!^.)(?=.)/g, '_');
}
console.log(spacer('this'));
Question 2
Use a closure and return for a non given paramter the function otherwise the extended value.
function l(v) {
var s = 'l';
fn = function (v) {
s += 3;
return v === undefined ? fn : s + v;
};
return v === undefined ? fn : s + v;
}
console.log(l('t') === 'lt');
console.log(l()('t') === 'l3t');
console.log(l()()('t') === 'l33t');
console.log(l()()('g') === 'l33g');
console.log(l()()()()()()()()()()()('t') === 'l33333333333t');
Question 3
Because function bar() {} is hoisted to the begin of the function and then overwritten with false. The outer bar variable has never changed it's content.
var bar = true;
function foo() {
bar = false;
console.log('foo\'s bar:', bar);
return 5;
function bar() {}
}
foo();
console.log(bar);

I have an If statement that is not working, yet is logically correct

if ("tester" == findrange[117])
{
var indict = 34;
}
if (keeperval[39] == "tester")
{
var indict2 = 45;
}
if (keeperval[39] == findrange[117])
{
var indict3 = 56;
}
This code will return when debugging will return these values:
indict = 34
indict2 = 45
indict3 = undefined
Does this make any sense? I just can't wrap my head around why this possibly wouldn't work!
You probably wrapped your strings in findrange[117] and keeperval[39] in String, instead of simply using a literal.
Therefor, both aren't strings, but instead string objects. When you use them in a comparison with strings, it will use the object's .toString(), therefor == "tester" will work.
However, when both sides of an equality comparison are objects, the result will be true if and only if both objects are actually the same:
var s1 = new String("test");
var s2 = new String("test");
console.log(s1 == s2); // logs false
So instead of
findrange[117] = new String("tester");
keeperval[39] = new String("tester");
use
findrange[117] = "tester";
keeperval[39] = "tester";
Even better, exchange your equality tests with type-safe equality tests:
if ("tester" === findrange[117])
{
var indict = 34;
}
if (keeperval[39] === "tester")
{
var indict2 = 45;
}
if (keeperval[39] === findrange[117])
{
var indict3 = 56;
}
Then you will see instantly that there's something off. (fiddle)
For further reference, see MDN's JavaScript guide, especially sameness in JavaScript.
EDIT: If you're not able to change the type of the values in your arrays, use the .toString() method before comparing:
if ("tester" === findrange[117].toString())
{
var indict = 34;
}
if (keeperval[39].toString() === "tester")
{
var indict2 = 45;
}
if (keeperval[39].toString() === findrange[117].toString())
{
var indict3 = 56;
}
use
keeperval[39] === findrange[117]
to understand if both of them are objects or strings.
try groovy console :
def findrange = ["tester","nontester"]
def keeperval = ["tester"]
if ("tester" == findrange[0])
{
def indict = 34;
println indict
}
if (keeperval[0] == "tester")
{
def indict2 = 45;
println indict2
}
if (keeperval[0] == findrange[0])
{
def indict3 = 56;
println indict3
}
output :
34
45
56
First check the type
console.log(typeof(findrange[117]));
In your case this should be an object
In JS,
compare obj to string; will compare obj.value to string value
compare obj to obj; will compare references to the object and not value

Javascript Function to split and return a value from a string

I am trying to grab a certain value. I am new to javascript and I can't figure out why this is not working.
If I parse "kid_2" I should get "kostas". Instead of "Kostas" I always get "02-23-2000". So I must have a logic problem in the loop but I am really stuck.
function getold_val(fieldname,str){
var chunks=str.split("||");
var allchunks = chunks.length-1;
for(k=0;k<allchunks;k++){
var n=str.indexOf(fieldname);
alert(chunks[k]);
if(n>0){
var chunkd=chunks[k].split("::");
alert(chunkd);
return chunkd[1];
}
}
}
var test = getold_val('kid_2','date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||');
alert(test);
A regex may be a little more appealing. Here's a fiddle:
function getValue(source, key){
return (new RegExp("(^|\\|)" + key + "::([^$\\|]+)", "i").exec(source) || {})[2];
}
getValue("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","kid_2");
But if you want something a little more involved, you can parse that string into a dictionary like so (fiddle):
function splitToDictionary(val, fieldDelimiter, valueDelimiter){
var dict = {},
fields = val.split(fieldDelimiter),
kvp;
for (var i = 0; i < fields.length; i++) {
if (fields[i] !== "") {
kvp = fields[i].split(valueDelimiter);
dict[kvp[0]] = kvp[1];
}
}
return dict;
}
var dict = splitToDictionary("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","||","::");
console.log(dict["date_1"]);
console.log(dict["date_2"]);
console.log(dict["kid_1"]);
console.log(dict["kid_2"]);​
This works, here's my fiddle.
function getold_val(fieldname,str) {
var chunks = str.split('||');
for(var i = 0; i < chunks.length-1; i++) {
if(chunks[i].indexOf(fieldname) >= 0) {
return(chunks[i].substring(fieldname.length+2));
}
}
}
alert(getold_val('kid_2', 'date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||'));
The issue with your code was (as #slebetman noticed as well) the fact that a string index can be 0 because it starts exactly in the first letter.
The code is almost the same as yours, I just didn't use the second .split('::') because I felt a .substring(...) would be easier.
There are two bugs. The first error is in the indexOf call:
var n = str.indexOf(fieldname);
This will always return a value greater than or equal to 0 since the field exists in the string. What you should be doing is:
var n = chunks[k].indexOf(fieldname);
The second error is in your if statement. It should be:
if(n >= 0) {
...
}
or
if(n > -1) {
...
}
The substring you are looking for could very well be the at the beginning of the string, in which case its index is 0. indexOf returns -1 if it cannot find what you're looking for.
That being said, here's a better way to do what you're trying to do:
function getold_val(fieldName, str) {
var keyValuePairs = str.split("||");
var returnValue = null;
if(/||$/.match(str)) {
keyValuePairs = keyValuePairs.slice(0, keyValuePairs.length - 1);
}
var found = false;
var i = 0;
while(i < keyValuePairs.length && !found) {
var keyValuePair = keyValuePairs[i].split("::");
var key = keyValuePair[0];
var value = keyValuePair[1];
if(fieldName === key) {
returnValue = value;
found = true;
}
i++;
}
return returnValue;
}

Categories

Resources