Indexes.js – When you need to find certain object properties fast

The result of this article is: indexes.js

Prerequisites: none


As mentioned in my article on component-based game design you sometimes need to find the same certain object properties very often and thus very fast.

The result of this article is the class Indexes.js, and that class helps you do just that.

Usage mockup

var entities = {
	0: {... entity object ...},
	1: {... entity object ...},
	2: {... entity object ...},
	3: {... entity object ...},
	4: {... entity object ...},
// We pass the "indexee" to the constructor
var idx = new JST.Indexes(entities);
// When adding an index we supply a name and a callbackfunction that returns either true or false
idx.add("ai", function(key, value) {
	return typeof !== "undefined";
// We fetch the index like this:
var entitiesWithAiComponent = idx.get("ai");
// And can process them in our gameloop like this:
for (var entityId in entitiesWithAiComponent) {
	var entity = entitiesWithAiComponent[entityId];
	// Update the ai for this entity
// If we add an entity...
entities[5] = someNewEntity;
// ... We can update...
// ... a certain index for a certain item
idx.updateIndexItem("ai", 5);
// ... a certain index (for all items)
// ... a certain item (for all indexes)
// ... all indexes for all items

The result

View the sourcecode on github

Published by

Olof Larsson

Web-developer, Founder of and wannabe indie game developer.