faulty eachSlice method

14 views
Skip to first unread message

petrob

unread,
Jul 25, 2012, 4:59:54 AM7/25/12
to prototype-s...@googlegroups.com
The Enumerable.eachSlice method , or the documentation is faulty!  Just adjust the src attribute to point to your copy of Prototype and try this to see why!

It's because the slice native array method always returns an array every time it's called, so the output will never be:
[['Sunny', 'Audrey', 'Matt'], ['Amelie', 'Will']], but an array with two undefined values!

.Either the iterator function should act accordingly as in the oroginal inGroupsOf method, or preferably the two methods should be adjusted for something like the ones below:
Probably you will never use these methods, but they are parts of the public interface, so they should work properly!

  function eachSlice(number, iterator, context) {
    var index = -number, slices = [], array = this.toArray();
    if (number < 1) return array;
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number).collect(iterator, context));
    return slices;
  }

function inGroupsOf(number, fillWith, iterator){
    fillWidth = Object.isUndefined(fillWith)? null : fillWith;
    var tmp = this.eachSlice(number, iterator), res = [];
   
    tmp.each(function(arr, index){
     
          while(arr.length < number){
            arr.push(fillWith);           
          }
          res.push(arr);
      });
      return res; 
};
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>  
 <meta http-equiv="Content-type" content="text/html;charset=iso-8859-1" />
    <title>Faulty eacSlice method test</title>


<script type="text/javascript" language="javascript" src="prototype_scripta/prototype_1_7.js"></script>
<script type="text/javascript" language="javascript">
   
    var students = [
  { name: 'Sunny', age: 20 },
  { name: 'Audrey', age: 21 },
  { name: 'Matt', age: 20 },
  { name: 'Amelie', age: 26 },
  { name: 'Will', age: 21 }
];
 var student_names = students.eachSlice(3, function(student, count) {
  if(typeof student.name == 'undefined'){alert(count + ' -student is an array!!');}
  return student.name;
});
for(var i = 0; i < student_names.length; i++){
    alert(typeof student_names[i]);
 }
 
</script>

</head>
<body>
   <div>Nothing to see here.</div>
</body>
</html>
Reply all
Reply to author
Forward
0 new messages