My solution to a “Daily Coding Problem” that I received in my mail today.

A fixed point in an array is an element whose value is equal to its index. Given a sorted array of distinct elements, return a fixed point, if one exists. Otherwise, return `False`.

For example, given `[-6, 0, 2, 40]`, you should return `2`. Given `[1, 5, 7, 8]`, you should return `False`.

Here’s my solution in Javascript,

``````function indexMatch(arr) {
if(arr == null || arr == undefined) {
return false;
}
for(var i=0; i < arr.length; i++) {
if( i == arr[i]) {
return i;
}
}
return false;
}

module.exports = {
indexMatch: indexMatch
};``````

#### Like the blog? Subscribe for updates

And here’s the corresponding tests for it using JEST

``````const indexMatchModule = require('./indexMatch');

describe("indexMatch function", () => {
test("Testing to see if we get 2 from [-6, 0, 2, 40]", () => {
let harness1 = [-6, 0, 2, 40];
expect(indexMatchModule.indexMatch(harness1)).toBe(2);
});
test("We don't expect to find anything from [1, 5, 7, 8]", () => {
let harness2 = [1, 5, 7, 8];
expect(indexMatchModule.indexMatch(harness2)).toBe(false);
});
test("Doing a null test", () => {
expect(indexMatchModule.indexMatch(null)).toBe(false);
});
test("Doing a undefined test", () => {
expect(indexMatchModule.indexMatch(undefined)).toBe(false);
});
});``````

#### Like the blog? Subscribe for updates

You can find the source code for all this along with the node project on Github.

As usual, if you find any of my posts useful support me by  buying or even trying one of my apps on the App Store.

https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.

Categories: Javascript