The codegolf object

14

1

Imagine this, we have an environment with a global scope containing just a single object, called codegolf. This object has a single child called stackexchange, which has a property called com.
Accessing this property would look like codegolf.stackexchange.com.

The challenge

The input of your program/function will be a string trying to access a property on the global scope. Whenever this property is found, you shall print/return a truthy value. If the property isn't found, a falsy value shall be printed/returned. The catch: when you try to access a property on a non-existant object, your program should throw any kind of error¹.

To make things a bit easier, you may assume that input will always be [a-z.], it will never be empty, it will never have repeating .'s and it will never start or end with a .. So codegolf. is an invalid input.

Test cases

codegolf.stackexchange.com => 1 // or any other truthy value
codegolf.stackexchange.net => 0 // or any other falsy value
codegolf.stackexchange => 1
codegolf.foo => 0
codegolf => 1
foo => 0
codegolf.com => 0
codegolf.constructor => 0

codegolf.foo.bar => Error (since foo is undefined)
codegolf.stackexchange.com.foo => Error (since com is a value, not an object)
codegolf.stackexchange.com.foo.bar => Error
foo.stackexchange.com => Error
foo.bar => Error
foo.bar.baz => Error

This is , shortest code in bytes wins

¹ if (and only if) your language of choice doesn't support errors at all, you must output something which makes it clear that this is an error. For example, if you use 1 for truthy and 0 for falsy, you may use "e" for an error. Be consistent in your return values and explain the behaviour in your post.

Bassdrop Cumberwubwubwub

Posted 2016-11-30T09:45:11.517

Reputation: 5 707

1I feel like foo => Error would be more appropriate. – Magic Octopus Urn – 2016-11-30T15:13:22.660

request to add codegolf.com to the test cases to rule out codegolf(.stackexchange)?(.com)?$ type checks – colsw – 2016-11-30T15:21:02.440

Another missing test case: foo.stackexchange.com – Jamie – 2016-11-30T15:22:37.033

@carusocomputing Nope. Think about JavaScript. foo would return undefined, but it wouldn't throw an error. foo.bar would throw an error because foo is not defined. – mbomb007 – 2016-11-30T16:17:16.930

@mbomb007 I mean, for Javascript yeah, for many other languages, that's not the case. – Magic Octopus Urn – 2016-11-30T16:48:01.613

1@carusocomputing True, but you can't say it's "more appropriate", when it makes sense both ways. codegolf.foo => 0, so foo => 0. – mbomb007 – 2016-11-30T16:52:42.527

Answers

8

JavaScript, 135 bytes

v=>(c=(p,i)=>new Proxy({}, {get:(o,q)=>(r=q==p[i]?c(p,i+1):o.$,i==3?r||z:r)}),x=c(["codegolf","stackexchange","com"],0),!!eval("x."+v))

Reworked the first attempt to prevent builtin keys being accessible, at this point its going to be better to use a different approach, but hey!

Returns true for valid, false for missing and errors on error.

Skorm

Posted 2016-11-30T09:45:11.517

Reputation: 91

4

JavaScript (ES6), 87 bytes

Returns false/ true or throws ReferenceError.

s=>s.split`.`.map((w,i)=>e|['codegolf','stackexchange','com'][i]!=w&&e++,e=0)&&e>1?X:!e

let f =
    
s=>s.split`.`.map((w,i)=>e|['codegolf','stackexchange','com'][i]!=w&&e++,e=0)&&e>1?X:!e

console.log(f('codegolf.stackexchange.com')); // => true
console.log(f('codegolf.stackexchange.net')); // => false
console.log(f('codegolf.stackexchange'));     // => true
console.log(f('codegolf.foo'));               // => false
console.log(f('codegolf'));                   // => true
console.log(f('foo'));                        // => false
console.log(f('codegolf.com'));               // => false

console.log(f('codegolf.foo.bar'));           // => Error

Probabilistic version, 78 bytes (non-competing)

Because all properties are guaranteed to match [a-z], we can give this a try:

s=>s.split`.`.map((w,i)=>e|[162,6,2][i]-parseInt(w,36)%587&&e++,e=0)&&e>1?X:!e

Apart from the fact that 587 is a prime and leads to rather short values for the words we are interested in, this is a rather random modulo choice.

Although it does pass all test cases, it is of course likely to return false-positives.

let f =
    
s=>s.split`.`.map((w,i)=>e|[162,6,2][i]-parseInt(w,36)%587&&e++,e=0)&&e>1?X:!e

console.log(f('codegolf.stackexchange.com')); // => true
console.log(f('codegolf.stackexchange.net')); // => false
console.log(f('codegolf.stackexchange'));     // => true
console.log(f('codegolf.foo'));               // => false
console.log(f('codegolf'));                   // => true
console.log(f('foo'));                        // => false
console.log(f('codegolf.com'));               // => false

console.log(f('codegolf.foo.bar'));           // => Error

Arnauld

Posted 2016-11-30T09:45:11.517

Reputation: 111 334

3

Batch, 269 231 bytes

@echo off
set/ps=
set w=1codegolf
for %%a in (%s:.= %)do call:l %%w
echo %w:~0,1%
exit/b
:g
if
:l
if %w:~-1%==. goto g
if not %1==%w% set w=0.&exit/b
set w=1com
if %1==com set w=1.
if %1==codegolf set w=1stackexchange

Takes input on STDIN; throws a syntax error for an invalid property. Works by using w as a state machine. If w ends with a . this means that the next property access is invalid. Edit: Saved 17 bytes by using the syntax error to abort the batch script. Saved 21 bytes by realising that one of my assignments could be unconditional.

Neil

Posted 2016-11-30T09:45:11.517

Reputation: 95 035

2

Javascript, 84 82 bytes

Not short enough to win, but since I am a beginner I thought it would be fun to share it. Maybe someone has a suggestion for improvement.

s=>s.split`.`.length>3&&e||!!eval('codegolf={stackexchange:{com:true}};window.'+s)

It passes all the tests in the question, returns true for existing value, false for non-existent and it throws an error if you try to get a property of a non-existent or non-object variable. However I now realize that this solution has some issues as well. As pointed out by @Florent in the comments it returns true when string prototype properties such as .toString are called.

Edit: 2 bytes shorter thanks to @MamaFunRoll

Test snippet:

var f =
s=>s.split`.`.length>3&&e||!!eval('codegolf={stackexchange:{com:true}};window.'+s)

console.log(f('codegolf.stackexchange.com')) //true
console.log(f('codegolf.stackexchange.net')) //false
console.log(f('codegolf.stackexchange')) //true
console.log(f('codegolf.foo')) //false
console.log(f('codegolf')) //true
console.log(f('foo')) //false
console.log(f('codegolf.com')) //false

console.log(f('codegolf.foo.bar')) // TypeError
console.log(f('codegolf.stackexchange.com.foo')) //ReferenceError
console.log(f('codegolf.stackexchange.com.foo.bar')) //ReferenceError
console.log(f('foo.stackexchange.com')) // TypeError
console.log(f('foo.bar')) // TypeError
console.log(f('foo.bar.baz')) // TypeError

tjespe

Posted 2016-11-30T09:45:11.517

Reputation: 121

{ "message": "Unable to get property 'bar' of undefined or null reference", "filename": "http://stacksnippets.net/js", "lineno": 1, "colno": 37 }

– RosLuP – 2016-11-30T20:41:11.087

@RosLuP I am not sure what you mean by this comment. The function is supposed to throw an error for codegolf.foo.bar – tjespe – 2016-11-30T20:43:44.837

than all ok for all you... but for me "throw" error is one error – RosLuP – 2016-11-30T20:50:07.720

@RosLuP yes, that's because all JavaScript scripts stops on the first error – tjespe – 2016-11-30T21:00:58.577

1.split('.') -> split\.`` Welcome! – Mama Fun Roll – 2016-12-01T06:57:33.343

1Does not work. f("codegolf.toString") should return false. f("codegolf.toString.toString") should throw. – Florent – 2016-12-01T08:24:24.453

1

C, 98 112 113 bytes

f(char*a){char*c="codegolf.stackexchage.com";while(*c&&*c==*a)++a,++c;return strchr(a,46)?*(a=0):!(*a|*c&*c-46);}

ungolfed

f(char*a){char*c="codegolf.stackexchage.com";
          while(*c&&*c==*a)++a,++c;
          return strchr(a,46)?*(a=0):!(*a|*c&*c-46);
         }

f(codegolf.stackexchage.com)=1
f(codegolf.stackexchage.net)=0
f(codegolf.stackexchage)=1
f(codegolf.foo)=0
f(codegolf)=1
f(foo)=0

for the below it has to seg fault

f(codegolf.stackexchage.com.foo)
f(foo.bar)
f(foo.bar.baz)
f(codegolf.foo.bar)
f(foo.v)

RosLuP

Posted 2016-11-30T09:45:11.517

Reputation: 3 036

What about the error(s)? f(codegolf.stackexchage.com.foo) should error, not return 0, for example. – Jonathan Allan – 2016-11-30T14:15:26.347

i don't fully understand why my C language entry that is less characters than C#,Java,Javascript, python,Bathc,Javascript, has less points (-1) than everyone – RosLuP – 2016-11-30T22:40:09.573

Maybe they downvoted before you fixed the codegolf.stackexchange.com.foo error, or they don't realize you fixed it. Edit the header to # C, <strike>98</strike> 112 bytes # to make it clear that you modified it. – Ray – 2016-11-30T23:30:18.377

3 is not an error either, in C it is what is considered a "truthy" value. See this meta post, and this code. – Jonathan Allan – 2016-12-01T00:06:20.523

I not use exceptions, in case of error program return 3. Should be -1 but 3 save 1 character – RosLuP – 2016-12-01T04:05:25.413

@Ray thank you. In C the prefered way it is not exception, as in the not good languages, but it return one error code to the caller (as it has to be) – RosLuP – 2016-12-01T04:10:43.753

If people insist on a fatal exception, you could return 1/0 instead of 3 to raise a floating point exception signal. But in a real program, returning a separate error code for separate types of errors, as you do here, is the Right Thing to do in C. And since raising SIGFPE is mandated by the OS and hardware, not the language, it's my opinion that what you do here is both within the letter and spirit of the problem description. – Ray – 2016-12-01T22:06:01.037

1/0 return 1, *0 is not allowed... 1/0.0 not seg fault. What seg fault is *(a=0) or *(char*)0 – RosLuP – 2016-12-02T08:39:35.927

1

JavaScript, 173 bytes

function d(a){var b="codegolf",u="stackexchange",c=a.split("."),e="e";return c.length==1?c[0]==b:c.length==2?c[0]==b?c[1]==u:e:c.length==3?c[0]==b?c[1]==u?c[2]=="com":e:e:e}

Works with IE 10, so should work on major modern browsers.

Try it here (+ ungolfed)

Trying

Posted 2016-11-30T09:45:11.517

Reputation: 11

2Could be way more golfed: d=(a,b="codegolf",u="stackexchange",c=a.split\.`,e="e")=>c[l="length"]==1?c[0]==b:c[l]==2?c[0]==b?c[1]==u:e:c[l]==3?c[0]==b?c[1]==u?c[2]=="com":e:e:e` (149 bytes) – Florent – 2016-11-30T15:28:31.943

@Florent I think he's trying to allow it to work on IE10 etc., so no arrow functions or default parameters. – Conor O'Brien – 2016-11-30T16:23:18.370

+1 for a great answer, +1 for e="e", but -1 for IE 10. – NoOneIsHere – 2016-11-30T18:59:32.110

1

C#, 155 bytes

Wasn't going to be the shortest but thought it would be fun give it a go in C#...

bool f(string s){var a=s.Split('.');int e=0,l=a.Length-1,i=l;for(;0<=i;i--){e+=a[i]!=new[]{"codegolf","stackexchange","com"}[i]?i<l?s[-1]:1:0;}return e<1;}
  • Splits the string and reverse iterates through the result.
  • A non matching element more than 1 iteration deep, errors (throwing an IndexOutOfRangeException by accessing a char at -1 position in the string).
  • Otherwise, returns false if any elements didn't match.

.NET Fiddle

Jamie

Posted 2016-11-30T09:45:11.517

Reputation: 111

1

Ruby, 84 80 bytes

Anonymous function which returns true or false, or divides by zero to raise error:

->s{k=1;s.split(?.).zip(%w[codegolf stackexchange com]){|i,o|1/0if !k;k=i==o};k} 

Try it online

daniero

Posted 2016-11-30T09:45:11.517

Reputation: 17 193

0

Java, 187 138 bytes

Version 2.0(138 bytes): Idea shamelessly stolen from @Jamie.

l->{for(String []a=l.split,int l=i=a.length-1,e=0;i>=0;e+=a[i]!=new String[]{"codegolf","stackexchange","com"}[i]?i<l?s[-1]:1:0)return e;}

Version 1.0(187 bytes):

l->{String[]a=l.split(".");return a[0].equals("codegolf")?(a.length<2?1:(a[1].equals("stackexchange")?(a.length<3?1:(a[2].equals("com")?1:0)):(a.length<3?0:a[-1]))):(a.length<2?0:a[-1]);}

Explanation of the return part:

return a[0].equals("codegolf")?(a.length<2?1:(a[1].equals("stackexchange")?(a.length<3?1:(a[2].equals("com")?1:0)):(a.length<3?0:a[-1]))):(a.length<2?0:a[-1]);
return                                                                                                                                                        ;
       a[0].equals("codegolf")?                                                                                                          :
                               (a.length<2? :                                                                                           ) (a.length<2? :     )
                                           1 (a[1].equals("stackexchange")?                                       :                    )              0 a[-1]
                                                                           (a.length<3? :                        ) (a.length<3? :     )
                                                                                       1 (a[2].equals("com")? : )              0 a[-1]
                                                                                                             1 0

Roman Gräf

Posted 2016-11-30T09:45:11.517

Reputation: 2 915