negate boolean function in javascript - javascript

How to negate a boolean function?
Such that using something like:
_.filter = function(collection, test) {
var tmp = []
_.each(collection, function(value){
if (test(value)) {
tmp.push(value);
}
})
return tmp
};
var bag = [1,2,3];
var evens = function(v) { return v % 2 === 0};
This is wrong:
// So that it returns the opposite of evens
var result = _.filter(bag, !evens);
result:
[1,3]

Underscore has a .negate() API for this:
_.filter(bag, _.negate(evens));
You could of course stash that as its own predicate:
var odds = _.negate(evens);
then
_.filter(bag, odds);

Try making a function that returns a function:
function negate(other) {
return function(v) {return !other(v)};
};
Used like this:
var result = _.filter(bag, negate(evens));
Or just declare a function when you call it:
var result = _.filter(bag, function(v) {return evens(v)});

Related

Mapping string with key-value pair to object

Given the following string with key-value pairs, how would you write a generic function to map it to an object?
At the moment, I am just splitting by : and ; to get the relevant data, but it doesn't seem like a clean approach.
This my code at the moment:
var pd = `id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74`;
var tempPd = pd.split(';');
for (i = 1; i < tempPd.length; i++) {
var b = tempPd[i].split(':');
console.log(b[1]);
}
What about using reduce:
function objectify(str) {
return str.split(";").reduce(function (obj, item) {
var a = item.split(":");
obj[a[0]] = a[1];
return obj;
}, {});
}
var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74";
console.log(objectify(strObj));
or:
function objectify(str){
return str.split(";").reduce((obj,item)=>{
var a = item.split(":");
obj[a[0]]=a[1];
return obj;
},{});
}
var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74";
console.log(objectify(strObj));

Calling functions insight function / arguments

I am trying to write a function that takes functions as arguments (as many as it gets) and returns them. The function funcArg should return 'Called me'. I used Array.prototype.slice.call(arguments); to create an array but I don't know how to call die functions in that array. Any ideas? Thanks!!
var caller = function() {
return "Called ";
};
var adder = function() {
return " me";
};
var funcArgs = function() {
var myArray = Array.prototype.slice.call(arguments);
}
funcArgs(caller);
funcArgs(calleradder);
You can do this using reduce.
var funcArgs = function() {
var functions = Array.prototype.slice.call(arguments);
return functions.reduce(function(total, f) {
return total + f();
}, '');
};
The way this works if you start off with an array of functions. We then go through each function one at a time. We then call that function and append it to the result of the previous function. Breaking this down into simpler code would look like this:
var funcArgs = function() {
var functions = [caller, adder];
var result = '';
result += functions[0](); // caller();
result += functions[1](); // adder();
return result;
};
If you have an array of functions you can loop over them with forEach.
var caller = function() {
return "Called "
}
var adder = function() {
return " me"
}
var funcArgs = function() {
var myArray = Array.prototype.slice.call(arguments);
myArray.forEach(function (fn) {
console.log(fn())
})
}
funcArgs(caller, adder); // "Called me"
If you want to actually return the values, rather than just console.log them, you can use reduce to return the strings concatenated (or whatever else)
var funcArgs = function() {
var myArray = Array.prototype.slice.call(arguments);
return myArray.reduce(function (acc, fn) {
return acc + fn()
}, '')
}

Get function parameter names without calling the function?

I know I can get the String representation of a function without calling it like this
function storeData(id, data) { console.log("Doing stuff..") };
storeData.toString(); //"function storeData(id, data) { console.log("Doing stuff..") }"
And I could in theory parse the resulting String to pull out the variable names. Any takers on writing that code? Is there an easier way? (I don't need to worry about minification)
try to use the following code:
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
var fnStr = func.toString().replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
if (result === null)
result = [];
return result;
}
getParamNames(getParamNames) // returns ['func']
getParamNames(function (a, b, c, d) { }) // returns ['a','b','c','d']
getParamNames(function (a,/*b,c,*/d) { }) // returns ['a','d']
getParamNames(function () { }) // returns []

Creating recursive list of objects

I want to create a function in Javascript which takes an array as argument and returns a list of objects. I have an array like this:
var arr= [10,20,30];
console.log(listFunction(arr));
The result should look like this:
{'val':10, 'restList':{'val':20, 'restList':{'val':30,'restList':'null'}}}
I have tried the forEach() function:
function listFunction(parentArr) {
var listOfObjects = [];
parentArr.forEach(function (entry, thisArg) {
var singleObj = {}
singleObj['val'] = entry;
singleObj['restList'] = singleObj;
listOfObjects[thisArg] = singleObj;
});
return listOfObjects;
};
You need to use a recursive function:
function listFunction(arr){
if(arr.length == 0){
return null;
}else{
return {val: arr[0], restList: listFunction(arr.slice(1,arr.length))};
}
}
This is the Lisp-style recursive list algorithm.
var recursiveList = function (array) {
return recursiveListHelper(arr, {});
};
var recursiveListHelper = function (array, obj) {
if (array.length === 0) //stopping condition
return null;
var car = array[0]; //current element
var cdr = array.slice(1); //rest of list
obj = {val: car};
obj.restList = recursiveListHelper(cdr, obj);
return obj;
};
You mentioned that you wanted to avoid using Array.slice. This solution uses array indexing instead of splitting into subarrays.
var recursiveIndexed = function (array) {
return recursiveIndexedHelper(array, {}, 0);
};
var recursiveIndexedHelper = function (array, obj, index) {
if (index == array.length)
return null;
var car = array[index];
obj = {val: car };
obj.restList = recursiveIndexedHelper(array, obj, index + 1);
return obj;
};
A plunker as example.

How to remove array objects having property

What is the easiest way to remove all objects from an array with a particular property = x?
Use _.filter
var result = _.filter(arr, function(item) {
return !("prop" in item);
});
If you want to limit it to the immediate properties of each item, use
var result = _.filter(arr, function(item) {
return !item.hasOwnProperty("prop");
});
It seems like the easiest way would be to use the filter method:
var newArray = _.filter(oldArray, function(x) { return !('prop' in x); });
// or
var newArray = _.filter(oldArray, function(x) { return !_.has(x, 'prop'); });
Or alternatively, the reject method should work just as well:
var newArray = _.reject(oldArray, function(x) { return 'prop' in x; });
// or
var newArray = _.reject(oldArray, function(x) { return _.has(x, 'prop'); });
Update Given your updated question, the code should look like this:
var newArray = _.filter(oldArray, function(x) { return x.property !== 'value'; });
Or like this
var newArray = _.reject(oldArray, function(x) { return x.property === 'value'; });

Categories