Hello, please sign in or register
You are here: Home

Javascript Sort Algorithm

Almost a year ago (when the latest piece of tech was the abacus and debugging was done with a citrusy-vinegar mix) i was given the coding challenge for an interview with a Spanish social networking site (who shall remain nameless). One of the questions was quite a good exercise for the Javascript Array.sort function, which i want to keep+share with you today.

¿Here are a bunch of tickets, sort them with javascript - por favor?

  • From Stockholm, take flight SK22 to New York JFK. Gate 22, seat 7B. Baggage will we automatically transferred from your last leg.
  • Take train 78A from Madrid to Barcelona. Sit in seat 45B.
  • From Gerona Airport, take flight SK455 to Stockholm. Gate 45B, seat 3A. Baggage drop at ticket counter 344.
  • Take the airport bus from Barcelona to Gerona Airport. No seat assignment.
 

Code

var ordertickets = {

	// Stops is an unordered list of stops which need to be sorted... this dwindles as the method is run
	stops : [],
	// the journey contains the ordered list of stops.
	journey : [],

	// Run at start
	// @param string Element Attr(id) Source list
	// @param string Element Attr(id) Target list
	init : function(id, idorderedlist){
		this.journey = [];
		// Get the children from the list who's 
		var listops = document.getElementById(id).children;
		var points = {'to':[],'from':[]};
		// get the stops from the HTML list
		for( var i=0;i<listops.length;i++){
			this.stops.push( listops[i].innerHTML );
			// get the first and last positions. These are only mentioned once.
			var res;
			if( res = listops[i].innerHTML.match(/[fF]rom\s*([A-Z]\w+).*?[tT]o\s*([A-Z]\w+)/) ){
				// add name to array
				points['from'].push(res[1]);
				points['to'].push(res[2]);
			};
		}
		// Get the unique points
		points = this.uniquepoints(points);
		
		// Sort and order the list
		this.sort(points);

		// clear ordered list
		document.getElementById(idorderedlist).innerHTML = '';

		// create the ordered list and append it
		this.createorderedlist(idorderedlist);
	},
	
	// Sort the journey
	// @param object {'from':string, 'to':string}
	
	sort : function(points){
	
		this.journey = this.stops.sort(function(a,b){
			// get from
			var regf = /[fF]rom\s+([A-Z]\w+)/,
				regt = /[tT]o\s+([A-Z]\w+)/,
				a_from = a.match(regf)[1],
				a_to = a.match(regt)[1],
				b_from = b.match(regf)[1],
				b_to = b.match(regt)[1];
	
			if( a_to === b_from )
				r = -1;
			else if( a_from === b_to )
				r = 1;
			else if( a_from === points.from )
				r = -1;
			else if( a_to === points.to )
				r = 1;
			
			//console.log([a_from, a_to, b_from, b_to, r]);
	
			return r;
		});
	},
	
	
	// From two arrays get the array_diff of the names and for each array return the single unique value.
	// @param object {'from':array, 'to':array}
	
	uniquepoints : function(points){
		// filter arrays to find the unique starting and ending points.
		for(var i=0; i<points['from'].length;i++ )
			for(var j=0; j<points['to'].length;j++ )
				if( points['to'][j] === points['from'][i] ){
					points['to'].splice(j,1);
					points['from'].splice(i,1);
					i--;
					j--;
				}

		return {'to':points['to'][0], 'from':points['from'][0]};
	},
	
	// create an ordered list from the values given
	// @param string Element attr(id=)
	createorderedlist : function(id){
		// populate the ordered list
		for( x in this.journey ){
			document.getElementById(id).innerHTML += '<li>'+this.journey[x]+'</li>';
		}
	}
}

It worked... but they gave the job to someone else, Estoy muy triste !

Comments

cmoutlet
vs ralph lauren outlet Ray Ban Sunglasses,Ray Ban Outlet,Ray Ban Sale,Cheap Ray Bans,Cheap Ray Ban Sunglasses,ray ban sunglasses outlet,ray ban,ray...
Created 21/10/15
oakleysunglasses
“I canada goose outlet think it doesn’t swarovski jewelry bode very
Created 21/01/16
linpingping
The michael--kors.org.uk next ralph lauren outlet day patriots jersey Mrs
Created 01/03/16
clibin
Tyrion 5c cases watched her ray ban sunglasses read. His timber...
Created 18/04/16
chenyan
Bond grinned. pandora-bracciali.it "We bcbgmax.in.net only chaussure...
Created 15/06/16
chenyan
Bond grinned. pandora-bracciali.it "We bcbgmax.in.net only chaussure...
Created 15/06/16
chenyan
Bond grinned. pandora-bracciali.it "We bcbgmax.in.net only chaussure...
Created 15/06/16
chenyan
Bond grinned. pandora-bracciali.it "We bcbgmax.in.net only chaussure...
Created 15/06/16
wlp
The oakley sunglasses cheap wreck, cheap nfl jerseys even replic...
Created 14/11/16
leilei3915
20170408 leilei3915 kate spade outlet coach facto...
Created 08/04/17
michael kors factory outlet
adidas nmd pandora bracelet
Created 16/05/17
wanglili
air jordan retro coach outlet online coach outlet...
Created 21/08/17
Title*
Comment

Prove you are not a robot

To prove you are not a robot, please type in the six character code you see in the picture below
Security confirmation codeI can't see this!
Contact
Name*
Email never shown*
Home Page

Author

Andrew Dodson
Since:Feb 2007

Comment | flag

Categories

Bookmark and Share