Port of CGGeometry from C to JS; with some helper functions