15
\$\begingroup\$

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.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ I feel like foo => Error would be more appropriate. \$\endgroup\$ Nov 30, 2016 at 15:13
  • \$\begingroup\$ request to add codegolf.com to the test cases to rule out codegolf(.stackexchange)?(.com)?$ type checks \$\endgroup\$
    – colsw
    Nov 30, 2016 at 15:21
  • \$\begingroup\$ Another missing test case: foo.stackexchange.com \$\endgroup\$
    – Jamie
    Nov 30, 2016 at 15:22
  • \$\begingroup\$ @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. \$\endgroup\$
    – mbomb007
    Nov 30, 2016 at 16:17
  • 2
    \$\begingroup\$ @carusocomputing True, but you can't say it's "more appropriate", when it makes sense both ways. codegolf.foo => 0, so foo => 0. \$\endgroup\$
    – mbomb007
    Nov 30, 2016 at 16:52

9 Answers 9

8
\$\begingroup\$

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.

\$\endgroup\$
0
4
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
6
  • \$\begingroup\$ { "message": "Unable to get property 'bar' of undefined or null reference", "filename": "stacksnippets.net/js", "lineno": 1, "colno": 37 } \$\endgroup\$
    – user58988
    Nov 30, 2016 at 20:41
  • \$\begingroup\$ @RosLuP I am not sure what you mean by this comment. The function is supposed to throw an error for codegolf.foo.bar \$\endgroup\$
    – tjespe
    Nov 30, 2016 at 20:43
  • \$\begingroup\$ than all ok for all you... but for me "throw" error is one error \$\endgroup\$
    – user58988
    Nov 30, 2016 at 20:50
  • 1
    \$\begingroup\$ .split('.') -> split`.` Welcome! \$\endgroup\$ Dec 1, 2016 at 6:57
  • 1
    \$\begingroup\$ Does not work. f("codegolf.toString") should return false. f("codegolf.toString.toString") should throw. \$\endgroup\$
    – Florent
    Dec 1, 2016 at 8:24
1
\$\begingroup\$

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)

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Could 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) \$\endgroup\$
    – Florent
    Nov 30, 2016 at 15:28
  • \$\begingroup\$ @Florent I think he's trying to allow it to work on IE10 etc., so no arrow functions or default parameters. \$\endgroup\$ Nov 30, 2016 at 16:23
  • \$\begingroup\$ +1 for a great answer, +1 for e="e", but -1 for IE 10. \$\endgroup\$ Nov 30, 2016 at 18:59
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
8
  • \$\begingroup\$ What about the error(s)? f(codegolf.stackexchage.com.foo) should error, not return 0, for example. \$\endgroup\$ Nov 30, 2016 at 14:15
  • \$\begingroup\$ 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 \$\endgroup\$
    – user58988
    Nov 30, 2016 at 22:40
  • \$\begingroup\$ 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. \$\endgroup\$
    – Ray
    Nov 30, 2016 at 23:30
  • \$\begingroup\$ 3 is not an error either, in C it is what is considered a "truthy" value. See this meta post, and this code. \$\endgroup\$ Dec 1, 2016 at 0:06
  • \$\begingroup\$ I not use exceptions, in case of error program return 3. Should be -1 but 3 save 1 character \$\endgroup\$
    – user58988
    Dec 1, 2016 at 4:05
0
\$\begingroup\$

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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.