Product Accessibility Magic

30 בJanuary 2017

אין תגובות

I wrote a few lines of code that provide infrastructure writing to prototype of functions of  JavaScript

Code Snippet
  1. //folowing the magic lines
  2. function doProductAccessabilityMagic(prodName, converters) {
  3.     iterateOnEachConverters(converters,
  4.     function addConvertToPrototype(sourceType, targetType, convertFunction) {
  5.         var nameOfConvertFunctionInPrototype = sourceType.name + targetType.name;
  6.         sourceType.prototype[nameOfConvertFunctionInPrototype] = convertFunction;
  7.     });
  8.     iterateOnEachConverters(converters,
  9.         function addProductToPrototype(sourceType, targetType, convertFunction) {
  10.             sourceType.prototype[prodName] = function () {
  11.                 var name = sourceType.name + targetType.name;
  12.                 var invoke = this[name];
  13.                 var convertVal = invoke.apply(this, arguments);
  14.                 return convertVal[prodName]();
  15.             }
  16.         });
  17. }
  18. function iterateOnEachConverters(converters, callback) {
  19.     for (prop in converters) {
  20.         callback(eval(prop), converters[prop][0], converters[prop][1]);
  21.     }
  22. }

I wrote a simple product knows how to calculate averages

But i  have added this product to some types of java script by the following lines

Code Snippet
  1. (function () {
  2.     // this is logic function
  3.     function Logic(sum, length) {
  4.         this.sum = sum;
  5.         this.length = length;
  6.         this.avgProduct = function () {
  7.             return this.sum / this.length;
  8.         }
  9.     }
  10.     // Enable you to navigate to product from this types Array,Function, Number
  11.     var converters = {
  12.         Array: [Logic, function convert() {
  13.             var sum = 0;
  14.             for (var i = 0; i < this.length  ; i++) {
  15.                 sum += this[i];
  16.             }
  17.             return new Logic(sum, this.length);
  18.         }],
  19.         Function: [Array, function convert() {
  20.             var data = this();
  21.             return data;
  22.         }],
  23.         Number: [Array, function convert(anotherNumber) {
  24.             return [this.valueOf(), anotherNumber];
  25.         }]
  26.     }
  27.     doProductAccessabilityMagic(“avgProduct”, converters);
  28. })();

Now the magic Happen Look at the use cases

Code Snippet
  1. // From here use cases
  2. console.log(“Example use case Array: “ + [1, 2, 56].avgProduct());
  3. console.log(“Example use case function: “ + (function () { return [1, 2, 56, 78] }).avgProduct());
  4. console.log(“Example use case two numbers: “ + (a = 40).avgProduct(50));

Good luck

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *