When there is a single dimension array, it is easy to check whether it is defined, by either simple calling arr[6] which will return undefined if such property does not exist or calling typeof arr[6] === undefined.
The problem is, that in my case I have arr[5][1][6][2][5][3][7], where arr[5] can be non existent, or arr[5][1], etc. Which will naturally trigger error: TypeError: Cannot read property [..] One solution is to write many IF statements. However, is there any better solution, that'd simple allow me to check whether arr[5][1][6][2][5][3][7] is defined?
I can't think of anything better than:
var defined = false;
try {
defined = !!arr[5][1][6][2][5][3][7]
} catch(e)
{
// nothing
}
But seriously bad design.
Since this seemed like an interesting problem, I wrote this function to solve it in a nice an non-exceptional way :)
var deepCheck = function(arr, indexes) {
var level = arr;
while(indexes.length) {
var v = indexes.shift()
if(!level[v]) {
return false;
}
level = level[v];
}
return true;
};
Now say you have this:
arr[foo][bar][baz];
You would check it using...
deepCheck(arr, [foo, bar, baz]);
Maybe I should point out that I do kind of agree that if you indeed have very very long arrays like that, it does sound like a design issue.
By using a try/catch block you can check if the element can be accessed.
var x;
try {
x = arr[5][1][6][2][5][3][7];
} catch(TypeError)
{
// the element cannot be accessed
x = undefined;
}
Then it's easy enough to check if 'x' is defined or not using an if statement.
A pragmatic approach would be to break this problem down into its component parts; look at what data is known and the tools you have at hand.
So, what do we know - well we know the keys that we want to inspect, in the case of checking if arr[5][1][6][2][5][3][7] is defined. Now ask yourself, what tools do we have in JavaScript? To check if an Array index is defined we can compare against null, ie:
if (array[index] === null) {
return false
}
If we were to try and write this code, one of the first things that should come to mind is to simply walk through each key, in order: eg:
if (array[5] === null) {
return false;
} else if (array[5][1] === null) {
return false
} ...snip...
// Good news, it's defined!
return true
Obviously this approach can be improved, it requires a tonne of duplicated code to be written out, it's inflexible and not reusable. If you ever find yourself doing the same thing over and over, you probably have a good candidate for a loop construct. In order for a loop you need a variant, something that will change with each repetition - in the example above the variant is the right most element of the nested array we are inspecting. First, let's start by listing our variants out:
var variants = [ 5, 1, 6, 2, 5, 3, 7 ];
for (var i = 0; i < variants.length; i++) {
console.log("variant: " + variants[i]);
}
Where, do we go from here? Well things get a bit harder, you need to understand how Arrays are passed by reference in JavaScript and exploit that in the loop body; ultimately you may end up with something like this:
function arrayDimensionsExist(source, dimensions) {
var currentDepth = source;
for (var i = 0; i < dimensions.length; i++) {
var key = dimensions[i];
if (currentDepth[key] === null) {
return false;
} else {
currentDepth = source[key];
}
}
return true;
}
Put the code accessing it between try and catch. If it works, it works, if not you get a nice exception and you can react accordingly.
As a side note, I shudder to think of what prompted you to design your system like that...
There's no solution built-in to the language, but you could handle it with a function like this:
var verifyIndexes = function(target) {
var current = target;
for (i = 1; i < arguments.length; i++) {
if (arguments[i] in current) {
current = current[arguments[i]];
} else {
return false;
}
}
return true;
}
var myArray = [[[1, 2, 3], 4], 5];
console.log(verifyIndexes(myArray, 0)); // true
console.log(verifyIndexes(myArray, 0, 0, 0)); // true
console.log(verifyIndexes(myArray, 0, 0, 3)); // false
console.log(verifyIndexes(myArray, 0, 1)); // true
console.log(verifyIndexes(myArray, 0, 2)); // false
Related
I have a general question which is about whether it is possible to make zero-allocation iterators in Javascript. Note that by "iterator" I am not married to the current definition of iterator in ECMAScript, but just a general pattern for iterating over user-defined ranges.
To make the problem concrete, say I have a list like [5, 5, 5, 2, 2, 1, 1, 1, 1] and I want to group adjacent repetitions together, and process it into a form which is more like [5, 3], [2, 2], [1, 4]. I then want to access each of these pairs inside a loop, something like "for each pair in grouped(array), do something with pair". Furthermore, I want to reuse this grouping algorithm in many places, and crucially, in some really hot inner loops (think millions of loops per second).
Question: Is there an iteration pattern to accomplish this which has zero overhead, as if I hand-wrote the loop myself?
Here are the things I've tried so far. Let's suppose for concreteness that I am trying to compute the sum of all pairs. (To be clear I am not looking for alternative ways of writing this code, I am looking for an abstraction pattern: the code is just here to provide a concrete example.)
Inlining the grouping code by hand. This method performs the best, but obscures the intent of the computation. Furthermore, inlining by hand is error-prone and annoying.
function sumPairs(array) {
let sum = 0
for (let i = 0; i != array.length; ) {
let elem = array[i++], count = 1
while (i < array.length && array[i] == elem) { i++; count++; }
// Here we can actually use the pair (elem, count)
sum += elem + count
}
return sum
}
Using a visitor pattern. We can write a reduceGroups function which will call a given visitor(acc, elem, count) for each pair (elem, count), similar to the usual Array.reduce method. With that our computation becomes somewhat clearer to read.
function sumPairsVisitor(array) {
return reduceGroups(array, (sofar, elem, count) => sofar + elem + count, 0)
}
Unfortunately, Firefox in particular still allocates when running this function, unless the closure definition is manually moved outside the function. Furthermore, we lose the ability to use control structures like break unless we complicate the interface a lot.
Writing a custom iterator. We can make a custom "iterator" (not an ES6 iterator) which exposes elem and count properties, an empty property indicating that there are no more pairs remaining, and a next() method which updates elem and count to the next pair. The consuming code looks like this:
function sumPairsIterator(array) {
let sum = 0
for (let iter = new GroupIter(array); !iter.empty; iter.next())
sum += iter.elem + iter.count
return sum
}
I find this code the easiest to read, and it seems to me that it should be the fastest method of abstraction. (In the best possible case, scalar replacement could completely collapse the iterator definition into the function. In the second best case, it should be clear that the iterator does not escape the for loop, so it can be stack-allocated). Unfortunately, both Chrome and Firefox seem to allocate here.
Of the approaches above, the custom-defined iterator performs quite well in most cases, except when you really need to put the pedal to the metal in a hot inner loop, at which point the GC pressure becomes apparent.
I would also be ok with a Javascript post-processor (the Google Closure Compiler perhaps?) which is able to accomplish this.
Check this out. I've not tested its performance but it should be good.
(+) (mostly) compatible to ES6 iterators.
(-) sacrificed ...GroupingIterator.from(arr) in order to not create a (imo. garbage) value-object. That's the mostly in the point above.
afaik, the primary use case for this is a for..of loop anyways.
(+) no objects created (GC)
(+) object pooling for the iterators; (again GC)
(+) compatible with controll-structures like break
class GroupingIterator {
/* object pooling */
static from(array) {
const instance = GroupingIterator._pool || new GroupingIterator();
GroupingIterator._pool = instance._pool;
instance._pool = null;
instance.array = array;
instance.done = false;
return instance;
}
static _pool = null;
_pool = null;
/* state and value / payload */
array = null;
element = null;
index = 0;
count = 0;
/* IteratorResult interface */
value = this;
done = true;
/* Iterator interface */
next() {
const array = this.array;
let index = this.index += this.count;
if (!array || index >= array.length) {
return this.return();
}
const element = this.element = array[index];
while (++index < array.length) {
if (array[index] !== element) break;
}
this.count = index - this.index;
return this;
}
return() {
this.done = true;
// cleanup
this.element = this.array = null;
this.count = this.index = 0;
// return iterator to pool
this._pool = GroupingIterator._pool;
return GroupingIterator._pool = this;
}
/* Iterable interface */
[Symbol.iterator]() {
return this;
}
}
var arr = [5, 5, 5, 2, 2, 1, 1, 1, 1];
for (const item of GroupingIterator.from(arr)) {
console.log("element", item.element, "index", item.index, "count", item.count);
}
Here, I am trying to write a code that takes a list of integers as a parameter and searches for the value 7. The function will return a boolean value representing true if 7 is in the list and false if it is not. This is what I have tried so far:
Could it be something with my else statement? Do I end it too soon? Or not soon enough?
You can simply use an array and use includes as per ECMA2016 like below:
if([2,5,7].includes(value)) {
return true;
}
return false;
or with list
var flag = false;
for(var i=0; i<arguments.length; i++)
{ if(arguments[i] == this) { flag = true; break; }}
return flag;
Javascript already has a function to do this. Array.prototype.includes(). You use it like this:
const containsSeven = list.includes(7)
If you are looking for something more complicated, like whether an item is an object and contains a particular key value pair for example, you can use Array.prototype.some()
Your declaration of the if statement is wrong. The else tag is on the wrong line. If you use else, it should come after the if-block.
But moving the else-block up, won't fix your function, because it will only return true if the first element in your array is a 7.
There are many good ways to do it, such as using higher order functions, but as it seems you are new to the language.
EDIT: Therefore, I would suggest one of the two simple ways below:
1) You could store the number of 7s found in the array in a for loop. Afterwards return false if the number of 7s is 0 or true if it the number is higher than 0
2) Another, much quicker way would be to return true in the for-loop when you encounter a 7 and after the for-loop just return false. Because a return statement exits the scope - which is your function - not only the for-loop would come to an end but also your function would return true much earlier.
For the second option, your function would look like this:
function find_value(list) {
for (let i = 0; i < list.length; i++) {
if(list[i] == 7) {
return true
}
}
return false
}
You can coerces to boolean the result of Array.prototype.find() which returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
Code:
const list1 = [4, 5, 6, 7, 8];
const list2 = [1, 2, 3, 4, 5];
const findTheNumber = (arr, num) => !!arr.find(n => n === num);
console.log(findTheNumber(list1, 7));
console.log(findTheNumber(list2, 7));
Try this way
function search(list , value){ // Value = 7;
return true ? list.indexOf(value) > -1 : false
}
I need to execute both sides of an && statement, but this won't happen if the first part returns false. Example:
function doSomething(x) {
console.log(x);
}
function checkSomething(x) {
var not1 = x !== 1;
if (not1) doSomething(x);
return not1;
}
function checkAll() {
return checkSomething(1)
&& checkSomething(3)
&& checkSomething(6)
}
var allValid = checkAll(); // Logs nothing, returns false
The problem here is that doSomething(x) should log 3 and 6, but because checkSomething(1) returns false, the other checks won't be called. What is the easiest way to run all the checks and return the result?
I know I could save all the values in variables and check those subsequently, but that does not look very clean when I have a lot of checks. I am looking for alternatives.
Use a single &. That is a bitwise operator. It will execute all conditions and then return a bitwise sum of the results.
function checkAll() {
return checkSomething(1)
& checkSomething(2)
& checkSomething(3)
}
You can multiply the comparison result and cast it to boolean.
function checkSomething(x) {
var not1 = x !== 1;
if (not1) alert(x);
return not1;
}
function checkAll() {
return !!(checkSomething(1) * checkSomething(2) * checkSomething(3));
}
document.write(checkAll());
Or take some array method:
function checkAll() {
return [checkSomething(2), checkSomething(2), checkSomething(3)].every(Boolean);
}
Coming back to my own question 2,5 years later I can agree with the people in the comments on how bad this code is by being based on side effects and therefore violating the single responsibility principle.
I just want to provide a proper solution for people visiting this page with the same question.
function doSomething(x) {
console.log(x);
}
function checkSomething(x) {
return x !== 1;
}
var values = [1, 3, 6];
var validValues = values.filter(checkSomething); // -> [3, 6]
validValues.forEach(doSomething); // -> Logs 3 and 6
var allValid = validValues.length === values.length; // false
As you can see, the checkSomething function now only does one thing: check something. The doSomething logic runs separately after all the checks are done.
A function should always either do something or return something, not both. Of course there are exceptions to this, but it is a good rule of thumb. This makes the code more predictable, testable and understandable.
Now, if at some point I want to check if all values are valid without "doing something", I can actually do this...
var allValid = checkSomething(1) && checkSomething(3) && checkSomething(6);
...without having to worry about side effects.
Conclusion: You don't want to avoid short circuited evaluation
I have an array of objects. Each object has a unique userTestrId. Here is the code that I am using when I want to delete one of the objects. Is this the most efficient way I can perform the delete? What I am concerned with is once a row has been deleted the code will still go all the way through the array even though there is no chance of another entry:
var id = 99;
self.tests.forEach(function (elem, index) {
if (elem['userTestId'] === id)
self.tests.splice(index, 1);
});
}
var id = 99;
self.tests.some(function (elem, index) {
if (elem['userTestId'] === id)
self.tests.splice(index, 1);
return true;
});
return false;
}
Could utilise Array.some? Stops looping once you return TRUE from a callback.
This is an alternative to #benhowdle89's answer.
Use Array.prototype.every
The .every method is used to iterate over an array and check whether each and every element passes a test or not. If the callback returns false for any single element, the loop breaks.
Take the following example:
var odds = [3, 5, 7, 9, 11, 12, 17, 19];
//an array with all odd numbers except one
var checkEven = function (n, i, arr) {
console.log ("Checking number ", n);
if (n%2===0) {
arr.splice(i, 1);
return false;
}
return true;
}
console.log(odds.every(checkEven), odds);
If you run the above and look at the console, the loop executed till number 12 only, where it spliced, and stopped.
You can employ similar logic in your code very easily :)
var id = 99;
self.tests.some(function (elem, index) {
if (elem['userTestId'] === id)
self.tests.splice(index, 1);
return true;
});
return false;
}
Polyfill :
some was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of some in implementations which do not natively support it.
// Production steps of ECMA-262, Edition 5, 15.4.4.17
// Reference: http://es5.github.io/#x15.4.4.17
if (!Array.prototype.some) {
Array.prototype.some = function(fun /*, thisArg*/) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.some called on null or undefined');
}
if (typeof fun !== 'function') {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t && fun.call(thisArg, t[i], i, t)) {
return true;
}
}
return false;
};
}
see in detail
While your concern is technically correct, it's unlikely to be an actual problem(Javascript is fast, this is a microoptimization).
What you should do is focus on using the appropriate interface, so your code could be easy to read and understand. .forEach() does not tell you what you want to do, unless you really do want to do something with each element of the array.
Lodash has the .remove() function, which removes all elements matching a predicate. Unfortunately, I couldn't find the exact specific function you wanted in JS's standard library or in lodash, so you would have to write your own wrapper:
var id = 99
removeFirst(tests, function (elem) { return elem.userTestId === id })
function removeFirst(array, callback) {
var index = array.findIndex(callback)
array.splice(index, 1)
}
Having noted that, you should avoid using an array at all - splicing is way more expensive than looping the whole array to begin with! Instead, since you have a unique identifier, you could use a map:
var map = {}
tests.forEach(function mapper(elem) {
map[elem.userTestId] = elem
})
Now, your removal function is simply delete map[id].
Yes, I know you could use regular objects as associative arrays in JavaScript, but I'd like to use something closer to java's Map's implementation (HashMap, LinkedHashMap etc). Something that could have any kind of data used as key. Are there any good hash(code/table) in JavaScript implementation out there?
In javascript, objects are literally a hash implementation. A Java HashMap will be a little bit of a fake-out, so I'd challenge you to re-think your needs.
The straight answer is no, I don't believe that there is a great implementation of Java's HashMap in javascript. If there is, it's bound to be part of a library that you may or may not want to use, and you certainly don't need to include a library just to have a little hash table.
So let's go ahead and write one, just to examine the problem. You can use it if you like. We'll just start by writing a constructor, and we'll piggyback off of Array, which is Object, but has some useful methods that will keep this example from getting too tedious:
function HashMap () {
var obj = [];
return obj;
}
var myHashMap = HashMap();
We'll add some methods straight from the world of Java, but translate into javascript as we go...
function HashMap() {
var obj = [];
obj.size = function () {
return this.length;
};
obj.isEmpty = function () {
return this.length === 0;
};
obj.containsKey = function (key) {
for (var i = 0; i < this.length; i++) {
if (this[i].key === key) {
return i;
}
}
return -1;
};
obj.get = function (key) {
var index = this.containsKey(key);
if (index > -1) {
return this[index].value;
}
};
obj.put = function (key, value) {
if (this.containsKey(key) !== -1) {
return this.get(key);
}
this.push({'key': key, 'value': value});
};
obj.clear = function () {
this = null; // Just kidding...
};
return obj;
}
We could continue to build it out, but I think it's the wrong approach. At the end of the day, we end up using what javascript provides behind the scenes, because we just simply don't have the HashMap type. In the process of pretending, it lends itself to all kinds of extra work.
It's a bit ironic that one of the things that makes javascript such an interesting and diverse language is the ease with which it handles this kind of wrestling. We can literally do anything we'd like, and the quick example here does nothing if it doesn't illustrate the deceptive power of the language. Yet given that power, it seems best not to use it.
I just think javascript wants to be lighter. My personal recommendation is that you re-examine the problem before you try implement a proper Java HashMap. Javascript neither wants nor affords for one.
Remember the native alternative:
var map = [{}, 'string', 4, {}];
..so fast and easy by comparison.
On the other hand, I don't believe that there are any hard-and-fast answers here. This implementation really may be a perfectly acceptable solution. If you feel you can use it, I'd say give it a whirl. But I'd never use it if I felt that we have reasonably simpler and more natural means at our disposal.. which I'm almost certain that we do.
Sidenote:
Is efficiency related to style? Notice the performance hit.. there's a big O staring us in the face at HashMap.put()... The less-than-optimal performance probably isn't a show-stopper here, and you'd probably need to be doing something very ambitious or have a large set of data before you'd even notice a performance hickup a modern browser. It's just interesting to note that operations tend to become less efficient when you're working against the grain, almost as if there is a natural entropy at work. Javascript is a high level language, and should offer efficient solutions when we keep in line with its conventions, just as a HashMap in Java will be a much more natural and high performing choice.
I have released a standalone JavaScript hash table implementation that goes further than those listed here.
http://www.timdown.co.uk/jshashtable/
Note that java collections using "any kind of object" as a key isn't quite right. Yes, you can use any object, but unless that object has good hashcode() and equals() implementations then it won't work well. The base Object class has a default implementation for these, but for custom classes to work (effectively) as hashtable keys you need to override them. Javascript has no equivalent (that I know of).
To create a hashtable in javascript that can (effectively) use arbitrary objects as the key you'd need to enforce something similar on the objects you use, at least if you want to keep the performance gains of a hashtable. If you can enforce a 'hashcode()' method that returns a String, then you can just use an Object under the hood as the actual hashtable.
Otherwise, you'd need to so something like the other solutions posted, which as of right now do not perform like hashtables. They both do O(n) searches over the list to try and find the key, which pretty much defeats the purpose of a hashtable (hashtables are generally constant time for get/put).
Here's a naive implementation I just put together - as keparo mentioned in a comment, one of the big issues is equality checking:
var ObjectMap = function()
{
this._keys = [];
this._values = [];
};
ObjectMap.prototype.clear = function()
{
this._keys = [];
this._values = [];
};
ObjectMap.prototype.get = function(key)
{
var index = this._indexOf(key, this._keys);
if (index != -1)
{
return this._values[index];
}
return undefined;
};
ObjectMap.prototype.hasKey = function(key)
{
return (this._indexOf(key, this._keys) != -1);
};
ObjectMap.prototype.hasValue = function(value)
{
return (this._indexOf(value, this._values) != -1);
};
ObjectMap.prototype.put = function(key, value)
{
var index = this._indexOf(key, this._keys);
if (index == -1)
{
index = this._keys.length;
}
this._keys[index] = key;
this._values[index] = value;
};
ObjectMap.prototype.remove = function(key)
{
var index = this._indexOf(key, this._keys);
if (index != -1)
{
this._keys.splice(index, 1);
this._values.splice(index, 1);
}
};
ObjectMap.prototype.size = function()
{
return this._keys.length;
};
ObjectMap.prototype._indexOf = function(item, list)
{
for (var i = 0, l = list.length; i < l; i++)
{
if (this._equals(list[i], item))
{
return i;
}
}
return -1;
};
ObjectMap.prototype._equals = function(a, b)
{
if (a === b)
{
return true;
}
// Custom objects can implement an equals method
if (typeof a.equals == "function" &&
typeof b.equals == "function")
{
return a.equals(b);
}
// Arrays are equal if they're the same length and their contents are equal
if (a instanceof Array && b instanceof Array)
{
if (a.length != b.length)
{
return false;
}
for (var i = 0, l = a.length; i < l; i++)
{
if (!this._equals(a[i], b[i]))
{
return false;
}
}
return true;
}
// Checking object properties - objects are equal if they have all the same
// properties and they're all equal.
var seenProperties = {};
for (var prop in a)
{
if (a.hasOwnProperty(prop))
{
if (!b.hasOwnProperty(prop))
{
return false;
}
if (!this._equals(a[prop], b[prop]))
{
return false;
}
seenProperties[prop] = true;
}
}
for (var prop in b)
{
if (!(prop in seenProperties) && b.hasOwnProperty(prop))
{
if (!a.hasOwnProperty(prop))
{
return false;
}
if (!this._equals(b[prop], a[prop]))
{
return false;
}
}
}
return true;
};
Example usage:
>>> var map = new ObjectMap();
>>> var o = {a: 1, b: [1,2], c: true};
>>> map.put(o, "buns");
>>> map.get(o)
"buns"
>>> map.get({a: 1, b: [1,2], c: true});
"buns"
>>> map.get({a: 1, b: [1,2], c: true, d:"hi"});
>>> var a = [1,2,3];
>>> map.put(a, "cheese");
>>> map.get(a);
"cheese"
>>> map.get([1,2,3]);
"cheese"
>>> map.get([1,2,3,4]);
>>> var d = new Date();
>>> map.put(d, "toast");
>>> map.get(d);
"toast"
>>> map.get(new Date(d.valueOf()));
"toast"
This is in no way a complete implementation, just a pointer for a way to implement such an object. For example, looking at what I've given, you would also need to add constructor property checks before the object property check, as this currently works:
>>> function TestObject(a) { this.a = a; };
>>> var t = new TestObject("sandwich");
>>> map.put(t, "butter");
>>> map.get({a: "sandwich"})
"butter"