What is an idempotent operation?

前端 未结 15 1093
情话喂你
情话喂你 2020-11-22 03:27

What is an idempotent operation?

15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 03:58

    Just wanted to throw out a real use case that demonstrates idempotence. In JavaScript, say you are defining a bunch of model classes (as in MVC model). The way this is often implemented is functionally equivalent to something like this (basic example):

    function model(name) {
      function Model() {
        this.name = name;
      }
    
      return Model;
    }
    

    You could then define new classes like this:

    var User = model('user');
    var Article = model('article');
    

    But if you were to try to get the User class via model('user'), from somewhere else in the code, it would fail:

    var User = model('user');
    // ... then somewhere else in the code (in a different scope)
    var User = model('user');
    

    Those two User constructors would be different. That is,

    model('user') !== model('user');
    

    To make it idempotent, you would just add some sort of caching mechanism, like this:

    var collection = {};
    
    function model(name) {
      if (collection[name])
        return collection[name];
    
      function Model() {
        this.name = name;
      }
    
      collection[name] = Model;
      return Model;
    }
    

    By adding caching, every time you did model('user') it will be the same object, and so it's idempotent. So:

    model('user') === model('user');
    

提交回复
热议问题