css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div id='app'>
  <h1>Immutable Data from Scratch</h1>
  <h3><a href='http://ryanfunduk.com/articles/immutable-data-from-scratch'>ryanfunduk.com/articles/immutable-data-from-scratch</a></h3>
  <div id='mount'></div>
  <button onClick='test(); return false;'>Run Immutable Tests</button>
  <ul id='test'></ul>
</div>

            
          
!
            
              #app { padding: 20px; font-family: sans-serif; }
h1, h3 { margin: 0; }
a { color: #aaa; }
a:hover { color: #999; }

#mount form { margin-top: 20px; }
#mount input { font-size: 20px; padding: 2px 4px; }
#mount ul { padding: 0; margin: 20px 0; list-style: none outside; }
#mount li { padding: 4px 8px; line-height: 20px; }
#mount span.toggle { font-weight: bold; color: #BBB; cursor: pointer; text-align: center; display: inline-block; width: 20px; height: 20px; margin-right: 6px; }
#mount span.toggle:hover { color: black; }
#mount a { color: #aaa; }
#mount a:hover { color: #999; }
#mount a.remove { margin-left: 10px; font-size: 12px; }
#mount a.remove:hover { color: #BB0000; }


ul#test {
  padding: 0;
  list-style: none outside;
}
ul#test li {
  font-family: monospace;
  font-size: 16px;
  white-space: pre-wrap;
  line-height: 22px;
  color: #111;
  padding: 1px 4px;
}
ul#test li small strong { font-size: 16px; }
ul#test li.pass { background-color: lightgreen; }
ul#test li.fail { background-color: lightcoral; }
ul#test li.info { background-color: lightblue; }
            
          
!
            
              'use strict' // we'll get TypeError trying to modify immutable objects

// run some tests for immutable()
// test()

// we need a new TodoStore that uses immutable data
// instead of just a plain object
var TodoStore = function() {
  var _emitter = new Dispatcher()
  var _nextId = 0
  var _todos = immutable({})

  dispatcher.register( function( payload ) {
    var originalTodos = _todos
    
    switch( payload.type ) {
      case 'SEED_TODOS':
        // just clobber the old one rather than piecemeal updating
        _todos = immutable( payload.todos )
        // go through the seed and set _nextId
        // appropriately so that creating new todos
        // doesn't override ones from the seed
        for( var i in _todos ) { _nextId = Math.max( _nextId+1, _todos[i].id ) }
        break
      case 'CREATE_TODO':
        payload.todo.id = _nextId++
        var patches = {}
        patches[payload.todo.id] = { $set: payload.todo }
        _todos = update( _todos, patches )
        break
      case 'REMOVE_TODO':
        _todos = update( _todos, { $unset: payload.todo.id } )
        break
      case 'UPDATE_TODO':
        var patches = {}
        patches[payload.todo.id] = { $merge: {} }
        for( var key in payload.todo ) {
          patches[payload.todo.id]['$merge'][key] = payload.todo[key]
        }
        _todos = update( _todos, patches )
        break
    }

    // notify anyone who cares that the store has updates
    // but only IF there are updates
    if( originalTodos !== _todos ) {
      _emitter.dispatch()
    }
  } )

  return {
    getTodos: function() { return _todos },
    addListener: _emitter.register,
    removeListener: _emitter.unregister
  }
}


// next, let's wrap TodoApp and TodoItem so
// that they memoize their previous render, and
// only bother re-running if their props have changed
function pure( componentFn, immutableProp ) {
  // keep track of props and render results
  var memoizedRenders = {}
  
  return function( props ) {
    // the prop we are considering ourselves pure 'against'
    var prop = props[immutableProp]
    
    // attempt to find a memoized render
    // for this prop and id
    var memoized = memoizedRenders[prop.id]

    // if we found one and the memoized value is
    // the exact same object as the new prop
    // then we don't need to render because the
    // result would be the same!
    if( memoized && memoized.value === prop ) {
      return memoized.result
    }
    // otherwise, render and store the results
    // for later lookup
    else {
      var result = componentFn( props )
      memoizedRenders[prop.id] = { value: prop, result: result }
      return result
    }
  }
}

// wrap TodoApp as being pure on 'todos'
// wrap TodoItem as being pure on 'todo'
//   by pure 'on', i mean, this component will
//   render the same thing given the same prop
//   with this key. this could be pretty easily
//   extended to work with multiple props
TodoApp = pure( TodoApp, 'todos' )
TodoItem = pure( TodoItem, 'todo' )



//
// Main Application
//   Dispatcher, TodoStore and TodoActions,
//   TodoApp and TodoItem
//   are from ryanfunduk.com/articles/react-from-scratch
//

window.dispatcher = new Dispatcher()
window.todoStore = new TodoStore()
window.todoActions = new TodoActions()

dispatcher.register( function( payload ) {
  //console.log( "ACTION: " + JSON.stringify(payload) )
} )

// the element we want to render into
var target = document.getElementById('mount')

// the function that re-renders the whole app
function tick() {
  render(
    dom( TodoApp, { todos: todoStore.getTodos() } ),
    target
  )
}

// seed todos and trigger an update
todoActions.listTodos()

// when the store changes, re-render
todoStore.addListener( tick )

// first render
tick()


function shallowCopy( a ) {
  if( Array.isArray( a ) ) {
    return [].concat(a)
  }
  else if( a && typeof(a) == 'object' ) {
    var newA = {}
    for( var k in a ) { newA[k] = a[k] }
    return newA
  }
  else {
    return a
  }
}

function immutable( obj ) {
  // already immutable!
  if( obj && obj.hasOwnProperty('__immutable') ) {
    return obj
  }
  
  var newObj

  if( Array.isArray( obj ) ) {
    newObj = []
    
    // first make all elements immutable
    for( var i in obj ) {
      newObj[i] = immutable( obj[i] )
    }
    
    // then disable all mutating methods of the array itself
    var unsafe = [ "push", "pop", "sort", "splice",
                   "shift", "unshift", "reverse" ]
    var fail = function() {
      throw new Error("Cannot modify immutable object")
    }
    unsafe.forEach( function( fn ) {
      Object.defineProperty( newObj, fn, { value: fail } )
    } )
  }
  else if( obj && typeof( obj ) == 'object' ) {
    // make all values in the object immutable
    newObj = {}
    for( var i in obj ) {
      newObj[i] = immutable( obj[i] )
    }
  }
  else {
    // primitive
    return obj
  }
  
  // add 'already immutable' property
  Object.defineProperty( newObj, '__immutable', { /*defaults*/ } )
  // prevent any more edits of any kind
  return Object.freeze( newObj )
}

function update( obj, updates ) {
  // commands we know how to perform
  var COMMANDS = [
    '$push', '$unshift', '$splice',
    '$merge', '$set', '$unset'
  ]
  
  // check if we're attempting a command right now
  // if you pass more than one command, that's not
  // allow and the last one will simply be taken!
  var command, changes
  Object.keys( updates ).forEach( function( c ) {
    if( COMMANDS.indexOf(c) != -1 ) {
      command = c
      changes = updates[command]
    }
  } )
    
  // prepare the new object
  // shallow copy suffices here due to each
  // nested object being handled recursively
  // (each will be shallow copied)
  var next = shallowCopy( obj )

  if( command ) {
    switch( command ) {
      case '$merge':
        for( var key in changes ) { next[key] = changes[key] }
        break
      case '$splice':
        next.splice.apply(next, changes)
        break
      case '$push':
        next.push.apply(next, changes)
        break
      case '$unshift':
        next.unshift.apply(next, changes)
        break
      case '$set':
        return changes
      case '$unset':
        delete next[changes]
        break
      default:
        throw new Error("Unknown command: " + command)  
    }
  }
  
  for( var key in updates ) {
    if( COMMANDS.indexOf(key) == -1 ) {
      next[key] = update( next[key], updates[key] )
    }
  }
  
  return immutable( next )
}

function test() {
  document.getElementById('test').innerHTML = ''
  var a = {
    x: [
      1, 2,
      { m: [ 1, 2, null, { n: 5 } ],
        o: [ 'p', 'q', 'r' ] }
    ],
    y: [ 9, 10, 11, 'test' ],
    z: 5
  }
  log( "a =", a )
  var b = immutable( a )

  assertEqual( a, b, 'a == immutable(a)' )
  assertEqual( b, immutable(b), 'a == immutable(immutable(a))', true )

  try { b.x[2].m.push( 100 ) }
  catch( e ) { log( 'PASS', 'attempt mutation ->', e.message ) }

  var b0 = update( b, { z: { $set: 10 } } )
  assertEqual( b0.z, 10, '$set' )

  var b1 = update( b, { $set: 5 } )
  assertEqual( b1, 5, 'clobber $set' )

  var b2 = update( b, { x: { 2: { m: { 3: { $set: 'wow' } } } } } )
  assertEqual( b2.x[2].m[3], 'wow', 'deep $set' )
  
  var b3 = update( b, { $unset: 'x' } )
  assertEqual( b3.hasOwnProperty('x'), false, '$unset' )

  // quickly test pure array
  var c = [ 1, 2, 3 ]
  var d = immutable(c)
  var d1 = update( d, { $push: [4] } )
  assertEqual( d1[3], 4, 'array $push', true )

  var b4 = update( b, { y: { $push: [1] } } )
  assertEqual( b4.y, a.y.concat( [1] ), 'object $push' )

  var b5 = update( b, { y: { $unshift: [1] } } )
  assertEqual( b5.y, [1].concat(a.y), '$unshift' )

  var b6 = update( b, { $merge: { a: 1 } } )
  assertEqual( b6.a, 1, '$merge' )

  var b7 = update( b, { x: { $splice: [2, 1] } } )
  assertEqual( b7.x, [1, 2], '$splice' )

  var b8 = update( b, { x: { $set: 'x' } } )
  assertEqual( b8.y, b.y, 'sibling keys untouched', true )
  
  var b9 = update( b, { x: { m: { $set: 'nested' } } } )
  assertEqual( b9.x.o, b.x.o, 'nested siblings untouched', true )
  assertEqual( b9.y, b.y, 'unrelated siblings untouched', true )
  
  assertEqual( b, a, 'update(...) -> original unchanged' )

  a.x = 5
  assertEqual( a.x, 5, 'mutable a.x=' )

  // HELPERS
  function assertEqual( a, b, msg, identity ) {
    identity = identity || false
    msg = msg || 'ASSERT'
    if( !identity ) {
      a = JSON.stringify( a )
      b = JSON.stringify( b )
    }
    if( a === b ) {
      log( 'PASS', '<em>' + msg + '</em>' )
    }
    else {
      log( 'FAIL', '<em>' + msg + '</em> -> <small>(expected <strong>' + a + '</strong> to equal <strong>' + b + '</strong>)</small>' )
    }
  }

  function log( passFailInfo ) {
    var toLog = Array.prototype.slice.call(arguments)
    if( ['PASS','FAIL','INFO'].indexOf( passFailInfo.toUpperCase() ) == -1 ) {
      passFailInfo = 'INFO'
    }
    else {
      toLog = toLog.slice(1)
    }
    var parts = [
      '<strong>' + passFailInfo.toUpperCase() + '</strong>'
    ]
    for( var i in toLog ) {
      parts.push(
        typeof( toLog[i] ) == 'string' ?
          toLog[i] :
          JSON.stringify( toLog[i] )
      )
    }
    var line = document.createElement('li')
    line.classList.add( passFailInfo.toLowerCase() )
    line.innerHTML = parts.join( ' ' )
    document.getElementById('test').appendChild( line )
  }
}

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console