repl.it
@cmarmar/

Alternate and Twice

ES6

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Create the functions alternate and twice. The `alternate` function returns an object that returns a value every other time it is called.  The `twice` function can only invoke the function passed to it a total of two times.   This should sound a lot like the `once` function but with a twist!


const alternate = (cb) => {
  let calls = 0
  return () => {
    calls++
    if(calls%2===1){
      return cb()
    }
  }
}

let message = ''

let sayHeyOnAlts = alternate(()=> message+= 'hey')

sayHeyOnAlts()
console.log(message)
sayHeyOnAlts()
console.log(message)
sayHeyOnAlts()
console.log(message)
sayHeyOnAlts()
console.log(message)

const twice = (cb) => {
  let timesRun = 0
  return () => {
    if(timesRun < 2){
      timesRun++
      return cb()
    }
    else return 0
  }
}

let fourtyFive = 5

let onlyTwice = twice(()=> fourtyFive*=3)

onlyTwice()
console.log(fourtyFive)
onlyTwice()
console.log(fourtyFive)
onlyTwice()
console.log(fourtyFive)
onlyTwice()
console.log(fourtyFive)
Babel Compiler v6.4.4 Copyright (c) 2014-2015 Sebastian McKenzie