Any suggestions on how to make this function more efficient or more generally useful?

Any suggestions on how to make this function more efficient or more generally useful?