Skip to content
This repository has been archived by the owner on May 25, 2021. It is now read-only.

Smart 404 page? #75

Open
Explosion-Scratch opened this issue Nov 29, 2020 · 1 comment
Open

Smart 404 page? #75

Explosion-Scratch opened this issue Nov 29, 2020 · 1 comment
Labels
enhancement New feature or request

Comments

@Explosion-Scratch
Copy link
Contributor

I thought of this idea and implemented it on my own site, basically whenever the user encounters a 404 page, instead of just giving a 404 message it provides or even redirects to the likely correct url. First it compares the distance between window.location.pathname and each of the correct paths on the website and returns the closest one. This uses the edit distance between them, using this snippet:

function distance(s1, s2) {
		s1 = s1.toLowerCase(); // Case doesn't matter in url's
		s2 = s2.toLowerCase();

		var costs = new Array();
		for (var i = 0; i <= s1.length; i++) {
			var lastValue = i;
			for (var j = 0; j <= s2.length; j++) {
				if (i == 0) costs[j] = j;
				else {
					if (j > 0) {
						var newValue = costs[j - 1];
						if (s1.charAt(i - 1) != s2.charAt(j - 1))
							newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
						costs[j - 1] = lastValue;
						lastValue = newValue;
					}
				}
			}
			if (i > 0) costs[s2.length] = lastValue;
		}
		return costs[s2.length];
	}

Then, to get the closest url I do this:

function closest(str) {
		var urls = ['index', 'blog', 'projects']; //Correct url's
		urls.sort((a, b) => editDistance(a, str) - editDistance(str, b));
		return urls[0];
	}

Now I can check how close these are, if they're 1 or 2 letters different than it's likely that the user meant that url:

// url = window.location.pathname
if(editDistance(closest(url), url) < 3) {
    window.location.href = `http://example.com/${closest(url)}`;
  }

Either way this makes an amazing user experience on any website and we should definitely do this on Scratch Addons.

(Also you can try it here or for no redirect here )

@Explosion-Scratch Explosion-Scratch linked a pull request Nov 29, 2020 that will close this issue
@Hans5958 Hans5958 added the enhancement New feature or request label Nov 30, 2020
@lightningmc09

This comment has been minimized.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants