Pure functions in EcmaScript

Oliver Hunt oliver at apple.com
Wed Nov 28 13:41:42 PST 2012


IIRC NaN is readonly, but you'd need to be able to guarantee the lexical scope between your function definition and the global object did have any shadowing :D

--Oliver

On Nov 28, 2012, at 1:32 PM, Axel Rauschmayer <axel at rauschma.de> wrote:

> Would returning NaN be impure (apart from running the risk of it having been changed to something different, globally)?
> 
> On Nov 28, 2012, at 21:35 , Oliver Hunt <oliver at apple.com> wrote:
> 
>> 
>> On Nov 28, 2012, at 12:25 PM, Waldemar Horwat <waldemar at google.com> wrote:
>> 
>>> On Wed, Nov 28, 2012 at 5:39 AM, Marius Gundersen <gundersen at gmail.com> wrote:
>>> On Wed, Nov 28, 2012 at 1:20 PM, Andreas Rossberg <rossberg at google.com> wrote:
>>> Second, due to the extremely impure nature of JavaScript, there aren't
>>> many useful pure functions you could even write. For example, your
>>> 'sum' function is not pure, because the implicit conversions required
>>> by + can cause arbitrary side effects.
>>> 
>>> Functions passed to the array methods map, reduce, filter, etc would be good candidates for pure/side-effect-free functions. These functions shouldn't alter any state; they should only return a new value based on the parameter they were sent.
>>> 
>>> You haven't addressed Andreas's point: Almost any function you write is nonpure, including your sum example. As a fun exercise, go ahead and write a pure version of your sum example.
>>> 
>>>     Waldemar
>> Here you go:
>> 
>> function sum(a, b) {
>>    var undefined;
>>    switch (typeof a) {
>>    case "number":
>>    case "string":
>>        break;
>>    default:
>>        return +undefined;
>>    }
>>    switch (typeof b) {
>>    case "number":
>>    case "string":
>>        break;
>>    default:
>>        return +undefined;
>>    }
>>    return a + b;
>> } 
>> 
>> 
>> 
>>> 
>>> _______________________________________________
>>> es-discuss mailing list
>>> es-discuss at mozilla.org
>>> https://mail.mozilla.org/listinfo/es-discuss
>> 
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
> 
> -- 
> Dr. Axel Rauschmayer
> axel at rauschma.de
> 
> home: rauschma.de
> twitter: twitter.com/rauschma
> blog: 2ality.com
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20121128/c1b3b41b/attachment.html>


More information about the es-discuss mailing list