Keyframe property diff

by João Vitor Scheuermann

JavaScript

function isEquivalent(a, b) {
    // Create arrays of property names
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    // If number of properties is different,
    // objects are not equivalent
    if (aProps.length !== bProps.length) {
        return false;
    }

    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        // If values of same property are not equal,
        // objects are not equivalent
        if (a[propName] !== b[propName]) {
            return false;
        }
    }

    // If we made it this far, objects
    // are considered equivalent
    return true;
}

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1)
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4()
}

class Keyframe {
  constructor(config) {
    this.id = guid()
    this.time = null
    this.properties = {}

    Object.assign(this, config)
  }
}

let keyframes = [
	new Keyframe({
    time: 0,
    properties: {
      opacity: 0
    }
  }),
  new Keyframe({
    time: 0.1,
    properties: {
      opacity: 1
    }
  })
]

function keyframesDiff (keyframes) {
	keyframes = keyframes.sort((a, b) => a.time - b.time)

	let sequences = new Array
  let currentSequence = new Array
  
  for (let index in keyframes) {
  	index = parseInt(index)
      	
    if (index < keyframes.length - 1) {    	
    	let current = keyframes[index]
      let next = keyframes[index + 1]
      
			if (isEquivalent(current.properties, next.properties)) {
        currentSequence.push(keyframes[index])
        sequences.push(currentSequence)
        currentSequence = new Array
      } else {
        currentSequence.push(keyframes[index])
      }      
    } else {    	
      let current = keyframes[index]
      let previous = keyframes[index - 1]
      
      if (isEquivalent(current.properties, previous.properties)) {
   ...