Logo

Programming-Idioms

History of Idiom 20 > diff from v1 to v2

Edit summary for version 2 by :

Version 1

2015-03-11, 12:19:58

Version 2

2015-03-11, 12:28:13

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Code
function search(m, x) {
	for (var i = 0; i < m.length; i++) {
		for (var j = 0; j < m[i].length; j++) {
			if (m[i][j] == x) {
				return [i, j];
			}
		}
	}
	return false;
}
Code
function search(m, x) {
    for (var i = 0; i < m.length; i++) {
        for (var j = 0; j < m[i].length; j++) {
            if (m[i][j] == x) {
                return [i, j];
            }
        }
    }
    return false;
}
Comments bubble
Return an array.
Comments bubble
Return an array if found, or false if not found.
Demo URL
https://jsfiddle.net/vzw4577n/