• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Problem with partial functions

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is something I don't understand about the below javascript. I executed the following code from Secrets of the Javascript Ninjas:

<!DOCTYPE html>
<html>
<head>
<title>Listing 5.12</title>
<script type="text/javascript" src="../scripts/assert.js"></script>
<link href="../styles/assert.css" rel="stylesheet" type="text/css">
</head>
<body>
<script type="text/javascript">

Function.prototype.partial = function() {
var fn = this, args = Array.prototype.slice.call(arguments);
return function() {
var arg = 0;
for (var i = 0; i < args.length && arg < arguments.length; i++) {
if (args[i] === undefined) {
args[i] = arguments[arg++];
}
}
return fn.apply(this, args);
};
};

Math.maxAbove500 = Math.max.partial(500);

assert(Math.maxAbove500(3,4,1,6) == 500, "Max of 500, 3, 4, 1, 6 is 500"); //#4
assert(Math.maxAbove500(3,4,11223,1,6) == 11223, "Max of 500, 3, 4, 11223, 1, 6 is 11223"); //#4

</script>
</body>
</html>

When it runs, the first assert works and returns true, but when the second assert runs it return false. It seems it should return true also since 11223 is the max in the array. Is there something I don't understand about this function or is there some sort of error? I'm running this in Chrome ver. 31.0.1650.57.
 
Ranch Hand
Posts: 59
6
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When calling partial, then you need to add some undefined values to act as placeholders for the values you pass in later:



The function can only be called once though because it modifies args in the outer scope. To use it multiple times, you need to make a copy:



or you can define partial without requiring undefined values, then you can call it like in your original code:

 
Then YOU must do the pig's work! Read this tiny ad. READ IT!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic