0

I need to inject some piece of code into a function, to prevent DRY. Here is an example of my code.

angular.module('crypt', ['ui.chart'])
.controller('MainCtrl', ['$http', function($http) {
  var self = this;
  self.encrypt = function() {
    $http.post('/encrypt',
             {'crypt': {'text': self.plain, 'shift':self.rot}})
    .then(function(response) {
      self.encrypted = response.data.encrypted;
      self.plain = '';
    // reusable function goes here
    // var frequencyArr = response.data.frequency;
    // var frequencyArrLength = frequencyArr.length;
    // if (frequencyArrLength) self.cryptChart = [frequencyArr];
    });
  };
  self.decrypt = function() {
    $http.post('/decrypt',
           {'crypt': {'text': self.encrypted, 'shift':self.rot}})
    .then(function(response) {
      self.plain = response.data.plain;
      self.encrypted = '';
      // and here 
      // the stuff to become a function
      var frequencyArr = response.data.frequency;
      var frequencyArrLength = frequencyArr.length;
      if (frequencyArrLength) self.cryptChart = [frequencyArr]; 
    });
  };
  // ...
}])

So how do I pack that 3 lines and make a reusable function in Angular way?

1 Answer 1

3

Maybe like this:

angular.module('crypt', ['ui.chart'])
.controller('MainCtrl', ['$http', function($http) {
  var self = this;

  function cryption(decrypt, callBack) {
    $http.post(
      decrypt ? '/decrypt' : '/encrypt', 
      {crypt: {text: decrypt ? self.encrypted : self.plain, shift: self.rot }})
    .then(callBack);
  }

  function cryptChart(response) {
    var frequencyArr = response.data.frequency;
    var frequencyArrLength = frequencyArr.length;
    if (frequencyArrLength) // can be simplyfied to response.data.frequency.length
      self.cryptChart = [frequencyArr];
  }

  self.encrypt = cryption(false, function(response) {
      self.encrypted = response.data.encrypted;
      self.plain = '';

      cryptChart(response);    
  });
  self.decrypt = cryption(true, function(response) {
      self.plain = response.data.plain;
      self.encrypted = '';

      cryptChart(response);
  });  
  // ...
}])

I went bit further and extracted the shared $http.post call into function as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.