Let $(X, d)$ be a metric space, and let $A, B \subset X$ be two open sets such that $d(A, B) \geq 1$. Suppose we have a function $f$ defined only on $A \cup B$ such that $f|_A \equiv 1$ and $f|_B \equiv -1$. My question is, can we extend $f$ as a Lipschitz function $f : X \to \mathbb{R}$ such that the Lipschitz norm of $f$ is $\leq 2$?
My intuitive guess is that the answer is yes, and $f$ could be defined in terms of some convenient distance function, but I cannot quite put my finger on it. I am also unsure whether $X$ needs to be compact for this to happen. Any help will be appreciated.