toHash

Преобразовать индексированный массив в ассоциативный, где ключами для элементов являются значения их поля name. Использовать reduce.

by Anastasia Sharko

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.4.5/mocha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.4.5/mocha.min.css">
<div id="mocha">
</div>
<script>
  mocha.setup('bdd');
  var assert = chai.assert;
  var expect = chai.expect;
</script>
<script>

  describe("toHash", function() {
    before(function () {
      chai.config.includeStack = false;
    });
    describe('формат', function(){
      it("объявлена", function() {
        assert.isFunction(window.toHash);
      });
      it("принимает 1 аргумент", function() {
        assert.equal(window.toHash.length, 1);
      });
    });
    function installProxy(target, method, pre, post){
    	var proxy = target[method] = function(delegate){
      	return function(){
        	if(pre) pre.apply(this, arguments);
        	var result = delegate.apply(this, arguments);
          if(post) post.apply(this, [result].concat(Array.apply(0, arguments)));
          return result;
        }
      }(target[method]);
      if(pre) {
      	proxy.pre = pre;
        pre.proxy = proxy;
      }
      if(post){
      	proxy.post = post;
        post.proxy = proxy;
      }
      return proxy;
    }
    if(typeof(window.toHash) == 'function'){
      describe('проверки', function(){

        const ALPHA = symbolRange('a', 'z');
        const DIGITS = symbolRange('0', '9');;
        const ALPHANUM = ALPHA.concat(DIGITS);
        function symbolRange(start, end){
          start = start.charCodeAt(0);
          end = end.charCodeAt(0);
          var result = [];
          while(start <= end)
            result.push(String.fromCharCode(start++));
          return result;
        }
        function pickRandomly(range){
          return range[~~(Math.random() * range.length)];
        }
        function randomAlphaNum(length){
          var result = pickRandomly(ALPHA);
         ...

JavaScript

function toHash(array){
	var a = {};
  var b = array.reduce(function(x,y){
  a[y.name] = y;
  return a;
  }, {});
  return b;
}
 /* можно и так: 
 function toHash(array){
 	array.forEach(function(y)
 	a[y.name] = y;
  return a;
 )}