Created
February 3, 2025 13:03
-
-
Save erdii/6373c79c99bb036f327647d716468d02 to your computer and use it in GitHub Desktop.
prefix replacement logic draft
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package imageprefix | |
import ( | |
"strings" | |
) | |
type Override struct { | |
From, To string | |
} | |
func Replace(image string, overrides []Override) string { | |
// Find most specific override. | |
bestMatch := mostSpecificIndex(image, overrides) | |
// No match found. Return original string. | |
if bestMatch == -1 { | |
return image | |
} | |
// Return image address with replaced prefix. | |
override := overrides[bestMatch] | |
return override.To + image[len(override.From):] | |
} | |
func mostSpecificIndex(image string, overrides []Override) int { | |
bestMatchLen := 0 | |
bestMatch := -1 | |
for i, override := range overrides { | |
// Skip not matching prefixes. | |
if !strings.HasPrefix(image, override.From) { | |
continue | |
} | |
// Skip if match is not longer than previous best match. | |
if bestMatchLen >= len(override.From) { | |
continue | |
} | |
// This override was the longest match yet. | |
// Store it: | |
bestMatch = i | |
bestMatchLen = len(override.From) | |
} | |
return bestMatch | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment