Done with one slight tweak. The function will return undefined rather than null when the ranges are disjointed.